blob: bc8a7527c85bb183bde54cfe4a95e829269fb5fb [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///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000052/// If IgnoreDeprecated is set to true, this should not want about deprecated
53/// 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///
John McCall28a6aea2009-11-04 02:18:39 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000059 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
60 // If there were any diagnostics suppressed by template argument deduction,
61 // emit them now.
62 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
63 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
64 if (Pos != SuppressedDiagnostics.end()) {
65 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
66 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
67 Diag(Suppressed[I].first, Suppressed[I].second);
68
69 // Clear out the list of suppressed diagnostics, so that we don't emit
70 // them again for this specialization. However, we don't remove this
71 // entry from the table, because we want to avoid ever emitting these
72 // diagnostics again.
73 Suppressed.clear();
74 }
75 }
76
Chris Lattner4bf74fd2009-02-15 22:43:40 +000077 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000078 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
79 EmitDeprecationWarning(D, DA->getMessage(), Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000080
Chris Lattnera27dd592009-10-25 17:21:40 +000081 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000082 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
83 if (UA->getMessage().empty())
84 Diag(Loc, diag::err_unavailable) << D->getDeclName();
85 else
86 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000087 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000088 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
89 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000090
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000093 if (FD->isDeleted()) {
94 Diag(Loc, diag::err_deleted_function_use);
95 Diag(D->getLocation(), diag::note_unavailable_here) << true;
96 return true;
97 }
Douglas Gregorde681d42009-02-24 04:26:15 +000098 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000099
Anders Carlsson73067a02010-10-22 23:37:08 +0000100 // Warn if this is used but marked unused.
101 if (D->hasAttr<UnusedAttr>())
102 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
103
Douglas Gregor171c45a2009-02-18 21:56:37 +0000104 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000105}
106
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000107/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000108/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000109/// attribute. It warns if call does not have the sentinel argument.
110///
111void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000112 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000113 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000114 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000115 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000116
117 // FIXME: In C++0x, if any of the arguments are parameter pack
118 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000119 int sentinelPos = attr->getSentinel();
120 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000121
Mike Stump87c57ac2009-05-16 07:39:55 +0000122 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
123 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000124 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000125 bool warnNotEnoughArgs = false;
126 int isMethod = 0;
127 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
128 // skip over named parameters.
129 ObjCMethodDecl::param_iterator P, E = MD->param_end();
130 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
131 if (nullPos)
132 --nullPos;
133 else
134 ++i;
135 }
136 warnNotEnoughArgs = (P != E || i >= NumArgs);
137 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000138 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 // skip over named parameters.
140 ObjCMethodDecl::param_iterator P, E = FD->param_end();
141 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000148 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000149 // block or function pointer call.
150 QualType Ty = V->getType();
151 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000152 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000153 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
154 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000155 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
156 unsigned NumArgsInProto = Proto->getNumArgs();
157 unsigned k;
158 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
159 if (nullPos)
160 --nullPos;
161 else
162 ++i;
163 }
164 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
165 }
166 if (Ty->isBlockPointerType())
167 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000168 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000169 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000170 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000171 return;
172
173 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000174 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000175 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000176 return;
177 }
178 int sentinel = i;
179 while (sentinelPos > 0 && i < NumArgs-1) {
180 --sentinelPos;
181 ++i;
182 }
183 if (sentinelPos > 0) {
184 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000185 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000186 return;
187 }
188 while (i < NumArgs-1) {
189 ++i;
190 ++sentinel;
191 }
192 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000193 if (!sentinelExpr) return;
194 if (sentinelExpr->isTypeDependent()) return;
195 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000196
197 // nullptr_t is always treated as null.
198 if (sentinelExpr->getType()->isNullPtrType()) return;
199
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000200 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000201 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
202 Expr::NPC_ValueDependentIsNull))
203 return;
204
205 // Unfortunately, __null has type 'int'.
206 if (isa<GNUNullExpr>(sentinelExpr)) return;
207
208 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
209 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000210}
211
Douglas Gregor87f95b02009-02-26 21:00:50 +0000212SourceRange Sema::getExprRange(ExprTy *E) const {
213 Expr *Ex = (Expr *)E;
214 return Ex? Ex->getSourceRange() : SourceRange();
215}
216
Chris Lattner513165e2008-07-25 21:10:04 +0000217//===----------------------------------------------------------------------===//
218// Standard Promotions and Conversions
219//===----------------------------------------------------------------------===//
220
Chris Lattner513165e2008-07-25 21:10:04 +0000221/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
222void Sema::DefaultFunctionArrayConversion(Expr *&E) {
223 QualType Ty = E->getType();
224 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
225
Chris Lattner513165e2008-07-25 21:10:04 +0000226 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000227 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000228 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000229 else if (Ty->isArrayType()) {
230 // In C90 mode, arrays only promote to pointers if the array expression is
231 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
232 // type 'array of type' is converted to an expression that has type 'pointer
233 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
234 // that has type 'array of type' ...". The relevant change is "an lvalue"
235 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000236 //
237 // C++ 4.2p1:
238 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
239 // T" can be converted to an rvalue of type "pointer to T".
240 //
John McCall086a4642010-11-24 05:12:34 +0000241 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000242 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000243 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000244 }
Chris Lattner513165e2008-07-25 21:10:04 +0000245}
246
Douglas Gregorb92a1562010-02-03 00:27:59 +0000247void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
248 DefaultFunctionArrayConversion(E);
John McCallf3735e02010-12-01 04:43:34 +0000249
250 // C++ [conv.lval]p1:
251 // A glvalue of a non-function, non-array type T can be
252 // converted to a prvalue.
253 if (E->isGLValue()) {
John McCall34376a62010-12-04 03:47:34 +0000254 QualType T = E->getType();
255 assert(!T.isNull() && "r-value conversion on typeless expression?");
256
257 // Create a load out of an ObjCProperty l-value, if necessary.
258 if (E->getObjectKind() == OK_ObjCProperty) {
259 ConvertPropertyForRValue(E);
260 if (!E->isGLValue())
261 return;
262 }
263
264 // We don't want to throw lvalue-to-rvalue casts on top of
265 // expressions of certain types in C++.
266 if (getLangOptions().CPlusPlus &&
267 (E->getType() == Context.OverloadTy ||
268 T->isDependentType() ||
269 T->isRecordType()))
270 return;
271
John McCallca61b652010-12-04 12:29:11 +0000272 // The C standard is actually really unclear on this point, and
273 // DR106 tells us what the result should be but not why. It's
274 // generally best to say that void just doesn't undergo
275 // lvalue-to-rvalue at all.
276 if (T->isVoidType())
277 return;
278
Douglas Gregorb92a1562010-02-03 00:27:59 +0000279 // C++ [conv.lval]p1:
John McCallf3735e02010-12-01 04:43:34 +0000280 // [...] If T is a non-class type, the type of the prvalue is the
Douglas Gregorb92a1562010-02-03 00:27:59 +0000281 // cv-unqualified version of T. Otherwise, the type of the
John McCallf3735e02010-12-01 04:43:34 +0000282 // rvalue is T.
Douglas Gregorb92a1562010-02-03 00:27:59 +0000283 //
284 // C99 6.3.2.1p2:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000285 // If the lvalue has qualified type, the value has the unqualified
286 // version of the type of the lvalue; otherwise, the value has the
John McCall34376a62010-12-04 03:47:34 +0000287 // type of the lvalue.
288 if (T.hasQualifiers())
John McCallf3735e02010-12-01 04:43:34 +0000289 T = T.getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +0000290
291 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
292 E, 0, VK_RValue);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000293 }
294}
295
296
Chris Lattner513165e2008-07-25 21:10:04 +0000297/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000298/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000299/// sometimes surpressed. For example, the array->pointer conversion doesn't
300/// apply if the array is an argument to the sizeof or address (&) operators.
301/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000302Expr *Sema::UsualUnaryConversions(Expr *&E) {
303 // First, convert to an r-value.
304 DefaultFunctionArrayLvalueConversion(E);
305
306 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000307 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000308
309 // Try to perform integral promotions if the object has a theoretically
310 // promotable type.
311 if (Ty->isIntegralOrUnscopedEnumerationType()) {
312 // C99 6.3.1.1p2:
313 //
314 // The following may be used in an expression wherever an int or
315 // unsigned int may be used:
316 // - an object or expression with an integer type whose integer
317 // conversion rank is less than or equal to the rank of int
318 // and unsigned int.
319 // - A bit-field of type _Bool, int, signed int, or unsigned int.
320 //
321 // If an int can represent all values of the original type, the
322 // value is converted to an int; otherwise, it is converted to an
323 // unsigned int. These are called the integer promotions. All
324 // other types are unchanged by the integer promotions.
325
326 QualType PTy = Context.isPromotableBitField(E);
327 if (!PTy.isNull()) {
328 ImpCastExprToType(E, PTy, CK_IntegralCast);
329 return E;
330 }
331 if (Ty->isPromotableIntegerType()) {
332 QualType PT = Context.getPromotedIntegerType(Ty);
333 ImpCastExprToType(E, PT, CK_IntegralCast);
334 return E;
335 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000336 }
337
John McCallf3735e02010-12-01 04:43:34 +0000338 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000339}
340
Chris Lattner2ce500f2008-07-25 22:25:12 +0000341/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000342/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000343/// double. All other argument types are converted by UsualUnaryConversions().
344void Sema::DefaultArgumentPromotion(Expr *&Expr) {
345 QualType Ty = Expr->getType();
346 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000347
John McCall9bc26772010-12-06 18:36:11 +0000348 UsualUnaryConversions(Expr);
349
Chris Lattner2ce500f2008-07-25 22:25:12 +0000350 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000351 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000352 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000353}
354
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000355/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
356/// will warn if the resulting type is not a POD type, and rejects ObjC
357/// interfaces passed by value. This returns true if the argument type is
358/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000359bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
360 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000361 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000363 // __builtin_va_start takes the second argument as a "varargs" argument, but
364 // it doesn't actually do anything with it. It doesn't need to be non-pod
365 // etc.
366 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
367 return false;
368
John McCall8b07ec22010-05-15 11:32:37 +0000369 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000370 DiagRuntimeBehavior(Expr->getLocStart(),
371 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
372 << Expr->getType() << CT))
373 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000374
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000375 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000376 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000377 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
378 << Expr->getType() << CT))
379 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000380
381 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000382}
383
Chris Lattner513165e2008-07-25 21:10:04 +0000384/// UsualArithmeticConversions - Performs various conversions that are common to
385/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000386/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000387/// responsible for emitting appropriate error diagnostics.
388/// FIXME: verify the conversion rules for "complex int" are consistent with
389/// GCC.
390QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
391 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000392 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000393 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000394
395 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000396
Mike Stump11289f42009-09-09 15:08:12 +0000397 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000398 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000399 QualType lhs =
400 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000401 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000402 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000403
404 // If both types are identical, no conversion is needed.
405 if (lhs == rhs)
406 return lhs;
407
408 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
409 // The caller can deal with this (e.g. pointer + int).
410 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
411 return lhs;
412
John McCalld005ac92010-11-13 08:17:45 +0000413 // Apply unary and bitfield promotions to the LHS's type.
414 QualType lhs_unpromoted = lhs;
415 if (lhs->isPromotableIntegerType())
416 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000417 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000418 if (!LHSBitfieldPromoteTy.isNull())
419 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000420 if (lhs != lhs_unpromoted && !isCompAssign)
421 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000422
John McCalld005ac92010-11-13 08:17:45 +0000423 // If both types are identical, no conversion is needed.
424 if (lhs == rhs)
425 return lhs;
426
427 // At this point, we have two different arithmetic types.
428
429 // Handle complex types first (C99 6.3.1.8p1).
430 bool LHSComplexFloat = lhs->isComplexType();
431 bool RHSComplexFloat = rhs->isComplexType();
432 if (LHSComplexFloat || RHSComplexFloat) {
433 // if we have an integer operand, the result is the complex type.
434
John McCallc5e62b42010-11-13 09:02:35 +0000435 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
436 if (rhs->isIntegerType()) {
437 QualType fp = cast<ComplexType>(lhs)->getElementType();
438 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
439 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
440 } else {
441 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000442 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000443 }
John McCalld005ac92010-11-13 08:17:45 +0000444 return lhs;
445 }
446
John McCallc5e62b42010-11-13 09:02:35 +0000447 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
448 if (!isCompAssign) {
449 // int -> float -> _Complex float
450 if (lhs->isIntegerType()) {
451 QualType fp = cast<ComplexType>(rhs)->getElementType();
452 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
453 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
454 } else {
455 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000456 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000457 }
458 }
John McCalld005ac92010-11-13 08:17:45 +0000459 return rhs;
460 }
461
462 // This handles complex/complex, complex/float, or float/complex.
463 // When both operands are complex, the shorter operand is converted to the
464 // type of the longer, and that is the type of the result. This corresponds
465 // to what is done when combining two real floating-point operands.
466 // The fun begins when size promotion occur across type domains.
467 // From H&S 6.3.4: When one operand is complex and the other is a real
468 // floating-point type, the less precise type is converted, within it's
469 // real or complex domain, to the precision of the other type. For example,
470 // when combining a "long double" with a "double _Complex", the
471 // "double _Complex" is promoted to "long double _Complex".
472 int order = Context.getFloatingTypeOrder(lhs, rhs);
473
474 // If both are complex, just cast to the more precise type.
475 if (LHSComplexFloat && RHSComplexFloat) {
476 if (order > 0) {
477 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000478 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000479 return lhs;
480
481 } else if (order < 0) {
482 // _Complex float -> _Complex double
483 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000484 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000485 return rhs;
486 }
487 return lhs;
488 }
489
490 // If just the LHS is complex, the RHS needs to be converted,
491 // and the LHS might need to be promoted.
492 if (LHSComplexFloat) {
493 if (order > 0) { // LHS is wider
494 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000495 QualType fp = cast<ComplexType>(lhs)->getElementType();
496 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
497 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000498 return lhs;
499 }
500
501 // RHS is at least as wide. Find its corresponding complex type.
502 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
503
504 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000505 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000506
507 // _Complex float -> _Complex double
508 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000509 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000510
511 return result;
512 }
513
514 // Just the RHS is complex, so the LHS needs to be converted
515 // and the RHS might need to be promoted.
516 assert(RHSComplexFloat);
517
518 if (order < 0) { // RHS is wider
519 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000520 if (!isCompAssign) {
521 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
522 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
523 }
John McCalld005ac92010-11-13 08:17:45 +0000524 return rhs;
525 }
526
527 // LHS is at least as wide. Find its corresponding complex type.
528 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
529
530 // double -> _Complex double
531 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000532 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000533
534 // _Complex float -> _Complex double
535 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000536 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000537
538 return result;
539 }
540
541 // Now handle "real" floating types (i.e. float, double, long double).
542 bool LHSFloat = lhs->isRealFloatingType();
543 bool RHSFloat = rhs->isRealFloatingType();
544 if (LHSFloat || RHSFloat) {
545 // If we have two real floating types, convert the smaller operand
546 // to the bigger result.
547 if (LHSFloat && RHSFloat) {
548 int order = Context.getFloatingTypeOrder(lhs, rhs);
549 if (order > 0) {
550 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
551 return lhs;
552 }
553
554 assert(order < 0 && "illegal float comparison");
555 if (!isCompAssign)
556 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
557 return rhs;
558 }
559
560 // If we have an integer operand, the result is the real floating type.
561 if (LHSFloat) {
562 if (rhs->isIntegerType()) {
563 // Convert rhs to the lhs floating point type.
564 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
565 return lhs;
566 }
567
568 // Convert both sides to the appropriate complex float.
569 assert(rhs->isComplexIntegerType());
570 QualType result = Context.getComplexType(lhs);
571
572 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000573 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000574
575 // float -> _Complex float
576 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000577 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000578
579 return result;
580 }
581
582 assert(RHSFloat);
583 if (lhs->isIntegerType()) {
584 // Convert lhs to the rhs floating point type.
585 if (!isCompAssign)
586 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
587 return rhs;
588 }
589
590 // Convert both sides to the appropriate complex float.
591 assert(lhs->isComplexIntegerType());
592 QualType result = Context.getComplexType(rhs);
593
594 // _Complex int -> _Complex float
595 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000596 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000597
598 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000599 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000600
601 return result;
602 }
603
604 // Handle GCC complex int extension.
605 // FIXME: if the operands are (int, _Complex long), we currently
606 // don't promote the complex. Also, signedness?
607 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
608 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
609 if (lhsComplexInt && rhsComplexInt) {
610 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
611 rhsComplexInt->getElementType());
612 assert(order && "inequal types with equal element ordering");
613 if (order > 0) {
614 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000615 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000616 return lhs;
617 }
618
619 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000620 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000621 return rhs;
622 } else if (lhsComplexInt) {
623 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000624 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000625 return lhs;
626 } else if (rhsComplexInt) {
627 // int -> _Complex int
628 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000629 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000630 return rhs;
631 }
632
633 // Finally, we have two differing integer types.
634 // The rules for this case are in C99 6.3.1.8
635 int compare = Context.getIntegerTypeOrder(lhs, rhs);
636 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
637 rhsSigned = rhs->hasSignedIntegerRepresentation();
638 if (lhsSigned == rhsSigned) {
639 // Same signedness; use the higher-ranked type
640 if (compare >= 0) {
641 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
642 return lhs;
643 } else if (!isCompAssign)
644 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
645 return rhs;
646 } else if (compare != (lhsSigned ? 1 : -1)) {
647 // The unsigned type has greater than or equal rank to the
648 // signed type, so use the unsigned type
649 if (rhsSigned) {
650 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
651 return lhs;
652 } else if (!isCompAssign)
653 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
654 return rhs;
655 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
656 // The two types are different widths; if we are here, that
657 // means the signed type is larger than the unsigned type, so
658 // use the signed type.
659 if (lhsSigned) {
660 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
661 return lhs;
662 } else if (!isCompAssign)
663 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
664 return rhs;
665 } else {
666 // The signed type is higher-ranked than the unsigned type,
667 // but isn't actually any bigger (like unsigned int and long
668 // on most 32-bit systems). Use the unsigned type corresponding
669 // to the signed type.
670 QualType result =
671 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
672 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
673 if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
675 return result;
676 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000677}
678
Chris Lattner513165e2008-07-25 21:10:04 +0000679//===----------------------------------------------------------------------===//
680// Semantic Analysis for various Expression Types
681//===----------------------------------------------------------------------===//
682
683
Steve Naroff83895f72007-09-16 03:34:24 +0000684/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000685/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
686/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
687/// multiple tokens. However, the common case is that StringToks points to one
688/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000689///
John McCalldadc5752010-08-24 06:29:42 +0000690ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000691Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000692 assert(NumStringToks && "Must have at least one string!");
693
Chris Lattner8a24e582009-01-16 18:51:42 +0000694 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000695 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000696 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000697
Chris Lattner23b7eb62007-06-15 23:05:46 +0000698 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000699 for (unsigned i = 0; i != NumStringToks; ++i)
700 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000701
Chris Lattner36fc8792008-02-11 00:02:17 +0000702 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000703 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000704 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000705
706 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000707 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000708 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000709
Chris Lattner36fc8792008-02-11 00:02:17 +0000710 // Get an array type for the string, according to C99 6.4.5. This includes
711 // the nul terminator character as well as the string length for pascal
712 // strings.
713 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000714 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000715 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Chris Lattner5b183d82006-11-10 05:03:26 +0000717 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000718 return Owned(StringLiteral::Create(Context, Literal.GetString(),
719 Literal.GetStringLength(),
720 Literal.AnyWide, StrTy,
721 &StringTokLocs[0],
722 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000723}
724
Chris Lattner2a9d9892008-10-20 05:16:36 +0000725/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
726/// CurBlock to VD should cause it to be snapshotted (as we do for auto
727/// variables defined outside the block) or false if this is not needed (e.g.
728/// for values inside the block or for globals).
729///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000730/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000731/// up-to-date.
732///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000733static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000734 ValueDecl *VD) {
735 // If the value is defined inside the block, we couldn't snapshot it even if
736 // we wanted to.
737 if (CurBlock->TheDecl == VD->getDeclContext())
738 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner2a9d9892008-10-20 05:16:36 +0000740 // If this is an enum constant or function, it is constant, don't snapshot.
741 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
742 return false;
743
744 // If this is a reference to an extern, static, or global variable, no need to
745 // snapshot it.
746 // FIXME: What about 'const' variables in C++?
747 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000748 if (!Var->hasLocalStorage())
749 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner497d7b02009-04-21 22:26:47 +0000751 // Blocks that have these can't be constant.
752 CurBlock->hasBlockDeclRefExprs = true;
753
754 // If we have nested blocks, the decl may be declared in an outer block (in
755 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
756 // be defined outside all of the current blocks (in which case the blocks do
757 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000758 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
759 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000760
Douglas Gregor9a28e842010-03-01 23:15:13 +0000761 if (!NextBlock)
762 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000763
Chris Lattner497d7b02009-04-21 22:26:47 +0000764 // If we found the defining block for the variable, don't mark the block as
765 // having a reference outside it.
766 if (NextBlock->TheDecl == VD->getDeclContext())
767 break;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattner497d7b02009-04-21 22:26:47 +0000769 // Otherwise, the DeclRef from the inner block causes the outer one to need
770 // a snapshot as well.
771 NextBlock->hasBlockDeclRefExprs = true;
772 }
Mike Stump11289f42009-09-09 15:08:12 +0000773
Chris Lattner2a9d9892008-10-20 05:16:36 +0000774 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000775}
776
Chris Lattner2a9d9892008-10-20 05:16:36 +0000777
John McCalldadc5752010-08-24 06:29:42 +0000778ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000779Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
780 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000781 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000782 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000783}
784
785/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000786ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000787Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000788 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000789 const DeclarationNameInfo &NameInfo,
790 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000791 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000792 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000793 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000794 << D->getDeclName();
795 return ExprError();
796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Anders Carlsson946b86d2009-06-24 00:10:43 +0000798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000799 if (isa<NonTypeTemplateParmDecl>(VD)) {
800 // Non-type template parameters can be referenced anywhere they are
801 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000802 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000803 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000804 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
805 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000806 Diag(NameInfo.getLoc(),
807 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000808 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000809 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000810 << D->getIdentifier();
811 return ExprError();
812 }
813 }
John McCall4bc41ae2010-11-18 19:01:18 +0000814
815 // This ridiculousness brought to you by 'extern void x;' and the
816 // GNU compiler collection.
817 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
818 Ty->isVoidType()) {
819 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000820 }
821 }
Mike Stump11289f42009-09-09 15:08:12 +0000822
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000823 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000824
John McCall086a4642010-11-24 05:12:34 +0000825 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000826 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000827 SS? SS->getRange() : SourceRange(),
828 D, NameInfo, Ty, VK);
829
830 // Just in case we're building an illegal pointer-to-member.
831 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
832 E->setObjectKind(OK_BitField);
833
834 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000835}
836
John McCallfeb624a2010-11-23 20:48:44 +0000837static ExprResult
838BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
839 const CXXScopeSpec &SS, FieldDecl *Field,
840 DeclAccessPair FoundDecl,
841 const DeclarationNameInfo &MemberNameInfo);
842
John McCalldadc5752010-08-24 06:29:42 +0000843ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000844Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000845 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000846 Expr *BaseObjectExpr,
847 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000848 // Build the expression that refers to the base object, from
849 // which we will build a sequence of member references to each
850 // of the anonymous union objects and, eventually, the field we
851 // found via name lookup.
852 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000853 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000854 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000855 if (BaseObject) {
856 // BaseObject is an anonymous struct/union variable (and is,
857 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000858 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000859 BaseObjectExpr =
860 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
861 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000862 BaseQuals
863 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000864 } else if (BaseObjectExpr) {
865 // The caller provided the base object expression. Determine
866 // whether its a pointer and whether it adds any qualifiers to the
867 // anonymous struct/union fields we're looking into.
868 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000869 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000870 BaseObjectIsPointer = true;
871 ObjectType = ObjectPtr->getPointeeType();
872 }
John McCall8ccfcb52009-09-24 19:53:00 +0000873 BaseQuals
874 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000875 } else {
876 // We've found a member of an anonymous struct/union that is
877 // inside a non-anonymous struct/union, so in a well-formed
878 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000879 DeclContext *DC = getFunctionLevelDeclContext();
880 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000881 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000882 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000883 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000884 cast<RecordDecl>(
885 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000886 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000887 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000888 == Context.getCanonicalType(ThisType)) ||
889 IsDerivedFrom(ThisType, AnonFieldType)) {
890 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000891 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000892 MD->getThisType(Context),
893 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000894 BaseObjectIsPointer = true;
895 }
896 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000897 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000898 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000899 }
John McCall8ccfcb52009-09-24 19:53:00 +0000900 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000901 }
902
Mike Stump11289f42009-09-09 15:08:12 +0000903 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000904 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000905 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000906 }
907
908 // Build the implicit member references to the field of the
909 // anonymous struct/union.
910 Expr *Result = BaseObjectExpr;
John McCallfeb624a2010-11-23 20:48:44 +0000911
Francois Pichet783dd6e2010-11-21 06:08:52 +0000912 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
913 FEnd = IndirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +0000914
Francois Pichet783dd6e2010-11-21 06:08:52 +0000915 // Skip the first VarDecl if present.
916 if (BaseObject)
917 FI++;
918 for (; FI != FEnd; FI++) {
919 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall8ccfcb52009-09-24 19:53:00 +0000920
John McCallfeb624a2010-11-23 20:48:44 +0000921 // FIXME: the first access can be qualified
922 CXXScopeSpec SS;
John McCall8ccfcb52009-09-24 19:53:00 +0000923
John McCallfeb624a2010-11-23 20:48:44 +0000924 // FIXME: these are somewhat meaningless
925 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
926 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +0000927
John McCallfeb624a2010-11-23 20:48:44 +0000928 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
929 SS, Field, FoundDecl, MemberNameInfo)
930 .take();
John McCall8ccfcb52009-09-24 19:53:00 +0000931
John McCallfeb624a2010-11-23 20:48:44 +0000932 // All the implicit accesses are dot-accesses.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000933 BaseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000934 }
935
Sebastian Redlffbcf962009-01-18 18:53:16 +0000936 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000937}
938
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000939/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000940/// possibly a list of template arguments.
941///
942/// If this produces template arguments, it is permitted to call
943/// DecomposeTemplateName.
944///
945/// This actually loses a lot of source location information for
946/// non-standard name kinds; we should consider preserving that in
947/// some way.
948static void DecomposeUnqualifiedId(Sema &SemaRef,
949 const UnqualifiedId &Id,
950 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000951 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000952 const TemplateArgumentListInfo *&TemplateArgs) {
953 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
954 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
955 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
956
957 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
958 Id.TemplateId->getTemplateArgs(),
959 Id.TemplateId->NumArgs);
960 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
961 TemplateArgsPtr.release();
962
John McCall3e56fd42010-08-23 07:28:44 +0000963 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000964 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
965 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000966 TemplateArgs = &Buffer;
967 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000968 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000969 TemplateArgs = 0;
970 }
971}
972
John McCall69f9dbc2010-02-08 19:26:07 +0000973/// Determines whether the given record is "fully-formed" at the given
974/// location, i.e. whether a qualified lookup into it is assured of
975/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000976static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000977 if (!Record->hasDefinition())
978 return false;
979
John McCall10eae182009-11-30 22:42:35 +0000980 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
981 E = Record->bases_end(); I != E; ++I) {
982 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
983 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
984 if (!BaseRT) return false;
985
986 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000987 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000988 !IsFullyFormedScope(SemaRef, BaseRecord))
989 return false;
990 }
991
992 return true;
993}
994
John McCall2d74de92009-12-01 22:10:20 +0000995/// Determines if the given class is provably not derived from all of
996/// the prospective base classes.
997static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
998 CXXRecordDecl *Record,
999 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001000 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001001 return false;
1002
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001003 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001004 if (!RD) return false;
1005 Record = cast<CXXRecordDecl>(RD);
1006
John McCall2d74de92009-12-01 22:10:20 +00001007 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1008 E = Record->bases_end(); I != E; ++I) {
1009 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1010 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1011 if (!BaseRT) return false;
1012
1013 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001014 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1015 return false;
1016 }
1017
1018 return true;
1019}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001020
John McCall2d74de92009-12-01 22:10:20 +00001021enum IMAKind {
1022 /// The reference is definitely not an instance member access.
1023 IMA_Static,
1024
1025 /// The reference may be an implicit instance member access.
1026 IMA_Mixed,
1027
1028 /// The reference may be to an instance member, but it is invalid if
1029 /// so, because the context is not an instance method.
1030 IMA_Mixed_StaticContext,
1031
1032 /// The reference may be to an instance member, but it is invalid if
1033 /// so, because the context is from an unrelated class.
1034 IMA_Mixed_Unrelated,
1035
1036 /// The reference is definitely an implicit instance member access.
1037 IMA_Instance,
1038
1039 /// The reference may be to an unresolved using declaration.
1040 IMA_Unresolved,
1041
1042 /// The reference may be to an unresolved using declaration and the
1043 /// context is not an instance method.
1044 IMA_Unresolved_StaticContext,
1045
John McCall2d74de92009-12-01 22:10:20 +00001046 /// All possible referrents are instance members and the current
1047 /// context is not an instance method.
1048 IMA_Error_StaticContext,
1049
1050 /// All possible referrents are instance members of an unrelated
1051 /// class.
1052 IMA_Error_Unrelated
1053};
1054
1055/// The given lookup names class member(s) and is not being used for
1056/// an address-of-member expression. Classify the type of access
1057/// according to whether it's possible that this reference names an
1058/// instance member. This is best-effort; it is okay to
1059/// conservatively answer "yes", in which case some errors will simply
1060/// not be caught until template-instantiation.
1061static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1062 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001063 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001064
John McCall87fe5d52010-05-20 01:18:31 +00001065 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001066 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001067 (!isa<CXXMethodDecl>(DC) ||
1068 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001069
1070 if (R.isUnresolvableResult())
1071 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1072
1073 // Collect all the declaring classes of instance members we find.
1074 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001075 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001076 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1077 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001078 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001079
John McCalla8ae2222010-04-06 21:38:20 +00001080 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001081 if (dyn_cast<FieldDecl>(D))
1082 hasField = true;
1083
John McCall2d74de92009-12-01 22:10:20 +00001084 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001085 Classes.insert(R->getCanonicalDecl());
1086 }
1087 else
1088 hasNonInstance = true;
1089 }
1090
1091 // If we didn't find any instance members, it can't be an implicit
1092 // member reference.
1093 if (Classes.empty())
1094 return IMA_Static;
1095
1096 // If the current context is not an instance method, it can't be
1097 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001098 if (isStaticContext) {
1099 if (hasNonInstance)
1100 return IMA_Mixed_StaticContext;
1101
1102 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1103 // C++0x [expr.prim.general]p10:
1104 // An id-expression that denotes a non-static data member or non-static
1105 // member function of a class can only be used:
1106 // (...)
1107 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1108 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1109 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1110 if (isUnevaluatedExpression)
1111 return IMA_Mixed_StaticContext;
1112 }
1113
1114 return IMA_Error_StaticContext;
1115 }
John McCall2d74de92009-12-01 22:10:20 +00001116
1117 // If we can prove that the current context is unrelated to all the
1118 // declaring classes, it can't be an implicit member reference (in
1119 // which case it's an error if any of those members are selected).
1120 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001121 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001122 Classes))
1123 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1124
1125 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1126}
1127
1128/// Diagnose a reference to a field with no object available.
1129static void DiagnoseInstanceReference(Sema &SemaRef,
1130 const CXXScopeSpec &SS,
1131 const LookupResult &R) {
1132 SourceLocation Loc = R.getNameLoc();
1133 SourceRange Range(Loc);
1134 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1135
1136 if (R.getAsSingle<FieldDecl>()) {
1137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1138 if (MD->isStatic()) {
1139 // "invalid use of member 'x' in static member function"
1140 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1141 << Range << R.getLookupName();
1142 return;
1143 }
1144 }
1145
1146 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1147 << R.getLookupName() << Range;
1148 return;
1149 }
1150
1151 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001152}
1153
John McCalld681c392009-12-16 08:11:27 +00001154/// Diagnose an empty lookup.
1155///
1156/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001157bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1158 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001159 DeclarationName Name = R.getLookupName();
1160
John McCalld681c392009-12-16 08:11:27 +00001161 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001162 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001163 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1164 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001165 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001166 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001167 diagnostic_suggest = diag::err_undeclared_use_suggest;
1168 }
John McCalld681c392009-12-16 08:11:27 +00001169
Douglas Gregor598b08f2009-12-31 05:20:13 +00001170 // If the original lookup was an unqualified lookup, fake an
1171 // unqualified lookup. This is useful when (for example) the
1172 // original lookup would not have found something because it was a
1173 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001174 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001175 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001176 if (isa<CXXRecordDecl>(DC)) {
1177 LookupQualifiedName(R, DC);
1178
1179 if (!R.empty()) {
1180 // Don't give errors about ambiguities in this lookup.
1181 R.suppressDiagnostics();
1182
1183 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1184 bool isInstance = CurMethod &&
1185 CurMethod->isInstance() &&
1186 DC == CurMethod->getParent();
1187
1188 // Give a code modification hint to insert 'this->'.
1189 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1190 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001191 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001192 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1193 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001194 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001195 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001196 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001197 Diag(R.getNameLoc(), diagnostic) << Name
1198 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1199 QualType DepThisType = DepMethod->getThisType(Context);
1200 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1201 R.getNameLoc(), DepThisType, false);
1202 TemplateArgumentListInfo TList;
1203 if (ULE->hasExplicitTemplateArgs())
1204 ULE->copyTemplateArgumentsInto(TList);
1205 CXXDependentScopeMemberExpr *DepExpr =
1206 CXXDependentScopeMemberExpr::Create(
1207 Context, DepThis, DepThisType, true, SourceLocation(),
1208 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1209 R.getLookupNameInfo(), &TList);
1210 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001211 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001212 // FIXME: we should be able to handle this case too. It is correct
1213 // to add this-> here. This is a workaround for PR7947.
1214 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001215 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001216 } else {
John McCalld681c392009-12-16 08:11:27 +00001217 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001218 }
John McCalld681c392009-12-16 08:11:27 +00001219
1220 // Do we really want to note all of these?
1221 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1222 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1223
1224 // Tell the callee to try to recover.
1225 return false;
1226 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001227
1228 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001229 }
1230 }
1231
Douglas Gregor598b08f2009-12-31 05:20:13 +00001232 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001233 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001234 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001235 if (!R.empty()) {
1236 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1237 if (SS.isEmpty())
1238 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1239 << FixItHint::CreateReplacement(R.getNameLoc(),
1240 R.getLookupName().getAsString());
1241 else
1242 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1243 << Name << computeDeclContext(SS, false) << R.getLookupName()
1244 << SS.getRange()
1245 << FixItHint::CreateReplacement(R.getNameLoc(),
1246 R.getLookupName().getAsString());
1247 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1248 Diag(ND->getLocation(), diag::note_previous_decl)
1249 << ND->getDeclName();
1250
1251 // Tell the callee to try to recover.
1252 return false;
1253 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001254
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001255 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1256 // FIXME: If we ended up with a typo for a type name or
1257 // Objective-C class name, we're in trouble because the parser
1258 // is in the wrong place to recover. Suggest the typo
1259 // correction, but don't make it a fix-it since we're not going
1260 // to recover well anyway.
1261 if (SS.isEmpty())
1262 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1263 else
1264 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1265 << Name << computeDeclContext(SS, false) << R.getLookupName()
1266 << SS.getRange();
1267
1268 // Don't try to recover; it won't work.
1269 return true;
1270 }
1271 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001272 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001273 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001274 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001275 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001276 else
Douglas Gregor25363982010-01-01 00:15:04 +00001277 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001278 << Name << computeDeclContext(SS, false) << Corrected
1279 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001280 return true;
1281 }
Douglas Gregor25363982010-01-01 00:15:04 +00001282 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001283 }
1284
1285 // Emit a special diagnostic for failed member lookups.
1286 // FIXME: computing the declaration context might fail here (?)
1287 if (!SS.isEmpty()) {
1288 Diag(R.getNameLoc(), diag::err_no_member)
1289 << Name << computeDeclContext(SS, false)
1290 << SS.getRange();
1291 return true;
1292 }
1293
John McCalld681c392009-12-16 08:11:27 +00001294 // Give up, we can't recover.
1295 Diag(R.getNameLoc(), diagnostic) << Name;
1296 return true;
1297}
1298
Douglas Gregor05fcf842010-11-02 20:36:02 +00001299ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1300 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001301 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1302 if (!IDecl)
1303 return 0;
1304 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1305 if (!ClassImpDecl)
1306 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001307 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001308 if (!property)
1309 return 0;
1310 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001311 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1312 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001313 return 0;
1314 return property;
1315}
1316
Douglas Gregor05fcf842010-11-02 20:36:02 +00001317bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1318 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1319 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1320 if (!IDecl)
1321 return false;
1322 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1323 if (!ClassImpDecl)
1324 return false;
1325 if (ObjCPropertyImplDecl *PIDecl
1326 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1327 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1328 PIDecl->getPropertyIvarDecl())
1329 return false;
1330
1331 return true;
1332}
1333
Fariborz Jahanian18722982010-07-17 00:59:30 +00001334static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001335 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001336 IdentifierInfo *II,
1337 SourceLocation NameLoc) {
1338 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001339 bool LookForIvars;
1340 if (Lookup.empty())
1341 LookForIvars = true;
1342 else if (CurMeth->isClassMethod())
1343 LookForIvars = false;
1344 else
1345 LookForIvars = (Lookup.isSingleResult() &&
1346 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1347 if (!LookForIvars)
1348 return 0;
1349
Fariborz Jahanian18722982010-07-17 00:59:30 +00001350 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1351 if (!IDecl)
1352 return 0;
1353 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001354 if (!ClassImpDecl)
1355 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001356 bool DynamicImplSeen = false;
1357 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1358 if (!property)
1359 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001360 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001361 DynamicImplSeen =
1362 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001363 // property implementation has a designated ivar. No need to assume a new
1364 // one.
1365 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1366 return 0;
1367 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001368 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001369 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1370 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001371 NameLoc,
1372 II, PropType, /*Dinfo=*/0,
1373 ObjCIvarDecl::Protected,
1374 (Expr *)0, true);
1375 ClassImpDecl->addDecl(Ivar);
1376 IDecl->makeDeclVisibleInContext(Ivar, false);
1377 property->setPropertyIvarDecl(Ivar);
1378 return Ivar;
1379 }
1380 return 0;
1381}
1382
John McCalldadc5752010-08-24 06:29:42 +00001383ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001384 CXXScopeSpec &SS,
1385 UnqualifiedId &Id,
1386 bool HasTrailingLParen,
1387 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001388 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1389 "cannot be direct & operand and have a trailing lparen");
1390
1391 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001392 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001393
John McCall10eae182009-11-30 22:42:35 +00001394 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001395
1396 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001397 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001398 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001400
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001401 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001402 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001403 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001404
John McCalle66edc12009-11-24 19:00:30 +00001405 // C++ [temp.dep.expr]p3:
1406 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001407 // -- an identifier that was declared with a dependent type,
1408 // (note: handled after lookup)
1409 // -- a template-id that is dependent,
1410 // (note: handled in BuildTemplateIdExpr)
1411 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001412 // -- a nested-name-specifier that contains a class-name that
1413 // names a dependent type.
1414 // Determine whether this is a member of an unknown specialization;
1415 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001416 bool DependentID = false;
1417 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1418 Name.getCXXNameType()->isDependentType()) {
1419 DependentID = true;
1420 } else if (SS.isSet()) {
1421 DeclContext *DC = computeDeclContext(SS, false);
1422 if (DC) {
1423 if (RequireCompleteDeclContext(SS, DC))
1424 return ExprError();
1425 // FIXME: We should be checking whether DC is the current instantiation.
1426 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1427 DependentID = !IsFullyFormedScope(*this, RD);
1428 } else {
1429 DependentID = true;
1430 }
1431 }
1432
1433 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001434 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001435 TemplateArgs);
1436 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001437 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001438 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001439 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001440 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001441 // Lookup the template name again to correctly establish the context in
1442 // which it was found. This is really unfortunate as we already did the
1443 // lookup to determine that it was a template name in the first place. If
1444 // this becomes a performance hit, we can work harder to preserve those
1445 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001446 bool MemberOfUnknownSpecialization;
1447 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1448 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001449 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001450 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001451 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001452
John McCalle66edc12009-11-24 19:00:30 +00001453 // If this reference is in an Objective-C method, then we need to do
1454 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001455 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001456 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001457 if (E.isInvalid())
1458 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001459
John McCalle66edc12009-11-24 19:00:30 +00001460 Expr *Ex = E.takeAs<Expr>();
1461 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001462 // Synthesize ivars lazily
1463 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001464 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1465 if (const ObjCPropertyDecl *Property =
1466 canSynthesizeProvisionalIvar(II)) {
1467 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1468 Diag(Property->getLocation(), diag::note_property_declare);
1469 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001470 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1471 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001472 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001473 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001474 // for further use, this must be set to false if in class method.
1475 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001476 }
Chris Lattner59a25942008-03-31 00:36:02 +00001477 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001478
John McCalle66edc12009-11-24 19:00:30 +00001479 if (R.isAmbiguous())
1480 return ExprError();
1481
Douglas Gregor171c45a2009-02-18 21:56:37 +00001482 // Determine whether this name might be a candidate for
1483 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001484 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001485
John McCalle66edc12009-11-24 19:00:30 +00001486 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001487 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001488 // in C90, extension in C99, forbidden in C++).
1489 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1490 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1491 if (D) R.addDecl(D);
1492 }
1493
1494 // If this name wasn't predeclared and if this is not a function
1495 // call, diagnose the problem.
1496 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001497 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001498 return ExprError();
1499
1500 assert(!R.empty() &&
1501 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001502
1503 // If we found an Objective-C instance variable, let
1504 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001505 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001506 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1507 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001508 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001509 assert(E.isInvalid() || E.get());
1510 return move(E);
1511 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001512 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
John McCalle66edc12009-11-24 19:00:30 +00001515 // This is guaranteed from this point on.
1516 assert(!R.empty() || ADL);
1517
1518 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001519 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001520 !getLangOptions().ObjCNonFragileABI2 &&
1521 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001522 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001523 if (Property) {
1524 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1525 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001526 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001527 }
1528 }
John McCalle66edc12009-11-24 19:00:30 +00001529 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001530 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1531 // C99 DR 316 says that, if a function type comes from a
1532 // function definition (without a prototype), that type is only
1533 // used for checking compatibility. Therefore, when referencing
1534 // the function, we pretend that we don't have the full function
1535 // type.
John McCalle66edc12009-11-24 19:00:30 +00001536 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001537 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001538
Douglas Gregor3256d042009-06-30 15:47:41 +00001539 QualType T = Func->getType();
1540 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001541 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001542 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1543 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001544 // Note that functions are r-values in C.
1545 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001546 }
1547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCall2d74de92009-12-01 22:10:20 +00001549 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001550 // C++ [class.mfct.non-static]p3:
1551 // When an id-expression that is not part of a class member access
1552 // syntax and not used to form a pointer to member is used in the
1553 // body of a non-static member function of class X, if name lookup
1554 // resolves the name in the id-expression to a non-static non-type
1555 // member of some class C, the id-expression is transformed into a
1556 // class member access expression using (*this) as the
1557 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001558 //
1559 // But we don't actually need to do this for '&' operands if R
1560 // resolved to a function or overloaded function set, because the
1561 // expression is ill-formed if it actually works out to be a
1562 // non-static member function:
1563 //
1564 // C++ [expr.ref]p4:
1565 // Otherwise, if E1.E2 refers to a non-static member function. . .
1566 // [t]he expression can be used only as the left-hand operand of a
1567 // member function call.
1568 //
1569 // There are other safeguards against such uses, but it's important
1570 // to get this right here so that we don't end up making a
1571 // spuriously dependent expression if we're inside a dependent
1572 // instance method.
John McCall57500772009-12-16 12:17:52 +00001573 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001574 bool MightBeImplicitMember;
1575 if (!isAddressOfOperand)
1576 MightBeImplicitMember = true;
1577 else if (!SS.isEmpty())
1578 MightBeImplicitMember = false;
1579 else if (R.isOverloadedResult())
1580 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001581 else if (R.isUnresolvableResult())
1582 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001583 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001584 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1585 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001586
1587 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001588 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001589 }
1590
John McCalle66edc12009-11-24 19:00:30 +00001591 if (TemplateArgs)
1592 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001593
John McCalle66edc12009-11-24 19:00:30 +00001594 return BuildDeclarationNameExpr(SS, R, ADL);
1595}
1596
John McCall57500772009-12-16 12:17:52 +00001597/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001598ExprResult
John McCall57500772009-12-16 12:17:52 +00001599Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1600 LookupResult &R,
1601 const TemplateArgumentListInfo *TemplateArgs) {
1602 switch (ClassifyImplicitMemberAccess(*this, R)) {
1603 case IMA_Instance:
1604 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1605
John McCall57500772009-12-16 12:17:52 +00001606 case IMA_Mixed:
1607 case IMA_Mixed_Unrelated:
1608 case IMA_Unresolved:
1609 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1610
1611 case IMA_Static:
1612 case IMA_Mixed_StaticContext:
1613 case IMA_Unresolved_StaticContext:
1614 if (TemplateArgs)
1615 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1616 return BuildDeclarationNameExpr(SS, R, false);
1617
1618 case IMA_Error_StaticContext:
1619 case IMA_Error_Unrelated:
1620 DiagnoseInstanceReference(*this, SS, R);
1621 return ExprError();
1622 }
1623
1624 llvm_unreachable("unexpected instance member access kind");
1625 return ExprError();
1626}
1627
John McCall10eae182009-11-30 22:42:35 +00001628/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1629/// declaration name, generally during template instantiation.
1630/// There's a large number of things which don't need to be done along
1631/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001632ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001633Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001634 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001635 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001636 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001637 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001638
John McCall0b66eb32010-05-01 00:40:08 +00001639 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001640 return ExprError();
1641
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001642 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001643 LookupQualifiedName(R, DC);
1644
1645 if (R.isAmbiguous())
1646 return ExprError();
1647
1648 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001649 Diag(NameInfo.getLoc(), diag::err_no_member)
1650 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001651 return ExprError();
1652 }
1653
1654 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1655}
1656
1657/// LookupInObjCMethod - The parser has read a name in, and Sema has
1658/// detected that we're currently inside an ObjC method. Perform some
1659/// additional lookup.
1660///
1661/// Ideally, most of this would be done by lookup, but there's
1662/// actually quite a lot of extra work involved.
1663///
1664/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001665ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001666Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001667 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001668 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001669 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001670
John McCalle66edc12009-11-24 19:00:30 +00001671 // There are two cases to handle here. 1) scoped lookup could have failed,
1672 // in which case we should look for an ivar. 2) scoped lookup could have
1673 // found a decl, but that decl is outside the current instance method (i.e.
1674 // a global variable). In these two cases, we do a lookup for an ivar with
1675 // this name, if the lookup sucedes, we replace it our current decl.
1676
1677 // If we're in a class method, we don't normally want to look for
1678 // ivars. But if we don't find anything else, and there's an
1679 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001680 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001681
1682 bool LookForIvars;
1683 if (Lookup.empty())
1684 LookForIvars = true;
1685 else if (IsClassMethod)
1686 LookForIvars = false;
1687 else
1688 LookForIvars = (Lookup.isSingleResult() &&
1689 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001690 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001691 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001692 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001693 ObjCInterfaceDecl *ClassDeclared;
1694 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1695 // Diagnose using an ivar in a class method.
1696 if (IsClassMethod)
1697 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1698 << IV->getDeclName());
1699
1700 // If we're referencing an invalid decl, just return this as a silent
1701 // error node. The error diagnostic was already emitted on the decl.
1702 if (IV->isInvalidDecl())
1703 return ExprError();
1704
1705 // Check if referencing a field with __attribute__((deprecated)).
1706 if (DiagnoseUseOfDecl(IV, Loc))
1707 return ExprError();
1708
1709 // Diagnose the use of an ivar outside of the declaring class.
1710 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1711 ClassDeclared != IFace)
1712 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1713
1714 // FIXME: This should use a new expr for a direct reference, don't
1715 // turn this into Self->ivar, just return a BareIVarExpr or something.
1716 IdentifierInfo &II = Context.Idents.get("self");
1717 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001718 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001719 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001720 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001721 SelfName, false, false);
1722 if (SelfExpr.isInvalid())
1723 return ExprError();
1724
John McCalle66edc12009-11-24 19:00:30 +00001725 MarkDeclarationReferenced(Loc, IV);
1726 return Owned(new (Context)
1727 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1728 SelfExpr.takeAs<Expr>(), true, true));
1729 }
Chris Lattner87313662010-04-12 05:10:17 +00001730 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001731 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001732 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001733 ObjCInterfaceDecl *ClassDeclared;
1734 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1735 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1736 IFace == ClassDeclared)
1737 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1738 }
1739 }
1740
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001741 if (Lookup.empty() && II && AllowBuiltinCreation) {
1742 // FIXME. Consolidate this with similar code in LookupName.
1743 if (unsigned BuiltinID = II->getBuiltinID()) {
1744 if (!(getLangOptions().CPlusPlus &&
1745 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1746 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1747 S, Lookup.isForRedeclaration(),
1748 Lookup.getNameLoc());
1749 if (D) Lookup.addDecl(D);
1750 }
1751 }
1752 }
John McCalle66edc12009-11-24 19:00:30 +00001753 // Sentinel value saying that we didn't do anything special.
1754 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001755}
John McCalld14a8642009-11-21 08:51:07 +00001756
John McCall16df1e52010-03-30 21:47:33 +00001757/// \brief Cast a base object to a member's actual type.
1758///
1759/// Logically this happens in three phases:
1760///
1761/// * First we cast from the base type to the naming class.
1762/// The naming class is the class into which we were looking
1763/// when we found the member; it's the qualifier type if a
1764/// qualifier was provided, and otherwise it's the base type.
1765///
1766/// * Next we cast from the naming class to the declaring class.
1767/// If the member we found was brought into a class's scope by
1768/// a using declaration, this is that class; otherwise it's
1769/// the class declaring the member.
1770///
1771/// * Finally we cast from the declaring class to the "true"
1772/// declaring class of the member. This conversion does not
1773/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001774bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001775Sema::PerformObjectMemberConversion(Expr *&From,
1776 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001777 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001778 NamedDecl *Member) {
1779 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1780 if (!RD)
1781 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001782
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001783 QualType DestRecordType;
1784 QualType DestType;
1785 QualType FromRecordType;
1786 QualType FromType = From->getType();
1787 bool PointerConversions = false;
1788 if (isa<FieldDecl>(Member)) {
1789 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001790
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001791 if (FromType->getAs<PointerType>()) {
1792 DestType = Context.getPointerType(DestRecordType);
1793 FromRecordType = FromType->getPointeeType();
1794 PointerConversions = true;
1795 } else {
1796 DestType = DestRecordType;
1797 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001798 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001799 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1800 if (Method->isStatic())
1801 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001802
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001803 DestType = Method->getThisType(Context);
1804 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001805
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001806 if (FromType->getAs<PointerType>()) {
1807 FromRecordType = FromType->getPointeeType();
1808 PointerConversions = true;
1809 } else {
1810 FromRecordType = FromType;
1811 DestType = DestRecordType;
1812 }
1813 } else {
1814 // No conversion necessary.
1815 return false;
1816 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001817
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001818 if (DestType->isDependentType() || FromType->isDependentType())
1819 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001820
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001821 // If the unqualified types are the same, no conversion is necessary.
1822 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1823 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001824
John McCall16df1e52010-03-30 21:47:33 +00001825 SourceRange FromRange = From->getSourceRange();
1826 SourceLocation FromLoc = FromRange.getBegin();
1827
John McCall2536c6d2010-08-25 10:28:54 +00001828 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001829
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001830 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001831 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001832 // class name.
1833 //
1834 // If the member was a qualified name and the qualified referred to a
1835 // specific base subobject type, we'll cast to that intermediate type
1836 // first and then to the object in which the member is declared. That allows
1837 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1838 //
1839 // class Base { public: int x; };
1840 // class Derived1 : public Base { };
1841 // class Derived2 : public Base { };
1842 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1843 //
1844 // void VeryDerived::f() {
1845 // x = 17; // error: ambiguous base subobjects
1846 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1847 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001848 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001849 QualType QType = QualType(Qualifier->getAsType(), 0);
1850 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1851 assert(QType->isRecordType() && "lookup done with non-record type");
1852
1853 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1854
1855 // In C++98, the qualifier type doesn't actually have to be a base
1856 // type of the object type, in which case we just ignore it.
1857 // Otherwise build the appropriate casts.
1858 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001859 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001860 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001861 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001862 return true;
1863
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001864 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001865 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001866 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1867 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001868
1869 FromType = QType;
1870 FromRecordType = QRecordType;
1871
1872 // If the qualifier type was the same as the destination type,
1873 // we're done.
1874 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1875 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001876 }
1877 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001878
John McCall16df1e52010-03-30 21:47:33 +00001879 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001880
John McCall16df1e52010-03-30 21:47:33 +00001881 // If we actually found the member through a using declaration, cast
1882 // down to the using declaration's type.
1883 //
1884 // Pointer equality is fine here because only one declaration of a
1885 // class ever has member declarations.
1886 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1887 assert(isa<UsingShadowDecl>(FoundDecl));
1888 QualType URecordType = Context.getTypeDeclType(
1889 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1890
1891 // We only need to do this if the naming-class to declaring-class
1892 // conversion is non-trivial.
1893 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1894 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001895 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001896 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001897 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001898 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001899
John McCall16df1e52010-03-30 21:47:33 +00001900 QualType UType = URecordType;
1901 if (PointerConversions)
1902 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001903 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001904 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001905 FromType = UType;
1906 FromRecordType = URecordType;
1907 }
1908
1909 // We don't do access control for the conversion from the
1910 // declaring class to the true declaring class.
1911 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001912 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001913
John McCallcf142162010-08-07 06:22:56 +00001914 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001915 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1916 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001917 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001918 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001919
John McCalle3027922010-08-25 11:45:40 +00001920 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001921 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001922 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001923}
Douglas Gregor3256d042009-06-30 15:47:41 +00001924
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001925/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001926static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001927 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001928 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001929 const DeclarationNameInfo &MemberNameInfo,
1930 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001931 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001932 const TemplateArgumentListInfo *TemplateArgs = 0) {
1933 NestedNameSpecifier *Qualifier = 0;
1934 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001935 if (SS.isSet()) {
1936 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1937 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001938 }
Mike Stump11289f42009-09-09 15:08:12 +00001939
John McCalle66edc12009-11-24 19:00:30 +00001940 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001941 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001942 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001943}
1944
John McCallfeb624a2010-11-23 20:48:44 +00001945static ExprResult
1946BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1947 const CXXScopeSpec &SS, FieldDecl *Field,
1948 DeclAccessPair FoundDecl,
1949 const DeclarationNameInfo &MemberNameInfo) {
1950 // x.a is an l-value if 'a' has a reference type. Otherwise:
1951 // x.a is an l-value/x-value/pr-value if the base is (and note
1952 // that *x is always an l-value), except that if the base isn't
1953 // an ordinary object then we must have an rvalue.
1954 ExprValueKind VK = VK_LValue;
1955 ExprObjectKind OK = OK_Ordinary;
1956 if (!IsArrow) {
1957 if (BaseExpr->getObjectKind() == OK_Ordinary)
1958 VK = BaseExpr->getValueKind();
1959 else
1960 VK = VK_RValue;
1961 }
1962 if (VK != VK_RValue && Field->isBitField())
1963 OK = OK_BitField;
1964
1965 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1966 QualType MemberType = Field->getType();
1967 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1968 MemberType = Ref->getPointeeType();
1969 VK = VK_LValue;
1970 } else {
1971 QualType BaseType = BaseExpr->getType();
1972 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1973
1974 Qualifiers BaseQuals = BaseType.getQualifiers();
1975
1976 // GC attributes are never picked up by members.
1977 BaseQuals.removeObjCGCAttr();
1978
1979 // CVR attributes from the base are picked up by members,
1980 // except that 'mutable' members don't pick up 'const'.
1981 if (Field->isMutable()) BaseQuals.removeConst();
1982
1983 Qualifiers MemberQuals
1984 = S.Context.getCanonicalType(MemberType).getQualifiers();
1985
1986 // TR 18037 does not allow fields to be declared with address spaces.
1987 assert(!MemberQuals.hasAddressSpace());
1988
1989 Qualifiers Combined = BaseQuals + MemberQuals;
1990 if (Combined != MemberQuals)
1991 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1992 }
1993
1994 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1995 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1996 FoundDecl, Field))
1997 return ExprError();
1998 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
1999 Field, FoundDecl, MemberNameInfo,
2000 MemberType, VK, OK));
2001}
2002
John McCall2d74de92009-12-01 22:10:20 +00002003/// Builds an implicit member access expression. The current context
2004/// is known to be an instance method, and the given unqualified lookup
2005/// set is known to contain only instance members, at least one of which
2006/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002007ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002008Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2009 LookupResult &R,
2010 const TemplateArgumentListInfo *TemplateArgs,
2011 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002012 assert(!R.empty() && !R.isAmbiguous());
2013
John McCalld14a8642009-11-21 08:51:07 +00002014 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002015
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002016 // We may have found a field within an anonymous union or struct
2017 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002018 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00002019 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002020 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2021 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2022
Sebastian Redlffbcf962009-01-18 18:53:16 +00002023
John McCall2d74de92009-12-01 22:10:20 +00002024 // If this is known to be an instance access, go ahead and build a
2025 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00002026 DeclContext *DC = getFunctionLevelDeclContext();
2027 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00002028 Expr *This = 0; // null signifies implicit access
2029 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002030 SourceLocation Loc = R.getNameLoc();
2031 if (SS.getRange().isValid())
2032 Loc = SS.getRange().getBegin();
2033 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002034 }
2035
John McCallb268a282010-08-23 23:25:46 +00002036 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00002037 /*OpLoc*/ SourceLocation(),
2038 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002039 SS,
2040 /*FirstQualifierInScope*/ 0,
2041 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002042}
2043
John McCalle66edc12009-11-24 19:00:30 +00002044bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002045 const LookupResult &R,
2046 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002047 // Only when used directly as the postfix-expression of a call.
2048 if (!HasTrailingLParen)
2049 return false;
2050
2051 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002052 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002053 return false;
2054
2055 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002056 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002057 return false;
2058
2059 // Turn off ADL when we find certain kinds of declarations during
2060 // normal lookup:
2061 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2062 NamedDecl *D = *I;
2063
2064 // C++0x [basic.lookup.argdep]p3:
2065 // -- a declaration of a class member
2066 // Since using decls preserve this property, we check this on the
2067 // original decl.
John McCall57500772009-12-16 12:17:52 +00002068 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002069 return false;
2070
2071 // C++0x [basic.lookup.argdep]p3:
2072 // -- a block-scope function declaration that is not a
2073 // using-declaration
2074 // NOTE: we also trigger this for function templates (in fact, we
2075 // don't check the decl type at all, since all other decl types
2076 // turn off ADL anyway).
2077 if (isa<UsingShadowDecl>(D))
2078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2079 else if (D->getDeclContext()->isFunctionOrMethod())
2080 return false;
2081
2082 // C++0x [basic.lookup.argdep]p3:
2083 // -- a declaration that is neither a function or a function
2084 // template
2085 // And also for builtin functions.
2086 if (isa<FunctionDecl>(D)) {
2087 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2088
2089 // But also builtin functions.
2090 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2091 return false;
2092 } else if (!isa<FunctionTemplateDecl>(D))
2093 return false;
2094 }
2095
2096 return true;
2097}
2098
2099
John McCalld14a8642009-11-21 08:51:07 +00002100/// Diagnoses obvious problems with the use of the given declaration
2101/// as an expression. This is only actually called for lookups that
2102/// were not overloaded, and it doesn't promise that the declaration
2103/// will in fact be used.
2104static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2105 if (isa<TypedefDecl>(D)) {
2106 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2107 return true;
2108 }
2109
2110 if (isa<ObjCInterfaceDecl>(D)) {
2111 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2112 return true;
2113 }
2114
2115 if (isa<NamespaceDecl>(D)) {
2116 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2117 return true;
2118 }
2119
2120 return false;
2121}
2122
John McCalldadc5752010-08-24 06:29:42 +00002123ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002124Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002125 LookupResult &R,
2126 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002127 // If this is a single, fully-resolved result and we don't need ADL,
2128 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002129 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002130 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2131 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002132
2133 // We only need to check the declaration if there's exactly one
2134 // result, because in the overloaded case the results can only be
2135 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002136 if (R.isSingleResult() &&
2137 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002138 return ExprError();
2139
John McCall58cc69d2010-01-27 01:50:18 +00002140 // Otherwise, just build an unresolved lookup expression. Suppress
2141 // any lookup-related diagnostics; we'll hash these out later, when
2142 // we've picked a target.
2143 R.suppressDiagnostics();
2144
John McCalle66edc12009-11-24 19:00:30 +00002145 bool Dependent
2146 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00002147 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00002148 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002149 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002150 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002151 NeedsADL, R.isOverloadedResult(),
2152 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002153
2154 return Owned(ULE);
2155}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002156
John McCall7decc9e2010-11-18 06:31:45 +00002157static ExprValueKind getValueKindForDecl(ASTContext &Context,
2158 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002159 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2160 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2161 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002162 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2163 if (isa<FunctionDecl>(D)) {
2164 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2165 return VK_RValue;
2166 return VK_LValue;
2167 }
2168 return Expr::getValueKindForType(D->getType());
2169}
2170
John McCalld14a8642009-11-21 08:51:07 +00002171
2172/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002173ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002174Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002175 const DeclarationNameInfo &NameInfo,
2176 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002177 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002178 assert(!isa<FunctionTemplateDecl>(D) &&
2179 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002180
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002181 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002182 if (CheckDeclInExpr(*this, Loc, D))
2183 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002184
Douglas Gregore7488b92009-12-01 16:58:18 +00002185 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2186 // Specifically diagnose references to class templates that are missing
2187 // a template argument list.
2188 Diag(Loc, diag::err_template_decl_ref)
2189 << Template << SS.getRange();
2190 Diag(Template->getLocation(), diag::note_template_decl_here);
2191 return ExprError();
2192 }
2193
2194 // Make sure that we're referring to a value.
2195 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2196 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002197 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002198 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002199 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002200 return ExprError();
2201 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002202
Douglas Gregor171c45a2009-02-18 21:56:37 +00002203 // Check whether this declaration can be used. Note that we suppress
2204 // this check when we're going to perform argument-dependent lookup
2205 // on this function name, because this might not be the function
2206 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002207 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002208 return ExprError();
2209
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002210 // Only create DeclRefExpr's for valid Decl's.
2211 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002212 return ExprError();
2213
Francois Pichet783dd6e2010-11-21 06:08:52 +00002214 // Handle anonymous.
2215 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2216 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2217
John McCall7decc9e2010-11-18 06:31:45 +00002218 ExprValueKind VK = getValueKindForDecl(Context, VD);
2219
Chris Lattner2a9d9892008-10-20 05:16:36 +00002220 // If the identifier reference is inside a block, and it refers to a value
2221 // that is outside the block, create a BlockDeclRefExpr instead of a
2222 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2223 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002224 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002225 // We do not do this for things like enum constants, global variables, etc,
2226 // as they do not get snapshotted.
2227 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002228 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002229 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002230 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2231 Diag(Loc, diag::err_ref_vm_type);
2232 Diag(D->getLocation(), diag::note_declared_at);
2233 return ExprError();
2234 }
2235
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002236 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002237 Diag(Loc, diag::err_ref_array_type);
2238 Diag(D->getLocation(), diag::note_declared_at);
2239 return ExprError();
2240 }
2241
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002242 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002243 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002244
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002245 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002246 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002247 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002248 BlockDeclRefExpr *BDRE;
2249
2250 if (!byrefVar) {
2251 // This is to record that a 'const' was actually synthesize and added.
2252 bool constAdded = !ExprTy.isConstQualified();
2253 // Variable will be bound by-copy, make it const within the closure.
2254 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002255 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2256 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002257 }
2258 else
John McCall7decc9e2010-11-18 06:31:45 +00002259 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002260
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002261 if (getLangOptions().CPlusPlus) {
2262 if (!T->isDependentType() && !T->isReferenceType()) {
2263 Expr *E = new (Context)
2264 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002265 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002266 if (T->getAs<RecordType>())
2267 if (!T->isUnionType()) {
2268 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002269 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002270 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002271 SourceLocation(),
2272 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002273 if (!Res.isInvalid()) {
John McCall5d413782010-12-06 08:20:24 +00002274 Res = MaybeCreateExprWithCleanups(Res.get());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002275 Expr *Init = Res.takeAs<Expr>();
2276 BDRE->setCopyConstructorExpr(Init);
2277 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002278 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002279 }
2280 }
2281 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002282 }
2283 // If this reference is not in a block or if the referenced variable is
2284 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002285
John McCall7decc9e2010-11-18 06:31:45 +00002286 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002287 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002288}
Chris Lattnere168f762006-11-10 05:29:30 +00002289
John McCalldadc5752010-08-24 06:29:42 +00002290ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002291 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002292 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002293
Chris Lattnere168f762006-11-10 05:29:30 +00002294 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002295 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002296 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2297 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2298 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002299 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002300
Chris Lattnera81a0272008-01-12 08:14:25 +00002301 // Pre-defined identifiers are of type char[x], where x is the length of the
2302 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002303
Anders Carlsson2fb08242009-09-08 18:24:21 +00002304 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002305 if (!currentDecl && getCurBlock())
2306 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002307 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002308 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002309 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002310 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002311
Anders Carlsson0b209a82009-09-11 01:22:35 +00002312 QualType ResTy;
2313 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2314 ResTy = Context.DependentTy;
2315 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002316 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002317
Anders Carlsson0b209a82009-09-11 01:22:35 +00002318 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002319 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002320 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2321 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002322 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002323}
2324
John McCalldadc5752010-08-24 06:29:42 +00002325ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002326 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002327 bool Invalid = false;
2328 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2329 if (Invalid)
2330 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002331
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002332 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2333 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002334 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002335 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002336
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002337 QualType Ty;
2338 if (!getLangOptions().CPlusPlus)
2339 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2340 else if (Literal.isWide())
2341 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002342 else if (Literal.isMultiChar())
2343 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002344 else
2345 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002346
Sebastian Redl20614a72009-01-20 22:23:13 +00002347 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2348 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002349 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002350}
2351
John McCalldadc5752010-08-24 06:29:42 +00002352ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002353 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002354 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2355 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002356 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002357 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002358 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002359 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002360 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002361
Chris Lattner23b7eb62007-06-15 23:05:46 +00002362 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002363 // Add padding so that NumericLiteralParser can overread by one character.
2364 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002365 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002366
Chris Lattner67ca9252007-05-21 01:08:44 +00002367 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002368 bool Invalid = false;
2369 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2370 if (Invalid)
2371 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002372
Mike Stump11289f42009-09-09 15:08:12 +00002373 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002374 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002375 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002376 return ExprError();
2377
Chris Lattner1c20a172007-08-26 03:42:43 +00002378 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002379
Chris Lattner1c20a172007-08-26 03:42:43 +00002380 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002381 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002382 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002383 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002384 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002385 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002386 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002387 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002388
2389 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2390
John McCall53b93a02009-12-24 09:08:04 +00002391 using llvm::APFloat;
2392 APFloat Val(Format);
2393
2394 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002395
2396 // Overflow is always an error, but underflow is only an error if
2397 // we underflowed to zero (APFloat reports denormals as underflow).
2398 if ((result & APFloat::opOverflow) ||
2399 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002400 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002401 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002402 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002403 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002404 APFloat::getLargest(Format).toString(buffer);
2405 } else {
John McCall62abc942010-02-26 23:35:57 +00002406 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002407 APFloat::getSmallest(Format).toString(buffer);
2408 }
2409
2410 Diag(Tok.getLocation(), diagnostic)
2411 << Ty
2412 << llvm::StringRef(buffer.data(), buffer.size());
2413 }
2414
2415 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002416 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002417
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002418 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2419 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2420
Chris Lattner1c20a172007-08-26 03:42:43 +00002421 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002422 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002423 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002424 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002425
Neil Boothac582c52007-08-29 22:00:19 +00002426 // long long is a C99 feature.
2427 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002428 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002429 Diag(Tok.getLocation(), diag::ext_longlong);
2430
Chris Lattner67ca9252007-05-21 01:08:44 +00002431 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002432 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002433
Chris Lattner67ca9252007-05-21 01:08:44 +00002434 if (Literal.GetIntegerValue(ResultVal)) {
2435 // If this value didn't fit into uintmax_t, warn and force to ull.
2436 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002437 Ty = Context.UnsignedLongLongTy;
2438 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002439 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002440 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002441 // If this value fits into a ULL, try to figure out what else it fits into
2442 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002443
Chris Lattner67ca9252007-05-21 01:08:44 +00002444 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2445 // be an unsigned int.
2446 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2447
2448 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002449 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002450 if (!Literal.isLong && !Literal.isLongLong) {
2451 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002452 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002453
Chris Lattner67ca9252007-05-21 01:08:44 +00002454 // Does it fit in a unsigned int?
2455 if (ResultVal.isIntN(IntSize)) {
2456 // Does it fit in a signed int?
2457 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002458 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002459 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002460 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002461 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002462 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002463 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002464
Chris Lattner67ca9252007-05-21 01:08:44 +00002465 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002466 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002467 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002468
Chris Lattner67ca9252007-05-21 01:08:44 +00002469 // Does it fit in a unsigned long?
2470 if (ResultVal.isIntN(LongSize)) {
2471 // Does it fit in a signed long?
2472 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002473 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002474 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002475 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002476 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002477 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002478 }
2479
Chris Lattner67ca9252007-05-21 01:08:44 +00002480 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002481 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002482 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002483
Chris Lattner67ca9252007-05-21 01:08:44 +00002484 // Does it fit in a unsigned long long?
2485 if (ResultVal.isIntN(LongLongSize)) {
2486 // Does it fit in a signed long long?
2487 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002488 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002489 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002490 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002491 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002492 }
2493 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002494
Chris Lattner67ca9252007-05-21 01:08:44 +00002495 // If we still couldn't decide a type, we probably have something that
2496 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002497 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002498 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002499 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002500 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002501 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002502
Chris Lattner55258cf2008-05-09 05:59:00 +00002503 if (ResultVal.getBitWidth() != Width)
2504 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002505 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002506 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002507 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002508
Chris Lattner1c20a172007-08-26 03:42:43 +00002509 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2510 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002511 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002512 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002513
2514 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002515}
2516
John McCalldadc5752010-08-24 06:29:42 +00002517ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002518 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002519 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002520 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002521}
2522
Steve Naroff71b59a92007-06-04 22:22:31 +00002523/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002524/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002525bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002526 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002527 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002528 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002529 if (exprType->isDependentType())
2530 return false;
2531
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002532 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2533 // the result is the size of the referenced type."
2534 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2535 // result shall be the alignment of the referenced type."
2536 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2537 exprType = Ref->getPointeeType();
2538
Steve Naroff043d45d2007-05-15 02:32:35 +00002539 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002540 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002541 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002542 if (isSizeof)
2543 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2544 return false;
2545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Chris Lattner62975a72009-04-24 00:30:45 +00002547 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002548 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002549 Diag(OpLoc, diag::ext_sizeof_void_type)
2550 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002551 return false;
2552 }
Mike Stump11289f42009-09-09 15:08:12 +00002553
Chris Lattner62975a72009-04-24 00:30:45 +00002554 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002555 PDiag(diag::err_sizeof_alignof_incomplete_type)
2556 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002557 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002558
Chris Lattner62975a72009-04-24 00:30:45 +00002559 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002560 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002561 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002562 << exprType << isSizeof << ExprRange;
2563 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Chris Lattner62975a72009-04-24 00:30:45 +00002566 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002567}
2568
John McCall36e7fe32010-10-12 00:20:44 +00002569static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2570 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002571 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002572
Mike Stump11289f42009-09-09 15:08:12 +00002573 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002574 if (isa<DeclRefExpr>(E))
2575 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002576
2577 // Cannot know anything else if the expression is dependent.
2578 if (E->isTypeDependent())
2579 return false;
2580
Douglas Gregor71235ec2009-05-02 02:18:30 +00002581 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002582 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002583 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002584 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002585
2586 // Alignment of a field access is always okay, so long as it isn't a
2587 // bit-field.
2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002589 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002590 return false;
2591
John McCall36e7fe32010-10-12 00:20:44 +00002592 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002593}
2594
Douglas Gregor0950e412009-03-13 21:01:28 +00002595/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002596ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002597Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002598 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002599 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002600 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002601 return ExprError();
2602
John McCallbcd03502009-12-07 02:54:59 +00002603 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002604
Douglas Gregor0950e412009-03-13 21:01:28 +00002605 if (!T->isDependentType() &&
2606 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2607 return ExprError();
2608
2609 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002610 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002611 Context.getSizeType(), OpLoc,
2612 R.getEnd()));
2613}
2614
2615/// \brief Build a sizeof or alignof expression given an expression
2616/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002617ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002618Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002619 bool isSizeOf, SourceRange R) {
2620 // Verify that the operand is valid.
2621 bool isInvalid = false;
2622 if (E->isTypeDependent()) {
2623 // Delay type-checking for type-dependent expressions.
2624 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002625 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002626 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002627 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2628 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002629 } else if (E->getType()->isPlaceholderType()) {
2630 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2631 if (PE.isInvalid()) return ExprError();
2632 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002633 } else {
2634 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2635 }
2636
2637 if (isInvalid)
2638 return ExprError();
2639
2640 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2641 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2642 Context.getSizeType(), OpLoc,
2643 R.getEnd()));
2644}
2645
Sebastian Redl6f282892008-11-11 17:56:53 +00002646/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2647/// the same for @c alignof and @c __alignof
2648/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002649ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002650Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2651 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002652 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002653 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002654
Sebastian Redl6f282892008-11-11 17:56:53 +00002655 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002656 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002657 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002658 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002659 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002660
Douglas Gregor0950e412009-03-13 21:01:28 +00002661 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002662 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002663 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2664
Douglas Gregor0950e412009-03-13 21:01:28 +00002665 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002666}
2667
John McCall4bc41ae2010-11-18 19:01:18 +00002668static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2669 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002670 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002671 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002672
John McCall34376a62010-12-04 03:47:34 +00002673 // _Real and _Imag are only l-values for normal l-values.
2674 if (V->getObjectKind() != OK_Ordinary)
2675 S.DefaultFunctionArrayLvalueConversion(V);
2676
Chris Lattnere267f5d2007-08-26 05:39:26 +00002677 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002678 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002679 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002680
Chris Lattnere267f5d2007-08-26 05:39:26 +00002681 // Otherwise they pass through real integer and floating point types here.
2682 if (V->getType()->isArithmeticType())
2683 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002684
John McCall36226622010-10-12 02:09:17 +00002685 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002686 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002687 if (PR.isInvalid()) return QualType();
2688 if (PR.take() != V) {
2689 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002690 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002691 }
2692
Chris Lattnere267f5d2007-08-26 05:39:26 +00002693 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002694 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002695 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002696 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002697}
2698
2699
Chris Lattnere168f762006-11-10 05:29:30 +00002700
John McCalldadc5752010-08-24 06:29:42 +00002701ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002702Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002703 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002704 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002705 switch (Kind) {
2706 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002707 case tok::plusplus: Opc = UO_PostInc; break;
2708 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002709 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002710
John McCallb268a282010-08-23 23:25:46 +00002711 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002712}
2713
John McCall4bc41ae2010-11-18 19:01:18 +00002714/// Expressions of certain arbitrary types are forbidden by C from
2715/// having l-value type. These are:
2716/// - 'void', but not qualified void
2717/// - function types
2718///
2719/// The exact rule here is C99 6.3.2.1:
2720/// An lvalue is an expression with an object type or an incomplete
2721/// type other than void.
2722static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2723 return ((T->isVoidType() && !T.hasQualifiers()) ||
2724 T->isFunctionType());
2725}
2726
John McCalldadc5752010-08-24 06:29:42 +00002727ExprResult
John McCallb268a282010-08-23 23:25:46 +00002728Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2729 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002730 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002731 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002732 if (Result.isInvalid()) return ExprError();
2733 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002734
John McCallb268a282010-08-23 23:25:46 +00002735 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002736
Douglas Gregor40412ac2008-11-19 17:17:41 +00002737 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002738 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002739 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002740 Context.DependentTy,
2741 VK_LValue, OK_Ordinary,
2742 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002743 }
2744
Mike Stump11289f42009-09-09 15:08:12 +00002745 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002746 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002747 LHSExp->getType()->isEnumeralType() ||
2748 RHSExp->getType()->isRecordType() ||
2749 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002750 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002751 }
2752
John McCallb268a282010-08-23 23:25:46 +00002753 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002754}
2755
2756
John McCalldadc5752010-08-24 06:29:42 +00002757ExprResult
John McCallb268a282010-08-23 23:25:46 +00002758Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2759 Expr *Idx, SourceLocation RLoc) {
2760 Expr *LHSExp = Base;
2761 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002762
Chris Lattner36d572b2007-07-16 00:14:47 +00002763 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002764 if (!LHSExp->getType()->getAs<VectorType>())
2765 DefaultFunctionArrayLvalueConversion(LHSExp);
2766 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002767
Chris Lattner36d572b2007-07-16 00:14:47 +00002768 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002769 ExprValueKind VK = VK_LValue;
2770 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002771
Steve Naroffc1aadb12007-03-28 21:49:40 +00002772 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002773 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002774 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002775 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002776 Expr *BaseExpr, *IndexExpr;
2777 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002778 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2779 BaseExpr = LHSExp;
2780 IndexExpr = RHSExp;
2781 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002782 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002783 BaseExpr = LHSExp;
2784 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002785 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002786 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002787 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002788 BaseExpr = RHSExp;
2789 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002790 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002791 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002792 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002793 BaseExpr = LHSExp;
2794 IndexExpr = RHSExp;
2795 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002796 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002797 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002798 // Handle the uncommon case of "123[Ptr]".
2799 BaseExpr = RHSExp;
2800 IndexExpr = LHSExp;
2801 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002802 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002803 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002804 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002805 VK = LHSExp->getValueKind();
2806 if (VK != VK_RValue)
2807 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002808
Chris Lattner36d572b2007-07-16 00:14:47 +00002809 // FIXME: need to deal with const...
2810 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002811 } else if (LHSTy->isArrayType()) {
2812 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002813 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002814 // wasn't promoted because of the C90 rule that doesn't
2815 // allow promoting non-lvalue arrays. Warn, then
2816 // force the promotion here.
2817 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2818 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002819 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002820 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002821 LHSTy = LHSExp->getType();
2822
2823 BaseExpr = LHSExp;
2824 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002825 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002826 } else if (RHSTy->isArrayType()) {
2827 // Same as previous, except for 123[f().a] case
2828 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2829 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002830 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002831 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002832 RHSTy = RHSExp->getType();
2833
2834 BaseExpr = RHSExp;
2835 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002836 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002837 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002838 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2839 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002840 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002841 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002842 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002843 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2844 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002845
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002846 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002847 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2848 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002849 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2850
Douglas Gregorac1fb652009-03-24 19:52:54 +00002851 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002852 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2853 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002854 // incomplete types are not object types.
2855 if (ResultType->isFunctionType()) {
2856 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2857 << ResultType << BaseExpr->getSourceRange();
2858 return ExprError();
2859 }
Mike Stump11289f42009-09-09 15:08:12 +00002860
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002861 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2862 // GNU extension: subscripting on pointer to void
2863 Diag(LLoc, diag::ext_gnu_void_ptr)
2864 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002865
2866 // C forbids expressions of unqualified void type from being l-values.
2867 // See IsCForbiddenLValueType.
2868 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002869 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002870 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002871 PDiag(diag::err_subscript_incomplete_type)
2872 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002873 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002874
Chris Lattner62975a72009-04-24 00:30:45 +00002875 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002876 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002877 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2878 << ResultType << BaseExpr->getSourceRange();
2879 return ExprError();
2880 }
Mike Stump11289f42009-09-09 15:08:12 +00002881
John McCall4bc41ae2010-11-18 19:01:18 +00002882 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2883 !IsCForbiddenLValueType(Context, ResultType));
2884
Mike Stump4e1f26a2009-02-19 03:04:26 +00002885 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002886 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002887}
2888
John McCall4bc41ae2010-11-18 19:01:18 +00002889/// Check an ext-vector component access expression.
2890///
2891/// VK should be set in advance to the value kind of the base
2892/// expression.
2893static QualType
2894CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2895 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002896 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002897 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2898 // see FIXME there.
2899 //
2900 // FIXME: This logic can be greatly simplified by splitting it along
2901 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002902 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002903
Steve Narofff8fd09e2007-07-27 22:15:19 +00002904 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002905 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002906
Mike Stump4e1f26a2009-02-19 03:04:26 +00002907 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002908 // special names that indicate a subset of exactly half the elements are
2909 // to be selected.
2910 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002911
Nate Begemanbb70bf62009-01-18 01:47:54 +00002912 // This flag determines whether or not CompName has an 's' char prefix,
2913 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002914 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002915
John McCall4bc41ae2010-11-18 19:01:18 +00002916 bool HasRepeated = false;
2917 bool HasIndex[16] = {};
2918
2919 int Idx;
2920
Nate Begemanf322eab2008-05-09 06:41:27 +00002921 // Check that we've found one of the special components, or that the component
2922 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002923 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002924 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2925 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002926 } else if (!HexSwizzle &&
2927 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2928 do {
2929 if (HasIndex[Idx]) HasRepeated = true;
2930 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002931 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002932 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2933 } else {
2934 if (HexSwizzle) compStr++;
2935 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2936 if (HasIndex[Idx]) HasRepeated = true;
2937 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002938 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002939 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002940 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002941
Mike Stump4e1f26a2009-02-19 03:04:26 +00002942 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002943 // We didn't get to the end of the string. This means the component names
2944 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002945 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002946 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002947 return QualType();
2948 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002949
Nate Begemanbb70bf62009-01-18 01:47:54 +00002950 // Ensure no component accessor exceeds the width of the vector type it
2951 // operates on.
2952 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002953 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002954
2955 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002956 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002957
2958 while (*compStr) {
2959 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002960 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002961 << baseType << SourceRange(CompLoc);
2962 return QualType();
2963 }
2964 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002965 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002966
Steve Narofff8fd09e2007-07-27 22:15:19 +00002967 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002968 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002969 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002970 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002971 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002972 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002973 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002974 if (HexSwizzle)
2975 CompSize--;
2976
Steve Narofff8fd09e2007-07-27 22:15:19 +00002977 if (CompSize == 1)
2978 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002979
John McCall4bc41ae2010-11-18 19:01:18 +00002980 if (HasRepeated) VK = VK_RValue;
2981
2982 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002983 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002984 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00002985 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
2986 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
2987 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002988 }
2989 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002990}
2991
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002992static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002993 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002994 const Selector &Sel,
2995 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002996 if (Member)
2997 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2998 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002999 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003000 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003001
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003002 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3003 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003004 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3005 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003006 return D;
3007 }
3008 return 0;
3009}
3010
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003011static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3012 IdentifierInfo *Member,
3013 const Selector &Sel,
3014 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003015 // Check protocols on qualified interfaces.
3016 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003017 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003018 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003019 if (Member)
3020 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3021 GDecl = PD;
3022 break;
3023 }
3024 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003025 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003026 GDecl = OMD;
3027 break;
3028 }
3029 }
3030 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003031 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003032 E = QIdTy->qual_end(); I != E; ++I) {
3033 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003034 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3035 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003036 if (GDecl)
3037 return GDecl;
3038 }
3039 }
3040 return GDecl;
3041}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003042
John McCalldadc5752010-08-24 06:29:42 +00003043ExprResult
John McCallb268a282010-08-23 23:25:46 +00003044Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003045 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003046 const CXXScopeSpec &SS,
3047 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003048 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003049 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003050 // Even in dependent contexts, try to diagnose base expressions with
3051 // obviously wrong types, e.g.:
3052 //
3053 // T* t;
3054 // t.f;
3055 //
3056 // In Obj-C++, however, the above expression is valid, since it could be
3057 // accessing the 'f' property if T is an Obj-C interface. The extra check
3058 // allows this, while still reporting an error if T is a struct pointer.
3059 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003060 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003061 if (PT && (!getLangOptions().ObjC1 ||
3062 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003063 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003064 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003065 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003066 return ExprError();
3067 }
3068 }
3069
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003070 assert(BaseType->isDependentType() ||
3071 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003072 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003073
3074 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3075 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003076 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003077 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003078 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003079 SS.getRange(),
3080 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003081 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003082}
3083
3084/// We know that the given qualified member reference points only to
3085/// declarations which do not belong to the static type of the base
3086/// expression. Diagnose the problem.
3087static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3088 Expr *BaseExpr,
3089 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003090 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003091 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00003092 // If this is an implicit member access, use a different set of
3093 // diagnostics.
3094 if (!BaseExpr)
3095 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00003096
John McCall1e67dd62010-04-27 01:43:38 +00003097 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3098 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003099}
3100
3101// Check whether the declarations we found through a nested-name
3102// specifier in a member expression are actually members of the base
3103// type. The restriction here is:
3104//
3105// C++ [expr.ref]p2:
3106// ... In these cases, the id-expression shall name a
3107// member of the class or of one of its base classes.
3108//
3109// So it's perfectly legitimate for the nested-name specifier to name
3110// an unrelated class, and for us to find an overload set including
3111// decls from classes which are not superclasses, as long as the decl
3112// we actually pick through overload resolution is from a superclass.
3113bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3114 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003115 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003116 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003117 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3118 if (!BaseRT) {
3119 // We can't check this yet because the base type is still
3120 // dependent.
3121 assert(BaseType->isDependentType());
3122 return false;
3123 }
3124 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003125
3126 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003127 // If this is an implicit member reference and we find a
3128 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003129 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003130 return false;
John McCall10eae182009-11-30 22:42:35 +00003131
John McCall2d74de92009-12-01 22:10:20 +00003132 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003133 DeclContext *DC = (*I)->getDeclContext();
3134 while (DC->isTransparentContext())
3135 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003136
Douglas Gregora9c3e822010-07-28 22:27:52 +00003137 if (!DC->isRecord())
3138 continue;
3139
John McCall2d74de92009-12-01 22:10:20 +00003140 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003141 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003142
3143 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3144 return false;
3145 }
3146
John McCallcd4b4772009-12-02 03:53:29 +00003147 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003148 return true;
3149}
3150
3151static bool
3152LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3153 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003154 SourceLocation OpLoc, CXXScopeSpec &SS,
3155 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003156 RecordDecl *RDecl = RTy->getDecl();
3157 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003158 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003159 << BaseRange))
3160 return true;
3161
John McCalle9cccd82010-06-16 08:42:20 +00003162 if (HasTemplateArgs) {
3163 // LookupTemplateName doesn't expect these both to exist simultaneously.
3164 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3165
3166 bool MOUS;
3167 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3168 return false;
3169 }
3170
John McCall2d74de92009-12-01 22:10:20 +00003171 DeclContext *DC = RDecl;
3172 if (SS.isSet()) {
3173 // If the member name was a qualified-id, look into the
3174 // nested-name-specifier.
3175 DC = SemaRef.computeDeclContext(SS, false);
3176
John McCall0b66eb32010-05-01 00:40:08 +00003177 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003178 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3179 << SS.getRange() << DC;
3180 return true;
3181 }
3182
John McCall2d74de92009-12-01 22:10:20 +00003183 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003184
John McCall2d74de92009-12-01 22:10:20 +00003185 if (!isa<TypeDecl>(DC)) {
3186 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3187 << DC << SS.getRange();
3188 return true;
John McCall10eae182009-11-30 22:42:35 +00003189 }
3190 }
3191
John McCall2d74de92009-12-01 22:10:20 +00003192 // The record definition is complete, now look up the member.
3193 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003194
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003195 if (!R.empty())
3196 return false;
3197
3198 // We didn't find anything with the given name, so try to correct
3199 // for typos.
3200 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003201 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003202 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003203 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3204 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3205 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003206 << FixItHint::CreateReplacement(R.getNameLoc(),
3207 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003208 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3209 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3210 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003211 return false;
3212 } else {
3213 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003214 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003215 }
3216
John McCall10eae182009-11-30 22:42:35 +00003217 return false;
3218}
3219
John McCalldadc5752010-08-24 06:29:42 +00003220ExprResult
John McCallb268a282010-08-23 23:25:46 +00003221Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003222 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003223 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003224 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003225 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003226 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003227 if (BaseType->isDependentType() ||
3228 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003229 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003230 IsArrow, OpLoc,
3231 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003232 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003233
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003234 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003235
John McCall2d74de92009-12-01 22:10:20 +00003236 // Implicit member accesses.
3237 if (!Base) {
3238 QualType RecordTy = BaseType;
3239 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3240 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3241 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003242 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003243 return ExprError();
3244
3245 // Explicit member accesses.
3246 } else {
John McCalldadc5752010-08-24 06:29:42 +00003247 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003248 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003249 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003250
3251 if (Result.isInvalid()) {
3252 Owned(Base);
3253 return ExprError();
3254 }
3255
3256 if (Result.get())
3257 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003258
3259 // LookupMemberExpr can modify Base, and thus change BaseType
3260 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003261 }
3262
John McCallb268a282010-08-23 23:25:46 +00003263 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003264 OpLoc, IsArrow, SS, FirstQualifierInScope,
3265 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003266}
3267
John McCalldadc5752010-08-24 06:29:42 +00003268ExprResult
John McCallb268a282010-08-23 23:25:46 +00003269Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003270 SourceLocation OpLoc, bool IsArrow,
3271 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003272 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003273 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003274 const TemplateArgumentListInfo *TemplateArgs,
3275 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003276 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003277 if (IsArrow) {
3278 assert(BaseType->isPointerType());
3279 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3280 }
John McCalla8ae2222010-04-06 21:38:20 +00003281 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003282
John McCallb268a282010-08-23 23:25:46 +00003283 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003284 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3285 DeclarationName MemberName = MemberNameInfo.getName();
3286 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003287
3288 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003289 return ExprError();
3290
John McCall10eae182009-11-30 22:42:35 +00003291 if (R.empty()) {
3292 // Rederive where we looked up.
3293 DeclContext *DC = (SS.isSet()
3294 ? computeDeclContext(SS, false)
3295 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003296
John McCall10eae182009-11-30 22:42:35 +00003297 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003298 << MemberName << DC
3299 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003300 return ExprError();
3301 }
3302
John McCall38836f02010-01-15 08:34:02 +00003303 // Diagnose lookups that find only declarations from a non-base
3304 // type. This is possible for either qualified lookups (which may
3305 // have been qualified with an unrelated type) or implicit member
3306 // expressions (which were found with unqualified lookup and thus
3307 // may have come from an enclosing scope). Note that it's okay for
3308 // lookup to find declarations from a non-base type as long as those
3309 // aren't the ones picked by overload resolution.
3310 if ((SS.isSet() || !BaseExpr ||
3311 (isa<CXXThisExpr>(BaseExpr) &&
3312 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003313 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003314 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003315 return ExprError();
3316
3317 // Construct an unresolved result if we in fact got an unresolved
3318 // result.
3319 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00003320 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00003321 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00003322 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00003323 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003324
John McCall58cc69d2010-01-27 01:50:18 +00003325 // Suppress any lookup-related diagnostics; we'll do these when we
3326 // pick a member.
3327 R.suppressDiagnostics();
3328
John McCall10eae182009-11-30 22:42:35 +00003329 UnresolvedMemberExpr *MemExpr
3330 = UnresolvedMemberExpr::Create(Context, Dependent,
3331 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003332 BaseExpr, BaseExprType,
3333 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003334 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003335 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003336 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003337
3338 return Owned(MemExpr);
3339 }
3340
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003341 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003342 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003343 NamedDecl *MemberDecl = R.getFoundDecl();
3344
3345 // FIXME: diagnose the presence of template arguments now.
3346
3347 // If the decl being referenced had an error, return an error for this
3348 // sub-expr without emitting another error, in order to avoid cascading
3349 // error cases.
3350 if (MemberDecl->isInvalidDecl())
3351 return ExprError();
3352
John McCall2d74de92009-12-01 22:10:20 +00003353 // Handle the implicit-member-access case.
3354 if (!BaseExpr) {
3355 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003356 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003357 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003358
Douglas Gregorb15af892010-01-07 23:12:05 +00003359 SourceLocation Loc = R.getNameLoc();
3360 if (SS.getRange().isValid())
3361 Loc = SS.getRange().getBegin();
3362 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003363 }
3364
John McCall10eae182009-11-30 22:42:35 +00003365 bool ShouldCheckUse = true;
3366 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3367 // Don't diagnose the use of a virtual member function unless it's
3368 // explicitly qualified.
3369 if (MD->isVirtual() && !SS.isSet())
3370 ShouldCheckUse = false;
3371 }
3372
3373 // Check the use of this member.
3374 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3375 Owned(BaseExpr);
3376 return ExprError();
3377 }
3378
John McCall34376a62010-12-04 03:47:34 +00003379 // Perform a property load on the base regardless of whether we
3380 // actually need it for the declaration.
3381 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3382 ConvertPropertyForRValue(BaseExpr);
3383
John McCallfeb624a2010-11-23 20:48:44 +00003384 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3385 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3386 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003387
Francois Pichet783dd6e2010-11-21 06:08:52 +00003388 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3389 // We may have found a field within an anonymous union or struct
3390 // (C++ [class.union]).
3391 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003392 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003393
John McCall10eae182009-11-30 22:42:35 +00003394 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3395 MarkDeclarationReferenced(MemberLoc, Var);
3396 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003397 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003398 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003399 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003400 }
3401
John McCall7decc9e2010-11-18 06:31:45 +00003402 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003403 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3404 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003405 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003406 MemberFn->getType(),
3407 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3408 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003409 }
John McCall7decc9e2010-11-18 06:31:45 +00003410 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003411
3412 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3413 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3414 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003415 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003416 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003417 }
3418
3419 Owned(BaseExpr);
3420
Douglas Gregor861eb802010-04-25 20:55:08 +00003421 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003422 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003423 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003424 << MemberName << BaseType << int(IsArrow);
3425 else
3426 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3427 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003428
Douglas Gregor861eb802010-04-25 20:55:08 +00003429 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3430 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003431 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003432 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003433}
3434
3435/// Look up the given member of the given non-type-dependent
3436/// expression. This can return in one of two ways:
3437/// * If it returns a sentinel null-but-valid result, the caller will
3438/// assume that lookup was performed and the results written into
3439/// the provided structure. It will take over from there.
3440/// * Otherwise, the returned expression will be produced in place of
3441/// an ordinary member expression.
3442///
3443/// The ObjCImpDecl bit is a gross hack that will need to be properly
3444/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003445ExprResult
John McCall10eae182009-11-30 22:42:35 +00003446Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003447 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003448 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003449 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003450 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003451
Steve Naroffeaaae462007-12-16 21:42:28 +00003452 // Perform default conversions.
3453 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003454
Steve Naroff185616f2007-07-26 03:11:44 +00003455 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003456 assert(!BaseType->isDependentType());
3457
3458 DeclarationName MemberName = R.getLookupName();
3459 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003460
3461 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00003462 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00003463 // function. Suggest the addition of those parentheses, build the
3464 // call, and continue on.
3465 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3466 if (const FunctionProtoType *Fun
3467 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
3468 QualType ResultTy = Fun->getResultType();
3469 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00003470 ((!IsArrow && ResultTy->isRecordType()) ||
3471 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00003472 ResultTy->getAs<PointerType>()->getPointeeType()
3473 ->isRecordType()))) {
3474 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
Nick Lewyckyc60d6e72010-10-15 21:43:24 +00003475 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Douglas Gregord82ae382009-11-06 06:30:47 +00003476 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00003477 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003478
John McCalldadc5752010-08-24 06:29:42 +00003479 ExprResult NewBase
Douglas Gregorce5aa332010-09-09 16:33:13 +00003480 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00003481 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00003482 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00003483 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003484
Douglas Gregord82ae382009-11-06 06:30:47 +00003485 BaseExpr = NewBase.takeAs<Expr>();
3486 DefaultFunctionArrayConversion(BaseExpr);
3487 BaseType = BaseExpr->getType();
3488 }
3489 }
3490 }
3491
David Chisnall9f57c292009-08-17 16:35:33 +00003492 // If this is an Objective-C pseudo-builtin and a definition is provided then
3493 // use that.
3494 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003495 if (IsArrow) {
3496 // Handle the following exceptional case PObj->isa.
3497 if (const ObjCObjectPointerType *OPT =
3498 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00003499 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003500 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003501 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3502 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003503 }
3504 }
David Chisnall9f57c292009-08-17 16:35:33 +00003505 // We have an 'id' type. Rather than fall through, we check if this
3506 // is a reference to 'isa'.
3507 if (BaseType != Context.ObjCIdRedefinitionType) {
3508 BaseType = Context.ObjCIdRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003509 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003510 }
David Chisnall9f57c292009-08-17 16:35:33 +00003511 }
John McCall10eae182009-11-30 22:42:35 +00003512
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003513 // If this is an Objective-C pseudo-builtin and a definition is provided then
3514 // use that.
3515 if (Context.isObjCSelType(BaseType)) {
3516 // We have an 'SEL' type. Rather than fall through, we check if this
3517 // is a reference to 'sel_id'.
3518 if (BaseType != Context.ObjCSelRedefinitionType) {
3519 BaseType = Context.ObjCSelRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003520 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003521 }
3522 }
John McCall10eae182009-11-30 22:42:35 +00003523
Steve Naroff185616f2007-07-26 03:11:44 +00003524 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003525
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003526 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003527 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003528 // Also must look for a getter name which uses property syntax.
3529 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3530 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3531 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3532 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3533 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003534 if ((Getter = IFace->lookupClassMethod(Sel))) {
3535 // Check the use of this method.
3536 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3537 return ExprError();
3538 }
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003539 else
3540 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003541 // If we found a getter then this may be a valid dot-reference, we
3542 // will look for the matching setter, in case it is needed.
3543 Selector SetterSel =
3544 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3545 PP.getSelectorTable(), Member);
3546 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3547 if (!Setter) {
3548 // If this reference is in an @implementation, also check for 'private'
3549 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003550 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003551 }
3552 // Look through local category implementations associated with the class.
3553 if (!Setter)
3554 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003555
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003556 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3557 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003558
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003559 if (Getter || Setter) {
3560 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003561
John McCall4bc41ae2010-11-18 19:01:18 +00003562 ExprValueKind VK = VK_LValue;
3563 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003564 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003565 if (!getLangOptions().CPlusPlus &&
3566 IsCForbiddenLValueType(Context, PType))
3567 VK = VK_RValue;
3568 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003569 // Get the expression type from Setter's incoming parameter.
3570 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003571 }
3572 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3573
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003574 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003575 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3576 PType, VK, OK,
3577 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003578 }
3579 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3580 << MemberName << BaseType);
3581 }
3582 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003583
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003584 if (BaseType->isObjCClassType() &&
3585 BaseType != Context.ObjCClassRedefinitionType) {
3586 BaseType = Context.ObjCClassRedefinitionType;
John McCalle3027922010-08-25 11:45:40 +00003587 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003588 }
Mike Stump11289f42009-09-09 15:08:12 +00003589
John McCall10eae182009-11-30 22:42:35 +00003590 if (IsArrow) {
3591 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003592 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003593 else if (BaseType->isObjCObjectPointerType())
3594 ;
John McCalla928c652009-12-07 22:46:59 +00003595 else if (BaseType->isRecordType()) {
3596 // Recover from arrow accesses to records, e.g.:
3597 // struct MyRecord foo;
3598 // foo->bar
3599 // This is actually well-formed in C++ if MyRecord has an
3600 // overloaded operator->, but that should have been dealt with
3601 // by now.
3602 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3603 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003604 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003605 IsArrow = false;
3606 } else {
John McCall10eae182009-11-30 22:42:35 +00003607 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3608 << BaseType << BaseExpr->getSourceRange();
3609 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003610 }
John McCalla928c652009-12-07 22:46:59 +00003611 } else {
3612 // Recover from dot accesses to pointers, e.g.:
3613 // type *foo;
3614 // foo.bar
3615 // This is actually well-formed in two cases:
3616 // - 'type' is an Objective C type
3617 // - 'bar' is a pseudo-destructor name which happens to refer to
3618 // the appropriate pointer type
3619 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3620 const PointerType *PT = BaseType->getAs<PointerType>();
3621 if (PT && PT->getPointeeType()->isRecordType()) {
3622 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3623 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003624 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003625 BaseType = PT->getPointeeType();
3626 IsArrow = true;
3627 }
3628 }
John McCall10eae182009-11-30 22:42:35 +00003629 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003630
John McCall8b07ec22010-05-15 11:32:37 +00003631 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003632 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003633 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003634 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003635 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003636 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003637 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003638
Chris Lattnerdc420f42008-07-21 04:59:05 +00003639 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3640 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003641 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003642 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003643 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003644 ObjCInterfaceDecl *IDecl =
3645 OPT ? OPT->getInterfaceDecl()
3646 : BaseType->getAs<ObjCObjectType>()->getInterface();
3647 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003648 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3649
Steve Naroffa057ba92009-07-16 00:25:06 +00003650 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003651 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003653 if (!IV) {
3654 // Attempt to correct for typos in ivar names.
3655 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3656 LookupMemberName);
Douglas Gregord507d772010-10-20 03:06:34 +00003657 if (CorrectTypo(Res, 0, 0, IDecl, false,
3658 IsArrow? CTC_ObjCIvarLookup
3659 : CTC_ObjCPropertyLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003660 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003661 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003662 diag::err_typecheck_member_reference_ivar_suggest)
3663 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003664 << FixItHint::CreateReplacement(R.getNameLoc(),
3665 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003666 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003667 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003668 } else {
3669 Res.clear();
3670 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003671 }
3672 }
3673
Steve Naroffa057ba92009-07-16 00:25:06 +00003674 if (IV) {
3675 // If the decl being referenced had an error, return an error for this
3676 // sub-expr without emitting another error, in order to avoid cascading
3677 // error cases.
3678 if (IV->isInvalidDecl())
3679 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003680
Steve Naroffa057ba92009-07-16 00:25:06 +00003681 // Check whether we can reference this field.
3682 if (DiagnoseUseOfDecl(IV, MemberLoc))
3683 return ExprError();
3684 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3685 IV->getAccessControl() != ObjCIvarDecl::Package) {
3686 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3687 if (ObjCMethodDecl *MD = getCurMethodDecl())
3688 ClassOfMethodDecl = MD->getClassInterface();
3689 else if (ObjCImpDecl && getCurFunctionDecl()) {
3690 // Case of a c-function declared inside an objc implementation.
3691 // FIXME: For a c-style function nested inside an objc implementation
3692 // class, there is no implementation context available, so we pass
3693 // down the context as argument to this routine. Ideally, this context
3694 // need be passed down in the AST node and somehow calculated from the
3695 // AST for a function decl.
Mike Stump11289f42009-09-09 15:08:12 +00003696 if (ObjCImplementationDecl *IMPD =
John McCall48871652010-08-21 09:40:31 +00003697 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003698 ClassOfMethodDecl = IMPD->getClassInterface();
3699 else if (ObjCCategoryImplDecl* CatImplClass =
John McCall48871652010-08-21 09:40:31 +00003700 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003701 ClassOfMethodDecl = CatImplClass->getClassInterface();
3702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
3704 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3705 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003706 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003707 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003708 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003709 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3710 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003711 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003712 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003713 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003714
3715 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3716 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003717 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003718 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003719 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003720 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003721 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003722 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003723 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003724 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003725 if (!IsArrow && (BaseType->isObjCIdType() ||
3726 BaseType->isObjCQualifiedIdType())) {
John McCall34376a62010-12-04 03:47:34 +00003727 // This actually uses the base as an r-value.
3728 DefaultFunctionArrayLvalueConversion(BaseExpr);
3729 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3730
John McCall9dd450b2009-09-21 23:43:11 +00003731 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003732 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003733
Steve Naroff7cae42b2009-07-10 23:34:53 +00003734 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003735 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003736 if (Decl *PMDecl = FindGetterSetterNameDecl(QIdTy, Member, Sel,
3737 Context)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003738 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3739 // Check the use of this declaration
3740 if (DiagnoseUseOfDecl(PD, MemberLoc))
3741 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003742
Steve Naroff7cae42b2009-07-10 23:34:53 +00003743 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003744 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003745 MemberLoc,
3746 BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003747 }
3748 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3749 // Check the use of this method.
3750 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3751 return ExprError();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003752 Selector SetterSel =
3753 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3754 PP.getSelectorTable(), Member);
3755 ObjCMethodDecl *SMD = 0;
3756 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy, /*Property id*/0,
3757 SetterSel, Context))
3758 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3759 QualType PType = OMD->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003760
3761 ExprValueKind VK = VK_LValue;
3762 if (!getLangOptions().CPlusPlus &&
3763 IsCForbiddenLValueType(Context, PType))
3764 VK = VK_RValue;
3765 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3766
John McCallb7bd14f2010-12-02 01:19:52 +00003767 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType, VK, OK,
3768 MemberLoc, BaseExpr));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003769 }
3770 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003771
Steve Naroff7cae42b2009-07-10 23:34:53 +00003772 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003773 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003774 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003775
Chris Lattnerdc420f42008-07-21 04:59:05 +00003776 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3777 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003778 if (!IsArrow)
3779 if (const ObjCObjectPointerType *OPT =
John McCall34376a62010-12-04 03:47:34 +00003780 BaseType->getAsObjCInterfacePointerType()) {
3781 // This actually uses the base as an r-value.
3782 DefaultFunctionArrayLvalueConversion(BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00003783 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3784 SourceLocation(), QualType(), false);
John McCall34376a62010-12-04 03:47:34 +00003785 }
Mike Stump11289f42009-09-09 15:08:12 +00003786
Steve Naroffe87026a2009-07-24 17:54:45 +00003787 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003788 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003789 BaseType->isObjCObjectType() &&
3790 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003791 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003792 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003793 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003794
Chris Lattnerb63a7452008-07-21 04:28:12 +00003795 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003796 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003797 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall4bc41ae2010-11-18 19:01:18 +00003798 ExprValueKind VK = BaseExpr->getValueKind();
3799 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3800 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003801 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003802 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003803
3804 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3805 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003806 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003807
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003808 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3809 << BaseType << BaseExpr->getSourceRange();
3810
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003811 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003812}
3813
John McCall10eae182009-11-30 22:42:35 +00003814/// The main callback when the parser finds something like
3815/// expression . [nested-name-specifier] identifier
3816/// expression -> [nested-name-specifier] identifier
3817/// where 'identifier' encompasses a fairly broad spectrum of
3818/// possibilities, including destructor and operator references.
3819///
3820/// \param OpKind either tok::arrow or tok::period
3821/// \param HasTrailingLParen whether the next token is '(', which
3822/// is used to diagnose mis-uses of special members that can
3823/// only be called
3824/// \param ObjCImpDecl the current ObjC @implementation decl;
3825/// this is an ugly hack around the fact that ObjC @implementations
3826/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003827ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall10eae182009-11-30 22:42:35 +00003828 SourceLocation OpLoc,
3829 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003830 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003831 UnqualifiedId &Id,
John McCall48871652010-08-21 09:40:31 +00003832 Decl *ObjCImpDecl,
John McCall10eae182009-11-30 22:42:35 +00003833 bool HasTrailingLParen) {
3834 if (SS.isSet() && SS.isInvalid())
3835 return ExprError();
3836
3837 TemplateArgumentListInfo TemplateArgsBuffer;
3838
3839 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003840 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003841 const TemplateArgumentListInfo *TemplateArgs;
3842 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003843 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003844
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003845 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003846 bool IsArrow = (OpKind == tok::arrow);
3847
3848 NamedDecl *FirstQualifierInScope
3849 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3850 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3851
3852 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003853 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003854 if (Result.isInvalid()) return ExprError();
3855 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003856
Douglas Gregor41f90302010-04-12 20:54:26 +00003857 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3858 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003859 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003860 IsArrow, OpLoc,
3861 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003862 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003863 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003864 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003865 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3866 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003867
John McCalle9cccd82010-06-16 08:42:20 +00003868 if (Result.isInvalid()) {
3869 Owned(Base);
3870 return ExprError();
3871 }
John McCall10eae182009-11-30 22:42:35 +00003872
John McCalle9cccd82010-06-16 08:42:20 +00003873 if (Result.get()) {
3874 // The only way a reference to a destructor can be used is to
3875 // immediately call it, which falls into this case. If the
3876 // next token is not a '(', produce a diagnostic and build the
3877 // call now.
3878 if (!HasTrailingLParen &&
3879 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003880 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003881
John McCalle9cccd82010-06-16 08:42:20 +00003882 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003883 }
3884
John McCallb268a282010-08-23 23:25:46 +00003885 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003886 OpLoc, IsArrow, SS, FirstQualifierInScope,
3887 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003888 }
3889
3890 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003891}
3892
John McCalldadc5752010-08-24 06:29:42 +00003893ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003894 FunctionDecl *FD,
3895 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003896 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003897 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003898 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003899 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003900 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003901 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003902 return ExprError();
3903 }
3904
3905 if (Param->hasUninstantiatedDefaultArg()) {
3906 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003907
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003908 // Instantiate the expression.
3909 MultiLevelTemplateArgumentList ArgList
3910 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003911
Nico Weber44887f62010-11-29 18:19:25 +00003912 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003913 = ArgList.getInnermost();
3914 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3915 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003916
Nico Weber44887f62010-11-29 18:19:25 +00003917 ExprResult Result;
3918 {
3919 // C++ [dcl.fct.default]p5:
3920 // The names in the [default argument] expression are bound, and
3921 // the semantic constraints are checked, at the point where the
3922 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003923 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003924 Result = SubstExpr(UninstExpr, ArgList);
3925 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003926 if (Result.isInvalid())
3927 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003928
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003929 // Check the expression as an initializer for the parameter.
3930 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003931 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003932 InitializationKind Kind
3933 = InitializationKind::CreateCopy(Param->getLocation(),
3934 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3935 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003936
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003937 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3938 Result = InitSeq.Perform(*this, Entity, Kind,
3939 MultiExprArg(*this, &ResultE, 1));
3940 if (Result.isInvalid())
3941 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003942
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003943 // Build the default argument expression.
3944 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3945 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003946 }
3947
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003948 // If the default expression creates temporaries, we need to
3949 // push them to the current stack of expression temporaries so they'll
3950 // be properly destroyed.
3951 // FIXME: We should really be rebuilding the default argument with new
3952 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003953 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3954 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3955 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3956 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3957 ExprTemporaries.push_back(Temporary);
3958 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003959
3960 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003961 // Just mark all of the declarations in this potentially-evaluated expression
3962 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003963 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003964 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003965}
3966
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003967/// ConvertArgumentsForCall - Converts the arguments specified in
3968/// Args/NumArgs to the parameter types of the function FDecl with
3969/// function prototype Proto. Call is the call expression itself, and
3970/// Fn is the function expression. For a C++ member function, this
3971/// routine does not attempt to convert the object argument. Returns
3972/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003973bool
3974Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003975 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003976 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003977 Expr **Args, unsigned NumArgs,
3978 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003979 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003980 // assignment, to the types of the corresponding parameter, ...
3981 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003982 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003983
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003984 // If too few arguments are available (and we don't have default
3985 // arguments for the remaining parameters), don't make the call.
3986 if (NumArgs < NumArgsInProto) {
3987 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3988 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003989 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003990 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003991 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003992 }
3993
3994 // If too many are passed and not variadic, error on the extras and drop
3995 // them.
3996 if (NumArgs > NumArgsInProto) {
3997 if (!Proto->isVariadic()) {
3998 Diag(Args[NumArgsInProto]->getLocStart(),
3999 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004000 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004001 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004002 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4003 Args[NumArgs-1]->getLocEnd());
4004 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004005 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004006 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004007 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004008 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004009 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004010 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004011 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4012 if (Fn->getType()->isBlockPointerType())
4013 CallType = VariadicBlock; // Block
4014 else if (isa<MemberExpr>(Fn))
4015 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004016 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004017 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004018 if (Invalid)
4019 return true;
4020 unsigned TotalNumArgs = AllArgs.size();
4021 for (unsigned i = 0; i < TotalNumArgs; ++i)
4022 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004023
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004024 return false;
4025}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004026
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004027bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4028 FunctionDecl *FDecl,
4029 const FunctionProtoType *Proto,
4030 unsigned FirstProtoArg,
4031 Expr **Args, unsigned NumArgs,
4032 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004033 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004034 unsigned NumArgsInProto = Proto->getNumArgs();
4035 unsigned NumArgsToCheck = NumArgs;
4036 bool Invalid = false;
4037 if (NumArgs != NumArgsInProto)
4038 // Use default arguments for missing arguments
4039 NumArgsToCheck = NumArgsInProto;
4040 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004041 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004042 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004043 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004044
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004045 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004046 if (ArgIx < NumArgs) {
4047 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004048
Eli Friedman3164fb12009-03-22 22:00:50 +00004049 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4050 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004051 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004052 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004053 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004054
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004055 // Pass the argument
4056 ParmVarDecl *Param = 0;
4057 if (FDecl && i < FDecl->getNumParams())
4058 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004059
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004060 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004061 Param? InitializedEntity::InitializeParameter(Context, Param)
4062 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004063 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004064 SourceLocation(),
4065 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004066 if (ArgE.isInvalid())
4067 return true;
4068
4069 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004070 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004071 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072
John McCalldadc5752010-08-24 06:29:42 +00004073 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004074 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004075 if (ArgExpr.isInvalid())
4076 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004077
Anders Carlsson355933d2009-08-25 03:49:14 +00004078 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004079 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004080 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004081 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004082
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004083 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004084 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004085 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004086 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004087 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004088 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004089 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004090 }
4091 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004092 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004093}
4094
Steve Naroff83895f72007-09-16 03:34:24 +00004095/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004096/// This provides the location of the left/right parens and a list of comma
4097/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004098ExprResult
John McCallb268a282010-08-23 23:25:46 +00004099Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004100 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004101 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004102
4103 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004104 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004105 if (Result.isInvalid()) return ExprError();
4106 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004107
John McCallb268a282010-08-23 23:25:46 +00004108 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004109
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004110 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004111 // If this is a pseudo-destructor expression, build the call immediately.
4112 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4113 if (NumArgs > 0) {
4114 // Pseudo-destructor calls should not have any arguments.
4115 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004116 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004117 SourceRange(Args[0]->getLocStart(),
4118 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004119
Douglas Gregorad8a3362009-09-04 17:36:40 +00004120 NumArgs = 0;
4121 }
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregorad8a3362009-09-04 17:36:40 +00004123 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004124 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004127 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004128 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004129 // FIXME: Will need to cache the results of name lookup (including ADL) in
4130 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004131 bool Dependent = false;
4132 if (Fn->isTypeDependent())
4133 Dependent = true;
4134 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4135 Dependent = true;
4136
4137 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004138 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004139 Context.DependentTy, VK_RValue,
4140 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004141
4142 // Determine whether this is a call to an object (C++ [over.call.object]).
4143 if (Fn->getType()->isRecordType())
4144 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004145 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004146
John McCall10eae182009-11-30 22:42:35 +00004147 Expr *NakedFn = Fn->IgnoreParens();
4148
4149 // Determine whether this is a call to an unresolved member function.
4150 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4151 // If lookup was unresolved but not dependent (i.e. didn't find
4152 // an unresolved using declaration), it has to be an overloaded
4153 // function set, which means it must contain either multiple
4154 // declarations (all methods or method templates) or a single
4155 // method template.
4156 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004157 isa<FunctionTemplateDecl>(
4158 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004159 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004160
John McCall2d74de92009-12-01 22:10:20 +00004161 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004162 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004163 }
4164
Douglas Gregore254f902009-02-04 00:32:51 +00004165 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004166 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004167 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004168 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004169 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004170 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004171 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004172
Anders Carlsson61914b52009-10-03 17:40:22 +00004173 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004175 if (BO->getOpcode() == BO_PtrMemD ||
4176 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004177 if (const FunctionProtoType *FPT
4178 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004179 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004180 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004181
John McCallb268a282010-08-23 23:25:46 +00004182 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004183 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004184 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004185 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004186
4187 if (CheckCallReturnType(FPT->getResultType(),
4188 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004189 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004190 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004191
John McCallb268a282010-08-23 23:25:46 +00004192 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004193 RParenLoc))
4194 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004195
John McCallb268a282010-08-23 23:25:46 +00004196 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004197 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004198 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004199 diag::err_typecheck_call_not_function)
4200 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004201 }
4202 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004203 }
4204
Douglas Gregore254f902009-02-04 00:32:51 +00004205 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004206 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004207 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004208
Eli Friedmane14b1992009-12-26 03:35:45 +00004209 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004210 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4211 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4212 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4213 RParenLoc);
4214 }
4215
John McCall57500772009-12-16 12:17:52 +00004216 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004217 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4218 if (UnOp->getOpcode() == UO_AddrOf)
4219 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4220
John McCall57500772009-12-16 12:17:52 +00004221 if (isa<DeclRefExpr>(NakedFn))
4222 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4223
John McCall2d74de92009-12-01 22:10:20 +00004224 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4225}
4226
John McCall57500772009-12-16 12:17:52 +00004227/// BuildResolvedCallExpr - Build a call to a resolved expression,
4228/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004229/// unary-convert to an expression of function-pointer or
4230/// block-pointer type.
4231///
4232/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004233ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004234Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4235 SourceLocation LParenLoc,
4236 Expr **Args, unsigned NumArgs,
4237 SourceLocation RParenLoc) {
4238 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4239
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004240 // Promote the function operand.
4241 UsualUnaryConversions(Fn);
4242
Chris Lattner08464942007-12-28 05:29:59 +00004243 // Make the call expr early, before semantic checks. This guarantees cleanup
4244 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004245 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4246 Args, NumArgs,
4247 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004248 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004249 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004250
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004251 const FunctionType *FuncT;
4252 if (!Fn->getType()->isBlockPointerType()) {
4253 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4254 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004255 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004256 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004257 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4258 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004259 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004260 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004261 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004262 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004263 }
Chris Lattner08464942007-12-28 05:29:59 +00004264 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004265 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4266 << Fn->getType() << Fn->getSourceRange());
4267
Eli Friedman3164fb12009-03-22 22:00:50 +00004268 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004269 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004270 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004271 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004272 return ExprError();
4273
Chris Lattner08464942007-12-28 05:29:59 +00004274 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004275 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004276 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004277
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004278 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004279 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004280 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004281 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004282 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004283 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004284
Douglas Gregord8e97de2009-04-02 15:37:10 +00004285 if (FDecl) {
4286 // Check if we have too few/too many template arguments, based
4287 // on our knowledge of the function definition.
4288 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004289 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004290 const FunctionProtoType *Proto
4291 = Def->getType()->getAs<FunctionProtoType>();
4292 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004293 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4294 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004295 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004296
4297 // If the function we're calling isn't a function prototype, but we have
4298 // a function prototype from a prior declaratiom, use that prototype.
4299 if (!FDecl->hasPrototype())
4300 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004301 }
4302
Steve Naroff0b661582007-08-28 23:30:39 +00004303 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004304 for (unsigned i = 0; i != NumArgs; i++) {
4305 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004306
4307 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004308 InitializedEntity Entity
4309 = InitializedEntity::InitializeParameter(Context,
4310 Proto->getArgType(i));
4311 ExprResult ArgE = PerformCopyInitialization(Entity,
4312 SourceLocation(),
4313 Owned(Arg));
4314 if (ArgE.isInvalid())
4315 return true;
4316
4317 Arg = ArgE.takeAs<Expr>();
4318
4319 } else {
4320 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004321 }
4322
Douglas Gregor83025412010-10-26 05:45:40 +00004323 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4324 Arg->getType(),
4325 PDiag(diag::err_call_incomplete_argument)
4326 << Arg->getSourceRange()))
4327 return ExprError();
4328
Chris Lattner08464942007-12-28 05:29:59 +00004329 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004330 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004331 }
Chris Lattner08464942007-12-28 05:29:59 +00004332
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004333 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4334 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004335 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4336 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004337
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004338 // Check for sentinels
4339 if (NDecl)
4340 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004341
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004342 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004343 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004344 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004345 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004346
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004347 if (unsigned BuiltinID = FDecl->getBuiltinID())
4348 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004349 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004350 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004351 return ExprError();
4352 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004353
John McCallb268a282010-08-23 23:25:46 +00004354 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004355}
4356
John McCalldadc5752010-08-24 06:29:42 +00004357ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004358Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004359 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004360 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004361 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004362 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004363
4364 TypeSourceInfo *TInfo;
4365 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4366 if (!TInfo)
4367 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4368
John McCallb268a282010-08-23 23:25:46 +00004369 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004370}
4371
John McCalldadc5752010-08-24 06:29:42 +00004372ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004373Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004374 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004375 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004376
Eli Friedman37a186d2008-05-20 05:22:08 +00004377 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004378 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4379 PDiag(diag::err_illegal_decl_array_incomplete_type)
4380 << SourceRange(LParenLoc,
4381 literalExpr->getSourceRange().getEnd())))
4382 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004383 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004384 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4385 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004386 } else if (!literalType->isDependentType() &&
4387 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004388 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004389 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004390 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004391 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004392
Douglas Gregor85dabae2009-12-16 01:38:02 +00004393 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004394 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004395 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004396 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004397 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004398 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004399 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004400 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004401 &literalType);
4402 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004403 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004404 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004405
Chris Lattner79413952008-12-04 23:50:19 +00004406 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004407 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004408 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004409 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004410 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004411
John McCall7decc9e2010-11-18 06:31:45 +00004412 // In C, compound literals are l-values for some reason.
4413 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4414
John McCall5d7aa7f2010-01-19 22:33:45 +00004415 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004416 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004417}
4418
John McCalldadc5752010-08-24 06:29:42 +00004419ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004420Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004421 SourceLocation RBraceLoc) {
4422 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004423 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004424
Steve Naroff30d242c2007-09-15 18:49:24 +00004425 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004427
Ted Kremenekac034612010-04-13 23:39:13 +00004428 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4429 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004430 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004431 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004432}
4433
John McCalld7646252010-11-14 08:17:51 +00004434/// Prepares for a scalar cast, performing all the necessary stages
4435/// except the final cast and returning the kind required.
4436static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4437 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4438 // Also, callers should have filtered out the invalid cases with
4439 // pointers. Everything else should be possible.
4440
John McCalle84af4e2010-11-13 01:35:44 +00004441 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004442 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004443 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004444
John McCall8cb679e2010-11-15 09:13:47 +00004445 switch (SrcTy->getScalarTypeKind()) {
4446 case Type::STK_MemberPointer:
4447 llvm_unreachable("member pointer type in C");
4448
4449 case Type::STK_Pointer:
4450 switch (DestTy->getScalarTypeKind()) {
4451 case Type::STK_Pointer:
4452 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004453 CK_AnyPointerToObjCPointerCast :
4454 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004455 case Type::STK_Bool:
4456 return CK_PointerToBoolean;
4457 case Type::STK_Integral:
4458 return CK_PointerToIntegral;
4459 case Type::STK_Floating:
4460 case Type::STK_FloatingComplex:
4461 case Type::STK_IntegralComplex:
4462 case Type::STK_MemberPointer:
4463 llvm_unreachable("illegal cast from pointer");
4464 }
4465 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004466
John McCall8cb679e2010-11-15 09:13:47 +00004467 case Type::STK_Bool: // casting from bool is like casting from an integer
4468 case Type::STK_Integral:
4469 switch (DestTy->getScalarTypeKind()) {
4470 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004471 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004472 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004473 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004474 case Type::STK_Bool:
4475 return CK_IntegralToBoolean;
4476 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004477 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004478 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004479 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004480 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004481 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004482 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004483 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4484 CK_IntegralToFloating);
4485 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004486 case Type::STK_MemberPointer:
4487 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004488 }
4489 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004490
John McCall8cb679e2010-11-15 09:13:47 +00004491 case Type::STK_Floating:
4492 switch (DestTy->getScalarTypeKind()) {
4493 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004494 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004495 case Type::STK_Bool:
4496 return CK_FloatingToBoolean;
4497 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004498 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004499 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004500 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004501 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004502 S.ImpCastExprToType(Src, cast<ComplexType>(DestTy)->getElementType(),
4503 CK_FloatingToIntegral);
4504 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004505 case Type::STK_Pointer:
4506 llvm_unreachable("valid float->pointer cast?");
4507 case Type::STK_MemberPointer:
4508 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004509 }
4510 break;
4511
John McCall8cb679e2010-11-15 09:13:47 +00004512 case Type::STK_FloatingComplex:
4513 switch (DestTy->getScalarTypeKind()) {
4514 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004515 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004516 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004517 return CK_FloatingComplexToIntegralComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004518 case Type::STK_Floating:
John McCalld7646252010-11-14 08:17:51 +00004519 return CK_FloatingComplexToReal;
John McCall8cb679e2010-11-15 09:13:47 +00004520 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004521 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004522 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004523 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4524 CK_FloatingComplexToReal);
4525 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004526 case Type::STK_Pointer:
4527 llvm_unreachable("valid complex float->pointer cast?");
4528 case Type::STK_MemberPointer:
4529 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004530 }
4531 break;
4532
John McCall8cb679e2010-11-15 09:13:47 +00004533 case Type::STK_IntegralComplex:
4534 switch (DestTy->getScalarTypeKind()) {
4535 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004536 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004537 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004538 return CK_IntegralComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004539 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004540 return CK_IntegralComplexToReal;
John McCall8cb679e2010-11-15 09:13:47 +00004541 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004542 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004543 case Type::STK_Floating:
John McCalld7646252010-11-14 08:17:51 +00004544 S.ImpCastExprToType(Src, cast<ComplexType>(SrcTy)->getElementType(),
4545 CK_IntegralComplexToReal);
4546 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004547 case Type::STK_Pointer:
4548 llvm_unreachable("valid complex int->pointer cast?");
4549 case Type::STK_MemberPointer:
4550 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004551 }
4552 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004553 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004554
John McCalld7646252010-11-14 08:17:51 +00004555 llvm_unreachable("Unhandled scalar cast");
4556 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004557}
4558
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004559/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004560bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4561 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4562 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004563 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004564 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4565 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004566 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004567 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004568
John McCall7decc9e2010-11-18 06:31:45 +00004569 // We only support r-value casts in C.
4570 VK = VK_RValue;
4571
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004572 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4573 // type needs to be scalar.
4574 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004575 // We don't necessarily do lvalue-to-rvalue conversions on this.
4576 IgnoredValueConversions(castExpr);
4577
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004578 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004579 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004580 return false;
4581 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004582
John McCall34376a62010-12-04 03:47:34 +00004583 DefaultFunctionArrayLvalueConversion(castExpr);
4584
Eli Friedmane98194d2010-07-17 20:43:49 +00004585 if (RequireCompleteType(TyR.getBegin(), castType,
4586 diag::err_typecheck_cast_to_incomplete))
4587 return true;
4588
Anders Carlssonef918ac2009-10-16 02:35:04 +00004589 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004590 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004591 (castType->isStructureType() || castType->isUnionType())) {
4592 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004593 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004594 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4595 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004596 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004597 return false;
4598 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004599
Anders Carlsson525b76b2009-10-16 02:48:28 +00004600 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004601 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004602 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004603 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004604 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004605 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004606 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004607 castExpr->getType()) &&
4608 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004609 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4610 << castExpr->getSourceRange();
4611 break;
4612 }
4613 }
4614 if (Field == FieldEnd)
4615 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4616 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004617 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004618 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004619 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004620
Anders Carlsson525b76b2009-10-16 02:48:28 +00004621 // Reject any other conversions to non-scalar types.
4622 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4623 << castType << castExpr->getSourceRange();
4624 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004625
John McCalld7646252010-11-14 08:17:51 +00004626 // The type we're casting to is known to be a scalar or vector.
4627
4628 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004629 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004630 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004631 return Diag(castExpr->getLocStart(),
4632 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004633 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004634 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004635
4636 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004637 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004638
Anders Carlsson525b76b2009-10-16 02:48:28 +00004639 if (castType->isVectorType())
4640 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4641 if (castExpr->getType()->isVectorType())
4642 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4643
John McCalld7646252010-11-14 08:17:51 +00004644 // The source and target types are both scalars, i.e.
4645 // - arithmetic types (fundamental, enum, and complex)
4646 // - all kinds of pointers
4647 // Note that member pointers were filtered out with C++, above.
4648
Anders Carlsson43d70f82009-10-16 05:23:41 +00004649 if (isa<ObjCSelectorExpr>(castExpr))
4650 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004651
John McCalld7646252010-11-14 08:17:51 +00004652 // If either type is a pointer, the other type has to be either an
4653 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004654 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004655 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004656 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004657 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004658 return Diag(castExpr->getLocStart(),
4659 diag::err_cast_pointer_from_non_pointer_int)
4660 << castExprType << castExpr->getSourceRange();
4661 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004662 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004663 return Diag(castExpr->getLocStart(),
4664 diag::err_cast_pointer_to_non_pointer_int)
4665 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004666 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004667
John McCalld7646252010-11-14 08:17:51 +00004668 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004669
John McCalld7646252010-11-14 08:17:51 +00004670 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004671 CheckCastAlign(castExpr, castType, TyR);
4672
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004673 return false;
4674}
4675
Anders Carlsson525b76b2009-10-16 02:48:28 +00004676bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004677 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004678 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004679
Anders Carlssonde71adf2007-11-27 05:51:55 +00004680 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004681 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004682 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004684 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004685 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004686 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004687 } else
4688 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004689 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004690 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004691
John McCalle3027922010-08-25 11:45:40 +00004692 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004693 return false;
4694}
4695
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004696bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004697 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004698 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004699
Anders Carlsson43d70f82009-10-16 05:23:41 +00004700 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004701
Nate Begemanc8961a42009-06-27 22:05:55 +00004702 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4703 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004704 if (SrcTy->isVectorType()) {
4705 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4706 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4707 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004708 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004709 return false;
4710 }
4711
Nate Begemanbd956c42009-06-28 02:36:38 +00004712 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004713 // conversion will take place first from scalar to elt type, and then
4714 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004715 if (SrcTy->isPointerType())
4716 return Diag(R.getBegin(),
4717 diag::err_invalid_conversion_between_vector_and_scalar)
4718 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004719
4720 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4721 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004722 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004723
John McCalle3027922010-08-25 11:45:40 +00004724 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004725 return false;
4726}
4727
John McCalldadc5752010-08-24 06:29:42 +00004728ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004729Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004730 SourceLocation RParenLoc, Expr *castExpr) {
4731 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004732 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004733
John McCall97513962010-01-15 18:39:57 +00004734 TypeSourceInfo *castTInfo;
4735 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4736 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004737 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004738
Nate Begeman5ec4b312009-08-10 23:49:36 +00004739 // If the Expr being casted is a ParenListExpr, handle it specially.
4740 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004741 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004742 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004743
John McCallb268a282010-08-23 23:25:46 +00004744 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004745}
4746
John McCalldadc5752010-08-24 06:29:42 +00004747ExprResult
John McCallebe54742010-01-15 18:56:44 +00004748Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004749 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004750 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004751 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004752 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004753 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004754 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004755 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004756
John McCallcf142162010-08-07 06:22:56 +00004757 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004758 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004759 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004760 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004761}
4762
Nate Begeman5ec4b312009-08-10 23:49:36 +00004763/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4764/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004765ExprResult
John McCallb268a282010-08-23 23:25:46 +00004766Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004767 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4768 if (!E)
4769 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004770
John McCalldadc5752010-08-24 06:29:42 +00004771 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004772
Nate Begeman5ec4b312009-08-10 23:49:36 +00004773 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004774 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4775 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004776
John McCallb268a282010-08-23 23:25:46 +00004777 if (Result.isInvalid()) return ExprError();
4778
4779 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004780}
4781
John McCalldadc5752010-08-24 06:29:42 +00004782ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004783Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004784 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004785 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004786 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004787 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004788 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004789
John Thompson781ad172010-06-30 22:55:51 +00004790 // Check for an altivec literal,
4791 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004792 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4793 if (PE->getNumExprs() == 0) {
4794 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4795 return ExprError();
4796 }
John Thompson781ad172010-06-30 22:55:51 +00004797 if (PE->getNumExprs() == 1) {
4798 if (!PE->getExpr(0)->getType()->isVectorType())
4799 isAltiVecLiteral = true;
4800 }
4801 else
4802 isAltiVecLiteral = true;
4803 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004804
John Thompson781ad172010-06-30 22:55:51 +00004805 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4806 // then handle it as such.
4807 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004808 llvm::SmallVector<Expr *, 8> initExprs;
4809 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4810 initExprs.push_back(PE->getExpr(i));
4811
4812 // FIXME: This means that pretty-printing the final AST will produce curly
4813 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004814 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4815 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004816 initExprs.size(), RParenLoc);
4817 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004818 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004819 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004820 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004821 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004822 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004823 if (Result.isInvalid()) return ExprError();
4824 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004825 }
4826}
4827
John McCalldadc5752010-08-24 06:29:42 +00004828ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004829 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004830 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004831 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004832 unsigned nexprs = Val.size();
4833 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004834 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4835 Expr *expr;
4836 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4837 expr = new (Context) ParenExpr(L, R, exprs[0]);
4838 else
4839 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004840 return Owned(expr);
4841}
4842
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004843/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4844/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004845/// C99 6.5.15
4846QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004847 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004848 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004849 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004850 // If both LHS and RHS are overloaded functions, try to resolve them.
4851 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4852 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4853 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4854 if (LHSResult.isInvalid())
4855 return QualType();
4856
4857 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4858 if (RHSResult.isInvalid())
4859 return QualType();
4860
4861 LHS = LHSResult.take();
4862 RHS = RHSResult.take();
4863 }
4864
Sebastian Redl1a99f442009-04-16 17:51:27 +00004865 // C++ is sufficiently different to merit its own checker.
4866 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004867 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4868 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004869
4870 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004871 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004872
Chris Lattner432cff52009-02-18 04:28:32 +00004873 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004874 if (SAVE) {
4875 SAVE = LHS = Cond;
4876 }
4877 else
4878 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004879 UsualUnaryConversions(RHS);
4880 QualType CondTy = Cond->getType();
4881 QualType LHSTy = LHS->getType();
4882 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004883
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004884 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004885 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004886 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4887 // Throw an error if its not either.
4888 if (getLangOptions().OpenCL) {
4889 if (!CondTy->isVectorType()) {
4890 Diag(Cond->getLocStart(),
4891 diag::err_typecheck_cond_expect_scalar_or_vector)
4892 << CondTy;
4893 return QualType();
4894 }
4895 }
4896 else {
4897 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4898 << CondTy;
4899 return QualType();
4900 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004901 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004902
Chris Lattnere2949f42008-01-06 22:42:25 +00004903 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004904 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4905 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004906
Nate Begemanabb5a732010-09-20 22:41:17 +00004907 // OpenCL: If the condition is a vector, and both operands are scalar,
4908 // attempt to implicity convert them to the vector type to act like the
4909 // built in select.
4910 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4911 // Both operands should be of scalar type.
4912 if (!LHSTy->isScalarType()) {
4913 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4914 << CondTy;
4915 return QualType();
4916 }
4917 if (!RHSTy->isScalarType()) {
4918 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4919 << CondTy;
4920 return QualType();
4921 }
4922 // Implicity convert these scalars to the type of the condition.
4923 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
4924 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
4925 }
4926
Chris Lattnere2949f42008-01-06 22:42:25 +00004927 // If both operands have arithmetic type, do the usual arithmetic conversions
4928 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004929 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4930 UsualArithmeticConversions(LHS, RHS);
4931 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004932 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004933
Chris Lattnere2949f42008-01-06 22:42:25 +00004934 // If both operands are the same structure or union type, the result is that
4935 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004936 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4937 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004938 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004939 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004940 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004941 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004942 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004943 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004944
Chris Lattnere2949f42008-01-06 22:42:25 +00004945 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004946 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004947 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4948 if (!LHSTy->isVoidType())
4949 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4950 << RHS->getSourceRange();
4951 if (!RHSTy->isVoidType())
4952 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4953 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004954 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
4955 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004956 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004957 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004958 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4959 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004960 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004961 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004962 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00004963 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004964 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004965 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004966 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004967 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00004968 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004969 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004970 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004971
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004972 // All objective-c pointer type analysis is done here.
4973 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4974 QuestionLoc);
4975 if (!compositeType.isNull())
4976 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004977
4978
Steve Naroff05efa972009-07-01 14:36:47 +00004979 // Handle block pointer types.
4980 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4981 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4982 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4983 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00004984 ImpCastExprToType(LHS, destType, CK_BitCast);
4985 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004986 return destType;
4987 }
4988 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004989 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004990 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004991 }
Steve Naroff05efa972009-07-01 14:36:47 +00004992 // We have 2 block pointer types.
4993 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4994 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004995 return LHSTy;
4996 }
Steve Naroff05efa972009-07-01 14:36:47 +00004997 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004998 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4999 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005000
Steve Naroff05efa972009-07-01 14:36:47 +00005001 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5002 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005003 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005004 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005005 // In this situation, we assume void* type. No especially good
5006 // reason, but this is what gcc does, and we do have to pick
5007 // to get a consistent AST.
5008 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005009 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5010 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005011 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005012 }
Steve Naroff05efa972009-07-01 14:36:47 +00005013 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005014 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5015 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005016 return LHSTy;
5017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005018
Steve Naroff05efa972009-07-01 14:36:47 +00005019 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5020 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5021 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005022 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5023 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005024
5025 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5026 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5027 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005028 QualType destPointee
5029 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005030 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005031 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005032 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005033 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005034 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005035 return destType;
5036 }
5037 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005038 QualType destPointee
5039 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005040 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005041 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005042 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005043 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005044 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005045 return destType;
5046 }
5047
5048 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5049 // Two identical pointer types are always compatible.
5050 return LHSTy;
5051 }
5052 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5053 rhptee.getUnqualifiedType())) {
5054 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5055 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5056 // In this situation, we assume void* type. No especially good
5057 // reason, but this is what gcc does, and we do have to pick
5058 // to get a consistent AST.
5059 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005060 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5061 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005062 return incompatTy;
5063 }
5064 // The pointer types are compatible.
5065 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5066 // differently qualified versions of compatible types, the result type is
5067 // a pointer to an appropriately qualified version of the *composite*
5068 // type.
5069 // FIXME: Need to calculate the composite type.
5070 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005071 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5072 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005073 return LHSTy;
5074 }
Mike Stump11289f42009-09-09 15:08:12 +00005075
John McCalle84af4e2010-11-13 01:35:44 +00005076 // GCC compatibility: soften pointer/integer mismatch. Note that
5077 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005078 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5079 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5080 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005081 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005082 return RHSTy;
5083 }
5084 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5085 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5086 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005087 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005088 return LHSTy;
5089 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005090
Chris Lattnere2949f42008-01-06 22:42:25 +00005091 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005092 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5093 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005094 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005095}
5096
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005097/// FindCompositeObjCPointerType - Helper method to find composite type of
5098/// two objective-c pointer types of the two input expressions.
5099QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5100 SourceLocation QuestionLoc) {
5101 QualType LHSTy = LHS->getType();
5102 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005103
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005104 // Handle things like Class and struct objc_class*. Here we case the result
5105 // to the pseudo-builtin, because that will be implicitly cast back to the
5106 // redefinition type if an attempt is made to access its fields.
5107 if (LHSTy->isObjCClassType() &&
5108 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005109 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005110 return LHSTy;
5111 }
5112 if (RHSTy->isObjCClassType() &&
5113 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005114 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005115 return RHSTy;
5116 }
5117 // And the same for struct objc_object* / id
5118 if (LHSTy->isObjCIdType() &&
5119 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005120 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005121 return LHSTy;
5122 }
5123 if (RHSTy->isObjCIdType() &&
5124 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005125 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005126 return RHSTy;
5127 }
5128 // And the same for struct objc_selector* / SEL
5129 if (Context.isObjCSelType(LHSTy) &&
5130 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005131 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005132 return LHSTy;
5133 }
5134 if (Context.isObjCSelType(RHSTy) &&
5135 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
John McCalle3027922010-08-25 11:45:40 +00005136 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005137 return RHSTy;
5138 }
5139 // Check constraints for Objective-C object pointers types.
5140 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005141
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005142 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5143 // Two identical object pointer types are always compatible.
5144 return LHSTy;
5145 }
5146 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5147 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5148 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005149
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005150 // If both operands are interfaces and either operand can be
5151 // assigned to the other, use that type as the composite
5152 // type. This allows
5153 // xxx ? (A*) a : (B*) b
5154 // where B is a subclass of A.
5155 //
5156 // Additionally, as for assignment, if either type is 'id'
5157 // allow silent coercion. Finally, if the types are
5158 // incompatible then make sure to use 'id' as the composite
5159 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005160
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005161 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5162 // It could return the composite type.
5163 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5164 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5165 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5166 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5167 } else if ((LHSTy->isObjCQualifiedIdType() ||
5168 RHSTy->isObjCQualifiedIdType()) &&
5169 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5170 // Need to handle "id<xx>" explicitly.
5171 // GCC allows qualified id and any Objective-C type to devolve to
5172 // id. Currently localizing to here until clear this should be
5173 // part of ObjCQualifiedIdTypesAreCompatible.
5174 compositeType = Context.getObjCIdType();
5175 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5176 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005177 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005178 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5179 ;
5180 else {
5181 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5182 << LHSTy << RHSTy
5183 << LHS->getSourceRange() << RHS->getSourceRange();
5184 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005185 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5186 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005187 return incompatTy;
5188 }
5189 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005190 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5191 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005192 return compositeType;
5193 }
5194 // Check Objective-C object pointer types and 'void *'
5195 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5196 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5197 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5198 QualType destPointee
5199 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5200 QualType destType = Context.getPointerType(destPointee);
5201 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005202 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005203 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005204 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005205 return destType;
5206 }
5207 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5208 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5209 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5210 QualType destPointee
5211 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5212 QualType destType = Context.getPointerType(destPointee);
5213 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005214 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005215 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005216 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005217 return destType;
5218 }
5219 return QualType();
5220}
5221
Steve Naroff83895f72007-09-16 03:34:24 +00005222/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005223/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005224ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005225 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005226 Expr *CondExpr, Expr *LHSExpr,
5227 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005228 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5229 // was the condition.
5230 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005231 Expr *SAVEExpr = 0;
5232 if (isLHSNull) {
5233 LHSExpr = SAVEExpr = CondExpr;
5234 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005235
John McCall7decc9e2010-11-18 06:31:45 +00005236 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005237 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005238 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005239 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005240 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005241 return ExprError();
5242
Douglas Gregor7e112b02009-08-26 14:37:04 +00005243 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005244 LHSExpr, ColonLoc,
5245 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005246 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005247}
5248
Steve Naroff3f597292007-05-11 22:18:03 +00005249// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005250// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005251// routine is it effectively iqnores the qualifiers on the top level pointee.
5252// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5253// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005254Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00005255Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00005256 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257
David Chisnall9f57c292009-08-17 16:35:33 +00005258 if ((lhsType->isObjCClassType() &&
5259 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
5260 (rhsType->isObjCClassType() &&
5261 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
5262 return Compatible;
5263 }
5264
Steve Naroff1f4d7272007-05-11 04:00:31 +00005265 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005266 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5267 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005268
Steve Naroff1f4d7272007-05-11 04:00:31 +00005269 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00005270 lhptee = Context.getCanonicalType(lhptee);
5271 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00005272
Chris Lattner9bad62c2008-01-04 18:04:52 +00005273 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005274
5275 // C99 6.5.16.1p1: This following citation is common to constraints
5276 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5277 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00005278 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00005279 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005280 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00005281
Mike Stump4e1f26a2009-02-19 03:04:26 +00005282 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5283 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005284 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005285 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005286 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005287 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005288
Chris Lattner0a788432008-01-03 22:56:36 +00005289 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005290 assert(rhptee->isFunctionType());
5291 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005292 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005293
Chris Lattner0a788432008-01-03 22:56:36 +00005294 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005295 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005296 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005297
5298 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005299 assert(lhptee->isFunctionType());
5300 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005301 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005302 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005303 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00005304 lhptee = lhptee.getUnqualifiedType();
5305 rhptee = rhptee.getUnqualifiedType();
5306 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5307 // Check if the pointee types are compatible ignoring the sign.
5308 // We explicitly check for char so that we catch "char" vs
5309 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005310 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005311 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005312 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005313 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005314
Chris Lattnerec3a1562009-10-17 20:33:28 +00005315 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005316 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005317 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005318 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005319
Eli Friedman80160bd2009-03-22 23:59:44 +00005320 if (lhptee == rhptee) {
5321 // Types are compatible ignoring the sign. Qualifier incompatibility
5322 // takes priority over sign incompatibility because the sign
5323 // warning can be disabled.
5324 if (ConvTy != Compatible)
5325 return ConvTy;
5326 return IncompatiblePointerSign;
5327 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005328
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005329 // If we are a multi-level pointer, it's possible that our issue is simply
5330 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5331 // the eventual target type is the same and the pointers have the same
5332 // level of indirection, this must be the issue.
5333 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5334 do {
5335 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5336 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005337
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005338 lhptee = Context.getCanonicalType(lhptee);
5339 rhptee = Context.getCanonicalType(rhptee);
5340 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005341
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005342 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00005343 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005344 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005345
Eli Friedman80160bd2009-03-22 23:59:44 +00005346 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00005347 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005348 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005349 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005350}
5351
Steve Naroff081c7422008-09-04 15:10:53 +00005352/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5353/// block pointer types are compatible or whether a block and normal pointer
5354/// are compatible. It is more restrict than comparing two function pointer
5355// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005356Sema::AssignConvertType
5357Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00005358 QualType rhsType) {
5359 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005360
Steve Naroff081c7422008-09-04 15:10:53 +00005361 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005362 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5363 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005364
Steve Naroff081c7422008-09-04 15:10:53 +00005365 // make sure we operate on the canonical type
5366 lhptee = Context.getCanonicalType(lhptee);
5367 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005368
Steve Naroff081c7422008-09-04 15:10:53 +00005369 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005370
Steve Naroff081c7422008-09-04 15:10:53 +00005371 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005372 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00005373 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005374
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005375 if (!getLangOptions().CPlusPlus) {
5376 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5377 return IncompatibleBlockPointer;
5378 }
5379 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005380 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005381 return ConvTy;
5382}
5383
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005384/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5385/// for assignment compatibility.
5386Sema::AssignConvertType
5387Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005388 if (lhsType->isObjCBuiltinType()) {
5389 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005390 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5391 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005392 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005393 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005394 }
5395 if (rhsType->isObjCBuiltinType()) {
5396 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005397 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5398 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005399 return IncompatiblePointer;
5400 return Compatible;
5401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005402 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005403 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005404 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005405 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5406 // make sure we operate on the canonical type
5407 lhptee = Context.getCanonicalType(lhptee);
5408 rhptee = Context.getCanonicalType(rhptee);
5409 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5410 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005411
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005412 if (Context.typesAreCompatible(lhsType, rhsType))
5413 return Compatible;
5414 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5415 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005416 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005417}
5418
John McCall29600e12010-11-16 02:32:08 +00005419Sema::AssignConvertType
5420Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5421 // Fake up an opaque expression. We don't actually care about what
5422 // cast operations are required, so if CheckAssignmentConstraints
5423 // adds casts to this they'll be wasted, but fortunately that doesn't
5424 // usually happen on valid code.
5425 OpaqueValueExpr rhs(rhsType, VK_RValue);
5426 Expr *rhsPtr = &rhs;
5427 CastKind K = CK_Invalid;
5428
5429 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5430}
5431
Mike Stump4e1f26a2009-02-19 03:04:26 +00005432/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5433/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005434/// pointers. Here are some objectionable examples that GCC considers warnings:
5435///
5436/// int a, *pint;
5437/// short *pshort;
5438/// struct foo *pfoo;
5439///
5440/// pint = pshort; // warning: assignment from incompatible pointer type
5441/// a = pint; // warning: assignment makes integer from pointer without a cast
5442/// pint = a; // warning: assignment makes pointer from integer without a cast
5443/// pint = pfoo; // warning: assignment from incompatible pointer type
5444///
5445/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005447///
John McCall8cb679e2010-11-15 09:13:47 +00005448/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005449Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005450Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005451 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005452 QualType rhsType = rhs->getType();
5453
Chris Lattnera52c2f22008-01-04 23:18:45 +00005454 // Get canonical types. We're not formatting these types, just comparing
5455 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005456 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5457 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005458
John McCall8cb679e2010-11-15 09:13:47 +00005459 if (lhsType == rhsType) {
5460 Kind = CK_NoOp;
Chris Lattnerf5c973d2008-01-07 17:51:46 +00005461 return Compatible; // Common case: fast path an exact match.
John McCall8cb679e2010-11-15 09:13:47 +00005462 }
Steve Naroff44fd8ff2007-07-24 21:46:40 +00005463
David Chisnall9f57c292009-08-17 16:35:33 +00005464 if ((lhsType->isObjCClassType() &&
5465 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
5466 (rhsType->isObjCClassType() &&
5467 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
John McCall8cb679e2010-11-15 09:13:47 +00005468 Kind = CK_BitCast;
5469 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005470 }
5471
Douglas Gregor6b754842008-10-28 00:22:11 +00005472 // If the left-hand side is a reference type, then we are in a
5473 // (rare!) case where we've allowed the use of references in C,
5474 // e.g., as a parameter type in a built-in function. In this case,
5475 // just make sure that the type referenced is compatible with the
5476 // right-hand side type. The caller is responsible for adjusting
5477 // lhsType so that the resulting expression does not have reference
5478 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005479 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005480 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5481 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005482 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005483 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005484 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005485 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005486 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5487 // to the same ExtVector type.
5488 if (lhsType->isExtVectorType()) {
5489 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005490 return Incompatible;
5491 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005492 // CK_VectorSplat does T -> vector T, so first cast to the
5493 // element type.
5494 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5495 if (elType != rhsType) {
5496 Kind = PrepareScalarCast(*this, rhs, elType);
5497 ImpCastExprToType(rhs, elType, Kind);
5498 }
5499 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005500 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005501 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005502 }
Mike Stump11289f42009-09-09 15:08:12 +00005503
Nate Begeman191a6b12008-07-14 18:02:46 +00005504 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005505 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005506 // Allow assignments of an AltiVec vector type to an equivalent GCC
5507 // vector type and vice versa
5508 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5509 Kind = CK_BitCast;
5510 return Compatible;
5511 }
5512
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005513 // If we are allowing lax vector conversions, and LHS and RHS are both
5514 // vectors, the total size only needs to be the same. This is a bitcast;
5515 // no bits are changed but the result type is different.
5516 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005517 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005518 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005519 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005520 }
Chris Lattner881a2122008-01-04 23:32:24 +00005521 }
5522 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005523 }
Eli Friedman3360d892008-05-30 18:07:22 +00005524
Douglas Gregorbea453a2010-05-23 21:53:47 +00005525 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005526 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005527 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005528 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005529 }
Eli Friedman3360d892008-05-30 18:07:22 +00005530
Chris Lattnerec646832008-04-07 06:49:41 +00005531 if (isa<PointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005532 if (rhsType->isIntegerType()) {
5533 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattner940cfeb2008-01-04 18:22:42 +00005534 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005535 }
Eli Friedman3360d892008-05-30 18:07:22 +00005536
John McCall8cb679e2010-11-15 09:13:47 +00005537 if (isa<PointerType>(rhsType)) {
5538 Kind = CK_BitCast;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005539 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005541
Steve Naroffaccc4882009-07-20 17:56:53 +00005542 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005543 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005544 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005545 if (lhsType->isVoidPointerType()) // an exception to the rule.
5546 return Compatible;
5547 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005548 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005549 if (rhsType->getAs<BlockPointerType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005550 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5551 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005552 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005553 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005554
5555 // Treat block pointers as objects.
John McCall8cb679e2010-11-15 09:13:47 +00005556 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5557 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005558 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005559 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005560 }
Steve Naroff081c7422008-09-04 15:10:53 +00005561 return Incompatible;
5562 }
5563
5564 if (isa<BlockPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005565 if (rhsType->isIntegerType()) {
5566 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005567 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005568 }
5569
5570 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005571
Steve Naroff32d072c2008-09-29 18:10:17 +00005572 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005573 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00005574 return Compatible;
5575
Steve Naroff081c7422008-09-04 15:10:53 +00005576 if (rhsType->isBlockPointerType())
5577 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005578
John McCall8cb679e2010-11-15 09:13:47 +00005579 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff081c7422008-09-04 15:10:53 +00005580 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00005581 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005582
Chris Lattnera52c2f22008-01-04 23:18:45 +00005583 return Incompatible;
5584 }
5585
Steve Naroff7cae42b2009-07-10 23:34:53 +00005586 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005587 if (rhsType->isIntegerType()) {
5588 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005589 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005590 }
5591
5592 Kind = CK_BitCast;
Mike Stump11289f42009-09-09 15:08:12 +00005593
Steve Naroffaccc4882009-07-20 17:56:53 +00005594 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005596 if (rhsType->isVoidPointerType()) // an exception to the rule.
5597 return Compatible;
5598 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005599 }
5600 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005601 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005602 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005603 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005604 if (RHSPT->getPointeeType()->isVoidType())
5605 return Compatible;
5606 }
5607 // Treat block pointers as objects.
5608 if (rhsType->isBlockPointerType())
5609 return Compatible;
5610 return Incompatible;
5611 }
Chris Lattnerec646832008-04-07 06:49:41 +00005612 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00005613 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005614 if (lhsType == Context.BoolTy) {
5615 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005616 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005617 }
Eli Friedman3360d892008-05-30 18:07:22 +00005618
John McCall8cb679e2010-11-15 09:13:47 +00005619 if (lhsType->isIntegerType()) {
5620 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005621 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005622 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005623
5624 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005625 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5626 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005627 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005628 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005629 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005630 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005631 if (isa<ObjCObjectPointerType>(rhsType)) {
5632 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005633 if (lhsType == Context.BoolTy) {
5634 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005635 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005636 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005637
John McCall8cb679e2010-11-15 09:13:47 +00005638 if (lhsType->isIntegerType()) {
5639 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005640 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005641 }
5642
5643 Kind = CK_BitCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005644
Steve Naroffaccc4882009-07-20 17:56:53 +00005645 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005646 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005647 if (lhsType->isVoidPointerType()) // an exception to the rule.
5648 return Compatible;
5649 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005650 }
5651 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005652 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5653 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005654 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005655 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005656 return Incompatible;
5657 }
Eli Friedman3360d892008-05-30 18:07:22 +00005658
Chris Lattnera52c2f22008-01-04 23:18:45 +00005659 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005660 if (Context.typesAreCompatible(lhsType, rhsType)) {
5661 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005662 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005663 }
Bill Wendling216423b2007-05-30 06:30:29 +00005664 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00005665 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005666}
5667
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005668/// \brief Constructs a transparent union from an expression that is
5669/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005670static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005671 QualType UnionType, FieldDecl *Field) {
5672 // Build an initializer list that designates the appropriate member
5673 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005674 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005675 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005676 SourceLocation());
5677 Initializer->setType(UnionType);
5678 Initializer->setInitializedFieldInUnion(Field);
5679
5680 // Build a compound literal constructing a value of the transparent
5681 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005682 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005683 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005684 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005685}
5686
5687Sema::AssignConvertType
5688Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5689 QualType FromType = rExpr->getType();
5690
Mike Stump11289f42009-09-09 15:08:12 +00005691 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005692 // transparent_union GCC extension.
5693 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005694 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005695 return Incompatible;
5696
5697 // The field to initialize within the transparent union.
5698 RecordDecl *UD = UT->getDecl();
5699 FieldDecl *InitField = 0;
5700 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005701 for (RecordDecl::field_iterator it = UD->field_begin(),
5702 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005703 it != itend; ++it) {
5704 if (it->getType()->isPointerType()) {
5705 // If the transparent union contains a pointer type, we allow:
5706 // 1) void pointer
5707 // 2) null pointer constant
5708 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005709 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005710 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005711 InitField = *it;
5712 break;
5713 }
Mike Stump11289f42009-09-09 15:08:12 +00005714
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005715 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005716 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005717 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005718 InitField = *it;
5719 break;
5720 }
5721 }
5722
John McCall29600e12010-11-16 02:32:08 +00005723 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005724 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005725 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005726 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005727 ImpCastExprToType(rhs, it->getType(), Kind);
5728 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005729 InitField = *it;
5730 break;
5731 }
5732 }
5733
5734 if (!InitField)
5735 return Incompatible;
5736
5737 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5738 return Compatible;
5739}
5740
Chris Lattner9bad62c2008-01-04 18:04:52 +00005741Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005742Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005743 if (getLangOptions().CPlusPlus) {
5744 if (!lhsType->isRecordType()) {
5745 // C++ 5.17p3: If the left operand is not of class type, the
5746 // expression is implicitly converted (C++ 4) to the
5747 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005748 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005749 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005750 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005751 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005752 }
5753
5754 // FIXME: Currently, we fall through and treat C++ classes like C
5755 // structures.
John McCall34376a62010-12-04 03:47:34 +00005756 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005757
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005758 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5759 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005760 if ((lhsType->isPointerType() ||
5761 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005762 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005763 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005764 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005765 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005766 return Compatible;
5767 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005768
Chris Lattnere6dcd502007-10-16 02:55:40 +00005769 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005770 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005771 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005772 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005773 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005774 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005775 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005776 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005777
John McCall8cb679e2010-11-15 09:13:47 +00005778 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005779 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005780 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005781
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005782 // C99 6.5.16.1p2: The value of the right operand is converted to the
5783 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005784 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5785 // so that we can use references in built-in functions even in C.
5786 // The getNonReferenceType() call makes sure that the resulting expression
5787 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005788 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005789 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005790 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005791}
5792
Chris Lattner326f7572008-11-18 01:30:42 +00005793QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005794 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005795 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005796 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005797 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005798}
5799
Chris Lattnerfaa54172010-01-12 21:23:57 +00005800QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005801 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005802 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005803 QualType lhsType =
5804 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5805 QualType rhsType =
5806 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005807
Nate Begeman191a6b12008-07-14 18:02:46 +00005808 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005809 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005810 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005811
Nate Begeman191a6b12008-07-14 18:02:46 +00005812 // Handle the case of a vector & extvector type of the same size and element
5813 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005814 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005815 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005816 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005817 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005818 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005819 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005820 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005821 return lhsType;
5822 }
5823
John McCalle3027922010-08-25 11:45:40 +00005824 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005825 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005826 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5827 // If we are allowing lax vector conversions, and LHS and RHS are both
5828 // vectors, the total size only needs to be the same. This is a
5829 // bitcast; no bits are changed but the result type is different.
5830 ImpCastExprToType(rex, lhsType, CK_BitCast);
5831 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005832 }
Eric Christophera613f562010-08-26 00:42:16 +00005833 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005834 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005835 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005836
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005837 // Handle the case of equivalent AltiVec and GCC vector types
5838 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5839 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005840 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005841 return rhsType;
5842 }
5843
Nate Begemanbd956c42009-06-28 02:36:38 +00005844 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5845 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5846 bool swapped = false;
5847 if (rhsType->isExtVectorType()) {
5848 swapped = true;
5849 std::swap(rex, lex);
5850 std::swap(rhsType, lhsType);
5851 }
Mike Stump11289f42009-09-09 15:08:12 +00005852
Nate Begeman886448d2009-06-28 19:12:57 +00005853 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005854 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005855 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005856 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005857 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5858 if (order > 0)
5859 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5860 if (order >= 0) {
5861 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005862 if (swapped) std::swap(rex, lex);
5863 return lhsType;
5864 }
5865 }
5866 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5867 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005868 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5869 if (order > 0)
5870 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5871 if (order >= 0) {
5872 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005873 if (swapped) std::swap(rex, lex);
5874 return lhsType;
5875 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005876 }
5877 }
Mike Stump11289f42009-09-09 15:08:12 +00005878
Nate Begeman886448d2009-06-28 19:12:57 +00005879 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005880 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005881 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005882 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005883 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005884}
5885
Chris Lattnerfaa54172010-01-12 21:23:57 +00005886QualType Sema::CheckMultiplyDivideOperands(
5887 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005888 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005889 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005890
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005891 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005892
Chris Lattnerfaa54172010-01-12 21:23:57 +00005893 if (!lex->getType()->isArithmeticType() ||
5894 !rex->getType()->isArithmeticType())
5895 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005896
Chris Lattnerfaa54172010-01-12 21:23:57 +00005897 // Check for division by zero.
5898 if (isDiv &&
5899 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005900 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005901 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005902
Chris Lattnerfaa54172010-01-12 21:23:57 +00005903 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005904}
5905
Chris Lattnerfaa54172010-01-12 21:23:57 +00005906QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005907 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005908 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005909 if (lex->getType()->hasIntegerRepresentation() &&
5910 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005911 return CheckVectorOperands(Loc, lex, rex);
5912 return InvalidOperands(Loc, lex, rex);
5913 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005914
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005915 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005916
Chris Lattnerfaa54172010-01-12 21:23:57 +00005917 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5918 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005919
Chris Lattnerfaa54172010-01-12 21:23:57 +00005920 // Check for remainder by zero.
5921 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005922 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5923 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005924
Chris Lattnerfaa54172010-01-12 21:23:57 +00005925 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005926}
5927
Chris Lattnerfaa54172010-01-12 21:23:57 +00005928QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005929 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005930 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5931 QualType compType = CheckVectorOperands(Loc, lex, rex);
5932 if (CompLHSTy) *CompLHSTy = compType;
5933 return compType;
5934 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005935
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005936 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005937
Steve Naroffe4718892007-04-27 18:30:00 +00005938 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005939 if (lex->getType()->isArithmeticType() &&
5940 rex->getType()->isArithmeticType()) {
5941 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005942 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005943 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005944
Eli Friedman8e122982008-05-18 18:08:51 +00005945 // Put any potential pointer into PExp
5946 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005947 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005948 std::swap(PExp, IExp);
5949
Steve Naroff6b712a72009-07-14 18:25:06 +00005950 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005951
Eli Friedman8e122982008-05-18 18:08:51 +00005952 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005953 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005954
Chris Lattner12bdebb2009-04-24 23:50:08 +00005955 // Check for arithmetic on pointers to incomplete types.
5956 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005957 if (getLangOptions().CPlusPlus) {
5958 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005959 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005960 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005961 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005962
5963 // GNU extension: arithmetic on pointer to void
5964 Diag(Loc, diag::ext_gnu_void_ptr)
5965 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005966 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005967 if (getLangOptions().CPlusPlus) {
5968 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5969 << lex->getType() << lex->getSourceRange();
5970 return QualType();
5971 }
5972
5973 // GNU extension: arithmetic on pointer to function
5974 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5975 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005976 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005977 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005978 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005979 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005980 PExp->getType()->isObjCObjectPointerType()) &&
5981 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005982 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5983 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005984 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005985 return QualType();
5986 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005987 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005988 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005989 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5990 << PointeeTy << PExp->getSourceRange();
5991 return QualType();
5992 }
Mike Stump11289f42009-09-09 15:08:12 +00005993
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005994 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005995 QualType LHSTy = Context.isPromotableBitField(lex);
5996 if (LHSTy.isNull()) {
5997 LHSTy = lex->getType();
5998 if (LHSTy->isPromotableIntegerType())
5999 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006000 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006001 *CompLHSTy = LHSTy;
6002 }
Eli Friedman8e122982008-05-18 18:08:51 +00006003 return PExp->getType();
6004 }
6005 }
6006
Chris Lattner326f7572008-11-18 01:30:42 +00006007 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006008}
6009
Chris Lattner2a3569b2008-04-07 05:30:13 +00006010// C99 6.5.6
6011QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006012 SourceLocation Loc, QualType* CompLHSTy) {
6013 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6014 QualType compType = CheckVectorOperands(Loc, lex, rex);
6015 if (CompLHSTy) *CompLHSTy = compType;
6016 return compType;
6017 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006018
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006019 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006020
Chris Lattner4d62f422007-12-09 21:53:25 +00006021 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006022
Chris Lattner4d62f422007-12-09 21:53:25 +00006023 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006024 if (lex->getType()->isArithmeticType()
6025 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006026 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006027 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006028 }
Mike Stump11289f42009-09-09 15:08:12 +00006029
Chris Lattner4d62f422007-12-09 21:53:25 +00006030 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006031 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006032 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006033
Douglas Gregorac1fb652009-03-24 19:52:54 +00006034 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006035
Douglas Gregorac1fb652009-03-24 19:52:54 +00006036 bool ComplainAboutVoid = false;
6037 Expr *ComplainAboutFunc = 0;
6038 if (lpointee->isVoidType()) {
6039 if (getLangOptions().CPlusPlus) {
6040 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6041 << lex->getSourceRange() << rex->getSourceRange();
6042 return QualType();
6043 }
6044
6045 // GNU C extension: arithmetic on pointer to void
6046 ComplainAboutVoid = true;
6047 } else if (lpointee->isFunctionType()) {
6048 if (getLangOptions().CPlusPlus) {
6049 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006050 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006051 return QualType();
6052 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006053
6054 // GNU C extension: arithmetic on pointer to function
6055 ComplainAboutFunc = lex;
6056 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006057 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006058 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006059 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006060 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006061 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006062
Chris Lattner12bdebb2009-04-24 23:50:08 +00006063 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006064 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006065 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6066 << lpointee << lex->getSourceRange();
6067 return QualType();
6068 }
Mike Stump11289f42009-09-09 15:08:12 +00006069
Chris Lattner4d62f422007-12-09 21:53:25 +00006070 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006071 if (rex->getType()->isIntegerType()) {
6072 if (ComplainAboutVoid)
6073 Diag(Loc, diag::ext_gnu_void_ptr)
6074 << lex->getSourceRange() << rex->getSourceRange();
6075 if (ComplainAboutFunc)
6076 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006077 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006078 << ComplainAboutFunc->getSourceRange();
6079
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006080 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006081 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006082 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006083
Chris Lattner4d62f422007-12-09 21:53:25 +00006084 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006085 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006086 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006087
Douglas Gregorac1fb652009-03-24 19:52:54 +00006088 // RHS must be a completely-type object type.
6089 // Handle the GNU void* extension.
6090 if (rpointee->isVoidType()) {
6091 if (getLangOptions().CPlusPlus) {
6092 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6093 << lex->getSourceRange() << rex->getSourceRange();
6094 return QualType();
6095 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006096
Douglas Gregorac1fb652009-03-24 19:52:54 +00006097 ComplainAboutVoid = true;
6098 } else if (rpointee->isFunctionType()) {
6099 if (getLangOptions().CPlusPlus) {
6100 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006101 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006102 return QualType();
6103 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006104
6105 // GNU extension: arithmetic on pointer to function
6106 if (!ComplainAboutFunc)
6107 ComplainAboutFunc = rex;
6108 } else if (!rpointee->isDependentType() &&
6109 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006110 PDiag(diag::err_typecheck_sub_ptr_object)
6111 << rex->getSourceRange()
6112 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006113 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006114
Eli Friedman168fe152009-05-16 13:54:38 +00006115 if (getLangOptions().CPlusPlus) {
6116 // Pointee types must be the same: C++ [expr.add]
6117 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6118 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6119 << lex->getType() << rex->getType()
6120 << lex->getSourceRange() << rex->getSourceRange();
6121 return QualType();
6122 }
6123 } else {
6124 // Pointee types must be compatible C99 6.5.6p3
6125 if (!Context.typesAreCompatible(
6126 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6127 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6128 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6129 << lex->getType() << rex->getType()
6130 << lex->getSourceRange() << rex->getSourceRange();
6131 return QualType();
6132 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006133 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006134
Douglas Gregorac1fb652009-03-24 19:52:54 +00006135 if (ComplainAboutVoid)
6136 Diag(Loc, diag::ext_gnu_void_ptr)
6137 << lex->getSourceRange() << rex->getSourceRange();
6138 if (ComplainAboutFunc)
6139 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006140 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006141 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006142
6143 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006144 return Context.getPointerDiffType();
6145 }
6146 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006147
Chris Lattner326f7572008-11-18 01:30:42 +00006148 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006149}
6150
Douglas Gregor0bf31402010-10-08 23:50:27 +00006151static bool isScopedEnumerationType(QualType T) {
6152 if (const EnumType *ET = dyn_cast<EnumType>(T))
6153 return ET->getDecl()->isScoped();
6154 return false;
6155}
6156
Chris Lattner2a3569b2008-04-07 05:30:13 +00006157// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006158QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006159 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006160 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006161 if (!lex->getType()->hasIntegerRepresentation() ||
6162 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006163 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006164
Douglas Gregor0bf31402010-10-08 23:50:27 +00006165 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6166 // hasIntegerRepresentation() above instead of this.
6167 if (isScopedEnumerationType(lex->getType()) ||
6168 isScopedEnumerationType(rex->getType())) {
6169 return InvalidOperands(Loc, lex, rex);
6170 }
6171
Nate Begemane46ee9a2009-10-25 02:26:48 +00006172 // Vector shifts promote their scalar inputs to vector type.
6173 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6174 return CheckVectorOperands(Loc, lex, rex);
6175
Chris Lattner5c11c412007-12-12 05:47:28 +00006176 // Shifts don't perform usual arithmetic conversions, they just do integer
6177 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00006178 QualType LHSTy = Context.isPromotableBitField(lex);
6179 if (LHSTy.isNull()) {
6180 LHSTy = lex->getType();
6181 if (LHSTy->isPromotableIntegerType())
6182 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006183 }
Chris Lattner3c133402007-12-13 07:28:16 +00006184 if (!isCompAssign)
John McCalle3027922010-08-25 11:45:40 +00006185 ImpCastExprToType(lex, LHSTy, CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006186
Chris Lattner5c11c412007-12-12 05:47:28 +00006187 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006188
Ryan Flynnf53fab82009-08-07 16:20:20 +00006189 // Sanity-check shift operands
6190 llvm::APSInt Right;
6191 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006192 if (!rex->isValueDependent() &&
6193 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006194 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006195 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6196 else {
6197 llvm::APInt LeftBits(Right.getBitWidth(),
6198 Context.getTypeSize(lex->getType()));
6199 if (Right.uge(LeftBits))
6200 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6201 }
6202 }
6203
Chris Lattner5c11c412007-12-12 05:47:28 +00006204 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006205 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006206}
6207
Chandler Carruth17773fc2010-07-10 12:30:03 +00006208static bool IsWithinTemplateSpecialization(Decl *D) {
6209 if (DeclContext *DC = D->getDeclContext()) {
6210 if (isa<ClassTemplateSpecializationDecl>(DC))
6211 return true;
6212 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6213 return FD->isFunctionTemplateSpecialization();
6214 }
6215 return false;
6216}
6217
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006218// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006219QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006220 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006221 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006222
Chris Lattner9a152e22009-12-05 05:40:13 +00006223 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006224 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006225 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006226
Steve Naroff31090012007-07-16 21:54:35 +00006227 QualType lType = lex->getType();
6228 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006229
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006230 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006231 !(lType->isBlockPointerType() && isRelational) &&
6232 !lex->getLocStart().isMacroID() &&
6233 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006234 // For non-floating point types, check for self-comparisons of the form
6235 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6236 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006237 //
6238 // NOTE: Don't warn about comparison expressions resulting from macro
6239 // expansion. Also don't warn about comparisons which are only self
6240 // comparisons within a template specialization. The warnings should catch
6241 // obvious cases in the definition of the template anyways. The idea is to
6242 // warn when the typed comparison operator will always evaluate to the same
6243 // result.
John McCall34376a62010-12-04 03:47:34 +00006244 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6245 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006246 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006247 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006248 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006249 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006250 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6251 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006252 << (Opc == BO_EQ
6253 || Opc == BO_LE
6254 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006255 } else if (lType->isArrayType() && rType->isArrayType() &&
6256 !DRL->getDecl()->getType()->isReferenceType() &&
6257 !DRR->getDecl()->getType()->isReferenceType()) {
6258 // what is it always going to eval to?
6259 char always_evals_to;
6260 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006261 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006262 always_evals_to = 0; // false
6263 break;
John McCalle3027922010-08-25 11:45:40 +00006264 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006265 always_evals_to = 1; // true
6266 break;
6267 default:
6268 // best we can say is 'a constant'
6269 always_evals_to = 2; // e.g. array1 <= array2
6270 break;
6271 }
6272 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6273 << 1 // array
6274 << always_evals_to);
6275 }
6276 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006277 }
Mike Stump11289f42009-09-09 15:08:12 +00006278
Chris Lattner222b8bd2009-03-08 19:39:53 +00006279 if (isa<CastExpr>(LHSStripped))
6280 LHSStripped = LHSStripped->IgnoreParenCasts();
6281 if (isa<CastExpr>(RHSStripped))
6282 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006283
Chris Lattner222b8bd2009-03-08 19:39:53 +00006284 // Warn about comparisons against a string constant (unless the other
6285 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006286 Expr *literalString = 0;
6287 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006288 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006289 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006290 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006291 literalString = lex;
6292 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006293 } else if ((isa<StringLiteral>(RHSStripped) ||
6294 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006295 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006296 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006297 literalString = rex;
6298 literalStringStripped = RHSStripped;
6299 }
6300
6301 if (literalString) {
6302 std::string resultComparison;
6303 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006304 case BO_LT: resultComparison = ") < 0"; break;
6305 case BO_GT: resultComparison = ") > 0"; break;
6306 case BO_LE: resultComparison = ") <= 0"; break;
6307 case BO_GE: resultComparison = ") >= 0"; break;
6308 case BO_EQ: resultComparison = ") == 0"; break;
6309 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006310 default: assert(false && "Invalid comparison operator");
6311 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006312
Douglas Gregor49862b82010-01-12 23:18:54 +00006313 DiagRuntimeBehavior(Loc,
6314 PDiag(diag::warn_stringcompare)
6315 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006316 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006317 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319
Douglas Gregorec170db2010-06-08 19:50:34 +00006320 // C99 6.5.8p3 / C99 6.5.9p4
6321 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6322 UsualArithmeticConversions(lex, rex);
6323 else {
6324 UsualUnaryConversions(lex);
6325 UsualUnaryConversions(rex);
6326 }
6327
6328 lType = lex->getType();
6329 rType = rex->getType();
6330
Douglas Gregorca63811b2008-11-19 03:25:36 +00006331 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006332 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006333
Chris Lattnerb620c342007-08-26 01:18:55 +00006334 if (isRelational) {
6335 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006336 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006337 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006338 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006339 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006340 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006341
Chris Lattnerb620c342007-08-26 01:18:55 +00006342 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006343 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006344 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006345
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006346 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006347 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006348 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006349 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006350
Douglas Gregorf267edd2010-06-15 21:38:40 +00006351 // All of the following pointer-related warnings are GCC extensions, except
6352 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006353 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006354 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006355 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006356 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006357 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006358
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006359 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006360 if (LCanPointeeTy == RCanPointeeTy)
6361 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006362 if (!isRelational &&
6363 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6364 // Valid unless comparison between non-null pointer and function pointer
6365 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006366 // In a SFINAE context, we treat this as a hard error to maintain
6367 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006368 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6369 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006370 Diag(Loc,
6371 isSFINAEContext()?
6372 diag::err_typecheck_comparison_of_fptr_to_void
6373 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006374 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006375
6376 if (isSFINAEContext())
6377 return QualType();
6378
John McCalle3027922010-08-25 11:45:40 +00006379 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006380 return ResultTy;
6381 }
6382 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006383
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006384 // C++ [expr.rel]p2:
6385 // [...] Pointer conversions (4.10) and qualification
6386 // conversions (4.4) are performed on pointer operands (or on
6387 // a pointer operand and a null pointer constant) to bring
6388 // them to their composite pointer type. [...]
6389 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006390 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006391 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006392 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006393 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006394 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006395 if (T.isNull()) {
6396 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6397 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6398 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006399 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006400 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006401 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006402 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006403 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006404 }
6405
John McCalle3027922010-08-25 11:45:40 +00006406 ImpCastExprToType(lex, T, CK_BitCast);
6407 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006408 return ResultTy;
6409 }
Eli Friedman16c209612009-08-23 00:27:47 +00006410 // C99 6.5.9p2 and C99 6.5.8p2
6411 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6412 RCanPointeeTy.getUnqualifiedType())) {
6413 // Valid unless a relational comparison of function pointers
6414 if (isRelational && LCanPointeeTy->isFunctionType()) {
6415 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6416 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6417 }
6418 } else if (!isRelational &&
6419 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6420 // Valid unless comparison between non-null pointer and function pointer
6421 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6422 && !LHSIsNull && !RHSIsNull) {
6423 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6424 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6425 }
6426 } else {
6427 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006428 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006429 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006430 }
Eli Friedman16c209612009-08-23 00:27:47 +00006431 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006432 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006433 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006434 }
Mike Stump11289f42009-09-09 15:08:12 +00006435
Sebastian Redl576fd422009-05-10 18:38:11 +00006436 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006437 // Comparison of nullptr_t with itself.
6438 if (lType->isNullPtrType() && rType->isNullPtrType())
6439 return ResultTy;
6440
Mike Stump11289f42009-09-09 15:08:12 +00006441 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006442 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006443 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006444 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006445 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006446 ImpCastExprToType(rex, lType,
6447 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006448 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006449 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006450 return ResultTy;
6451 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006452 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006453 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006454 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006455 ImpCastExprToType(lex, rType,
6456 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006457 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006458 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006459 return ResultTy;
6460 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006461
6462 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006463 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006464 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6465 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006466 // In addition, pointers to members can be compared, or a pointer to
6467 // member and a null pointer constant. Pointer to member conversions
6468 // (4.11) and qualification conversions (4.4) are performed to bring
6469 // them to a common type. If one operand is a null pointer constant,
6470 // the common type is the type of the other operand. Otherwise, the
6471 // common type is a pointer to member type similar (4.4) to the type
6472 // of one of the operands, with a cv-qualification signature (4.4)
6473 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006474 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006475 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006476 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006477 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006478 if (T.isNull()) {
6479 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006480 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006481 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006482 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006483 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006484 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006485 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006486 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006487 }
Mike Stump11289f42009-09-09 15:08:12 +00006488
John McCalle3027922010-08-25 11:45:40 +00006489 ImpCastExprToType(lex, T, CK_BitCast);
6490 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006491 return ResultTy;
6492 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006493 }
Mike Stump11289f42009-09-09 15:08:12 +00006494
Steve Naroff081c7422008-09-04 15:10:53 +00006495 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006496 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006497 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6498 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006499
Steve Naroff081c7422008-09-04 15:10:53 +00006500 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006501 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006502 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006503 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006504 }
John McCalle3027922010-08-25 11:45:40 +00006505 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006506 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006507 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006508 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006509 if (!isRelational
6510 && ((lType->isBlockPointerType() && rType->isPointerType())
6511 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006512 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006513 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006514 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006515 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006516 ->getPointeeType()->isVoidType())))
6517 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6518 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006519 }
John McCalle3027922010-08-25 11:45:40 +00006520 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006521 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006522 }
Steve Naroff081c7422008-09-04 15:10:53 +00006523
Steve Naroff7cae42b2009-07-10 23:34:53 +00006524 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006525 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006526 const PointerType *LPT = lType->getAs<PointerType>();
6527 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006528 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006529 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006530 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006531 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006532
Steve Naroff753567f2008-11-17 19:49:16 +00006533 if (!LPtrToVoid && !RPtrToVoid &&
6534 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006535 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006536 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006537 }
John McCalle3027922010-08-25 11:45:40 +00006538 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006539 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006540 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006541 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006542 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006543 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6544 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006545 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006546 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006547 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006548 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006549 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6550 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006551 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006552 bool isError = false;
6553 if ((LHSIsNull && lType->isIntegerType()) ||
6554 (RHSIsNull && rType->isIntegerType())) {
6555 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006556 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006557 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006558 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006559 else if (getLangOptions().CPlusPlus) {
6560 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6561 isError = true;
6562 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006563 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006564
Chris Lattnerd99bd522009-08-23 00:03:44 +00006565 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006566 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006567 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006568 if (isError)
6569 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006570 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006571
6572 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006573 ImpCastExprToType(lex, rType,
6574 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006575 else
John McCalle84af4e2010-11-13 01:35:44 +00006576 ImpCastExprToType(rex, lType,
6577 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006578 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006579 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006580
Steve Naroff4b191572008-09-04 16:56:14 +00006581 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006582 if (!isRelational && RHSIsNull
6583 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006584 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006585 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006586 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006587 if (!isRelational && LHSIsNull
6588 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006589 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006590 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006591 }
Chris Lattner326f7572008-11-18 01:30:42 +00006592 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006593}
6594
Nate Begeman191a6b12008-07-14 18:02:46 +00006595/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006596/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006597/// like a scalar comparison, a vector comparison produces a vector of integer
6598/// types.
6599QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006600 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006601 bool isRelational) {
6602 // Check to make sure we're operating on vectors of the same type and width,
6603 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006604 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006605 if (vType.isNull())
6606 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006607
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006608 // If AltiVec, the comparison results in a numeric type, i.e.
6609 // bool for C++, int for C
6610 if (getLangOptions().AltiVec)
6611 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6612
Nate Begeman191a6b12008-07-14 18:02:46 +00006613 QualType lType = lex->getType();
6614 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006615
Nate Begeman191a6b12008-07-14 18:02:46 +00006616 // For non-floating point types, check for self-comparisons of the form
6617 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6618 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006619 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006620 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6621 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6622 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006623 DiagRuntimeBehavior(Loc,
6624 PDiag(diag::warn_comparison_always)
6625 << 0 // self-
6626 << 2 // "a constant"
6627 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006628 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006629
Nate Begeman191a6b12008-07-14 18:02:46 +00006630 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006631 if (!isRelational && lType->hasFloatingRepresentation()) {
6632 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006633 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006634 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006635
Nate Begeman191a6b12008-07-14 18:02:46 +00006636 // Return the type for the comparison, which is the same as vector type for
6637 // integer vectors, or an integer type of identical size and number of
6638 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006639 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006640 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006641
John McCall9dd450b2009-09-21 23:43:11 +00006642 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006643 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006644 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006645 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006646 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006647 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6648
Mike Stump4e1f26a2009-02-19 03:04:26 +00006649 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006650 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006651 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6652}
6653
Steve Naroff218bc2b2007-05-04 21:54:46 +00006654inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006655 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006656 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6657 if (lex->getType()->hasIntegerRepresentation() &&
6658 rex->getType()->hasIntegerRepresentation())
6659 return CheckVectorOperands(Loc, lex, rex);
6660
6661 return InvalidOperands(Loc, lex, rex);
6662 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006663
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006664 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006665
Douglas Gregor0bf31402010-10-08 23:50:27 +00006666 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6667 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006668 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006669 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006670}
6671
Steve Naroff218bc2b2007-05-04 21:54:46 +00006672inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006673 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6674
6675 // Diagnose cases where the user write a logical and/or but probably meant a
6676 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6677 // is a constant.
6678 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006679 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006680 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006681 !Loc.isMacroID()) {
6682 // If the RHS can be constant folded, and if it constant folds to something
6683 // that isn't 0 or 1 (which indicate a potential logical operation that
6684 // happened to fold to true/false) then warn.
6685 Expr::EvalResult Result;
6686 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6687 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6688 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6689 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006690 << (Opc == BO_LAnd ? "&&" : "||")
6691 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006692 }
6693 }
Chris Lattner8406c512010-07-13 19:41:32 +00006694
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006695 if (!Context.getLangOptions().CPlusPlus) {
6696 UsualUnaryConversions(lex);
6697 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006698
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006699 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6700 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006701
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006702 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006703 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006704
John McCall4a2429a2010-06-04 00:29:51 +00006705 // The following is safe because we only use this method for
6706 // non-overloadable operands.
6707
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006708 // C++ [expr.log.and]p1
6709 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006710 // The operands are both contextually converted to type bool.
6711 if (PerformContextuallyConvertToBool(lex) ||
6712 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006713 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006714
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006715 // C++ [expr.log.and]p2
6716 // C++ [expr.log.or]p2
6717 // The result is a bool.
6718 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006719}
6720
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006721/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6722/// is a read-only property; return true if so. A readonly property expression
6723/// depends on various declarations and thus must be treated specially.
6724///
Mike Stump11289f42009-09-09 15:08:12 +00006725static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006726 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6727 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006728 if (PropExpr->isImplicitProperty()) return false;
6729
6730 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6731 QualType BaseType = PropExpr->isSuperReceiver() ?
6732 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006733 PropExpr->getBase()->getType();
6734
John McCallb7bd14f2010-12-02 01:19:52 +00006735 if (const ObjCObjectPointerType *OPT =
6736 BaseType->getAsObjCInterfacePointerType())
6737 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6738 if (S.isPropertyReadonly(PDecl, IFace))
6739 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006740 }
6741 return false;
6742}
6743
Chris Lattner30bd3272008-11-18 01:22:49 +00006744/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6745/// emit an error and return true. If so, return false.
6746static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006747 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006748 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006749 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006750 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6751 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006752 if (IsLV == Expr::MLV_Valid)
6753 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006754
Chris Lattner30bd3272008-11-18 01:22:49 +00006755 unsigned Diag = 0;
6756 bool NeedType = false;
6757 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006758 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006759 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006760 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6761 NeedType = true;
6762 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006763 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006764 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6765 NeedType = true;
6766 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006767 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006768 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6769 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006770 case Expr::MLV_Valid:
6771 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006772 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006773 case Expr::MLV_MemberFunction:
6774 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006775 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6776 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006777 case Expr::MLV_IncompleteType:
6778 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006779 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006780 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006781 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006782 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006783 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6784 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006785 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006786 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6787 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006788 case Expr::MLV_ReadonlyProperty:
6789 Diag = diag::error_readonly_property_assignment;
6790 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006791 case Expr::MLV_NoSetterProperty:
6792 Diag = diag::error_nosetter_property_assignment;
6793 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006794 case Expr::MLV_SubObjCPropertySetting:
6795 Diag = diag::error_no_subobject_property_setting;
6796 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006797 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006798
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006799 SourceRange Assign;
6800 if (Loc != OrigLoc)
6801 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006802 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006803 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006804 else
Mike Stump11289f42009-09-09 15:08:12 +00006805 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006806 return true;
6807}
6808
6809
6810
6811// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006812QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6813 SourceLocation Loc,
6814 QualType CompoundType) {
6815 // Verify that LHS is a modifiable lvalue, and emit error if not.
6816 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006817 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006818
6819 QualType LHSType = LHS->getType();
6820 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006821 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006822 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006823 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006824 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00006825 if (LHS->getObjectKind() == OK_ObjCProperty)
6826 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006827 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006828 // Special case of NSObject attributes on c-style pointer types.
6829 if (ConvTy == IncompatiblePointer &&
6830 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006831 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006832 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006833 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006834 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006835
John McCall7decc9e2010-11-18 06:31:45 +00006836 if (ConvTy == Compatible &&
6837 getLangOptions().ObjCNonFragileABI &&
6838 LHSType->isObjCObjectType())
6839 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6840 << LHSType;
6841
Chris Lattnerea714382008-08-21 18:04:13 +00006842 // If the RHS is a unary plus or minus, check to see if they = and + are
6843 // right next to each other. If so, the user may have typo'd "x =+ 4"
6844 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006845 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006846 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6847 RHSCheck = ICE->getSubExpr();
6848 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006849 if ((UO->getOpcode() == UO_Plus ||
6850 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006851 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006852 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006853 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6854 // And there is a space or other character before the subexpr of the
6855 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006856 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6857 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006858 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006859 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006860 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006861 }
Chris Lattnerea714382008-08-21 18:04:13 +00006862 }
6863 } else {
6864 // Compound assignment "x += y"
John McCall29600e12010-11-16 02:32:08 +00006865 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006866 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006867
Chris Lattner326f7572008-11-18 01:30:42 +00006868 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006869 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006870 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006871
Chris Lattner39561062010-07-07 06:14:23 +00006872
6873 // Check to see if the destination operand is a dereferenced null pointer. If
6874 // so, and if not volatile-qualified, this is undefined behavior that the
6875 // optimizer will delete, so warn about it. People sometimes try to use this
6876 // to get a deterministic trap and are surprised by clang's behavior. This
6877 // only handles the pattern "*null = whatever", which is a very syntactic
6878 // check.
6879 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006880 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006881 UO->getSubExpr()->IgnoreParenCasts()->
6882 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6883 !UO->getType().isVolatileQualified()) {
6884 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6885 << UO->getSubExpr()->getSourceRange();
6886 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6887 }
6888
Steve Naroff98cf3e92007-06-06 18:38:38 +00006889 // C99 6.5.16p3: The type of an assignment expression is the type of the
6890 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006891 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006892 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6893 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006894 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006895 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006896 return (getLangOptions().CPlusPlus
6897 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006898}
6899
Chris Lattner326f7572008-11-18 01:30:42 +00006900// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00006901static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006902 SourceLocation Loc) {
6903 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006904
John McCall4bc41ae2010-11-18 19:01:18 +00006905 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006906 if (LHSResult.isInvalid())
6907 return QualType();
6908
John McCall4bc41ae2010-11-18 19:01:18 +00006909 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006910 if (RHSResult.isInvalid())
6911 return QualType();
6912 RHS = RHSResult.take();
6913
John McCall73d36182010-10-12 07:14:40 +00006914 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6915 // operands, but not unary promotions.
6916 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006917
John McCall34376a62010-12-04 03:47:34 +00006918 // So we treat the LHS as a ignored value, and in C++ we allow the
6919 // containing site to determine what should be done with the RHS.
6920 S.IgnoredValueConversions(LHS);
6921
6922 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00006923 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00006924 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00006925 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006926 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006927
Chris Lattner326f7572008-11-18 01:30:42 +00006928 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006929}
6930
Steve Naroff7a5af782007-07-13 16:58:59 +00006931/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6932/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006933static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6934 ExprValueKind &VK,
6935 SourceLocation OpLoc,
6936 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006937 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006938 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006939
Chris Lattner6b0cf142008-11-21 07:05:48 +00006940 QualType ResType = Op->getType();
6941 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006942
John McCall4bc41ae2010-11-18 19:01:18 +00006943 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006944 // Decrement of bool is not allowed.
6945 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006946 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006947 return QualType();
6948 }
6949 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006950 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006951 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006952 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006953 } else if (ResType->isAnyPointerType()) {
6954 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006955
Chris Lattner6b0cf142008-11-21 07:05:48 +00006956 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006957 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006958 if (S.getLangOptions().CPlusPlus) {
6959 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006960 << Op->getSourceRange();
6961 return QualType();
6962 }
6963
6964 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00006965 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006966 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006967 if (S.getLangOptions().CPlusPlus) {
6968 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006969 << Op->getType() << Op->getSourceRange();
6970 return QualType();
6971 }
6972
John McCall4bc41ae2010-11-18 19:01:18 +00006973 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006974 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00006975 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
6976 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006977 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006978 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006979 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006980 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006981 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6982 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006983 << PointeeTy << Op->getSourceRange();
6984 return QualType();
6985 }
Eli Friedman090addd2010-01-03 00:20:48 +00006986 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006987 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006988 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006989 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006990 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00006991 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00006992 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006993 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6994 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00006995 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006996 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006997 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006998 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006999 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007000 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007001 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007002 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007003 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007004 // In C++, a prefix increment is the same type as the operand. Otherwise
7005 // (in C or with postfix), the increment is the unqualified type of the
7006 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007007 if (isPrefix && S.getLangOptions().CPlusPlus) {
7008 VK = VK_LValue;
7009 return ResType;
7010 } else {
7011 VK = VK_RValue;
7012 return ResType.getUnqualifiedType();
7013 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007014}
7015
John McCall34376a62010-12-04 03:47:34 +00007016void Sema::ConvertPropertyForRValue(Expr *&E) {
7017 assert(E->getValueKind() == VK_LValue &&
7018 E->getObjectKind() == OK_ObjCProperty);
7019 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7020
7021 ExprValueKind VK = VK_RValue;
7022 if (PRE->isImplicitProperty()) {
7023 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7024 VK = Expr::getValueKindForType(Result);
7025 }
7026
7027 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7028 E, 0, VK);
7029}
7030
7031void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7032 assert(LHS->getValueKind() == VK_LValue &&
7033 LHS->getObjectKind() == OK_ObjCProperty);
7034 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7035
7036 if (PRE->isImplicitProperty()) {
7037 // If using property-dot syntax notation for assignment, and there is a
7038 // setter, RHS expression is being passed to the setter argument. So,
7039 // type conversion (and comparison) is RHS to setter's argument type.
7040 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7041 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7042 LHSTy = (*P)->getType();
7043
7044 // Otherwise, if the getter returns an l-value, just call that.
7045 } else {
7046 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7047 ExprValueKind VK = Expr::getValueKindForType(Result);
7048 if (VK == VK_LValue) {
7049 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7050 CK_GetObjCProperty, LHS, 0, VK);
7051 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007052 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007053 }
John McCall34376a62010-12-04 03:47:34 +00007054 }
7055
7056 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007057 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007058 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007059 Expr *Arg = RHS;
7060 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7061 Owned(Arg));
7062 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007063 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007064 }
7065}
7066
7067
Anders Carlsson806700f2008-02-01 07:15:58 +00007068/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007069/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007070/// where the declaration is needed for type checking. We only need to
7071/// handle cases when the expression references a function designator
7072/// or is an lvalue. Here are some examples:
7073/// - &(x) => x
7074/// - &*****f => f for f a function designator.
7075/// - &s.xx => s
7076/// - &s.zz[1].yy -> s, if zz is an array
7077/// - *(x + 1) -> x, if x is an array
7078/// - &"123"[2] -> 0
7079/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007080static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007081 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007082 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007083 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007084 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007085 // If this is an arrow operator, the address is an offset from
7086 // the base's value, so the object the base refers to is
7087 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007088 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007089 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007090 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007091 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007092 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007093 // FIXME: This code shouldn't be necessary! We should catch the implicit
7094 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007095 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7096 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7097 if (ICE->getSubExpr()->getType()->isArrayType())
7098 return getPrimaryDecl(ICE->getSubExpr());
7099 }
7100 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007101 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007102 case Stmt::UnaryOperatorClass: {
7103 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007104
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007105 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007106 case UO_Real:
7107 case UO_Imag:
7108 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007109 return getPrimaryDecl(UO->getSubExpr());
7110 default:
7111 return 0;
7112 }
7113 }
Steve Naroff47500512007-04-19 23:00:49 +00007114 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007115 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007116 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007117 // If the result of an implicit cast is an l-value, we care about
7118 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007119 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007120 default:
7121 return 0;
7122 }
7123}
7124
7125/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007126/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007127/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007128/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007129/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007130/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007131/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007132static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7133 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007134 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007135 return S.Context.DependentTy;
7136 if (OrigOp->getType() == S.Context.OverloadTy)
7137 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007138
John McCall4bc41ae2010-11-18 19:01:18 +00007139 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007140 if (PR.isInvalid()) return QualType();
7141 OrigOp = PR.take();
7142
John McCall8d08b9b2010-08-27 09:08:28 +00007143 // Make sure to ignore parentheses in subsequent checks
7144 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007145
John McCall4bc41ae2010-11-18 19:01:18 +00007146 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007147 // Implement C99-only parts of addressof rules.
7148 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007149 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007150 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7151 // (assuming the deref expression is valid).
7152 return uOp->getSubExpr()->getType();
7153 }
7154 // Technically, there should be a check for array subscript
7155 // expressions here, but the result of one is always an lvalue anyway.
7156 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007157 NamedDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007158 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007159
Chris Lattner9156f1b2010-07-05 19:17:26 +00007160 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007161 bool sfinae = S.isSFINAEContext();
7162 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7163 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007164 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007165 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007166 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007167 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007168 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007169 } else if (lval == Expr::LV_MemberFunction) {
7170 // If it's an instance method, make a member pointer.
7171 // The expression must have exactly the form &A::foo.
7172
7173 // If the underlying expression isn't a decl ref, give up.
7174 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007175 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007176 << OrigOp->getSourceRange();
7177 return QualType();
7178 }
7179 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7180 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7181
7182 // The id-expression was parenthesized.
7183 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007184 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007185 << OrigOp->getSourceRange();
7186
7187 // The method was named without a qualifier.
7188 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007189 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007190 << op->getSourceRange();
7191 }
7192
John McCall4bc41ae2010-11-18 19:01:18 +00007193 return S.Context.getMemberPointerType(op->getType(),
7194 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007195 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007196 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007197 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007198 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007199 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007200 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007201 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007202 return QualType();
7203 }
John McCall086a4642010-11-24 05:12:34 +00007204 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007205 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007206 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007207 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007208 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007209 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007210 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007211 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007212 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007213 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007214 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007215 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007216 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007217 << "property expression" << op->getSourceRange();
7218 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007219 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007220 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007221 // with the register storage-class specifier.
7222 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007223 // in C++ it is not error to take address of a register
7224 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007225 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007226 !S.getLangOptions().CPlusPlus) {
7227 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007228 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007229 return QualType();
7230 }
John McCalld14a8642009-11-21 08:51:07 +00007231 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007232 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007233 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007234 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007235 // Could be a pointer to member, though, if there is an explicit
7236 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007237 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007238 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007239 if (Ctx && Ctx->isRecord()) {
7240 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007241 S.Diag(OpLoc,
7242 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007243 << FD->getDeclName() << FD->getType();
7244 return QualType();
7245 }
Mike Stump11289f42009-09-09 15:08:12 +00007246
John McCall4bc41ae2010-11-18 19:01:18 +00007247 return S.Context.getMemberPointerType(op->getType(),
7248 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007249 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007250 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007251 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007252 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007253 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007254
Eli Friedmance7f9002009-05-16 23:27:50 +00007255 if (lval == Expr::LV_IncompleteVoidType) {
7256 // Taking the address of a void variable is technically illegal, but we
7257 // allow it in cases which are otherwise valid.
7258 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007259 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007260 }
7261
Steve Naroff47500512007-04-19 23:00:49 +00007262 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007263 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007264 return S.Context.getObjCObjectPointerType(op->getType());
7265 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007266}
7267
Chris Lattner9156f1b2010-07-05 19:17:26 +00007268/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007269static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7270 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007271 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007272 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007273
John McCall4bc41ae2010-11-18 19:01:18 +00007274 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007275 QualType OpTy = Op->getType();
7276 QualType Result;
7277
7278 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7279 // is an incomplete type or void. It would be possible to warn about
7280 // dereferencing a void pointer, but it's completely well-defined, and such a
7281 // warning is unlikely to catch any mistakes.
7282 if (const PointerType *PT = OpTy->getAs<PointerType>())
7283 Result = PT->getPointeeType();
7284 else if (const ObjCObjectPointerType *OPT =
7285 OpTy->getAs<ObjCObjectPointerType>())
7286 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007287 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007288 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007289 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007290 if (PR.take() != Op)
7291 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007292 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007293
Chris Lattner9156f1b2010-07-05 19:17:26 +00007294 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007295 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007296 << OpTy << Op->getSourceRange();
7297 return QualType();
7298 }
John McCall4bc41ae2010-11-18 19:01:18 +00007299
7300 // Dereferences are usually l-values...
7301 VK = VK_LValue;
7302
7303 // ...except that certain expressions are never l-values in C.
7304 if (!S.getLangOptions().CPlusPlus &&
7305 IsCForbiddenLValueType(S.Context, Result))
7306 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007307
7308 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007309}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007310
John McCalle3027922010-08-25 11:45:40 +00007311static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007312 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007313 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007314 switch (Kind) {
7315 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007316 case tok::periodstar: Opc = BO_PtrMemD; break;
7317 case tok::arrowstar: Opc = BO_PtrMemI; break;
7318 case tok::star: Opc = BO_Mul; break;
7319 case tok::slash: Opc = BO_Div; break;
7320 case tok::percent: Opc = BO_Rem; break;
7321 case tok::plus: Opc = BO_Add; break;
7322 case tok::minus: Opc = BO_Sub; break;
7323 case tok::lessless: Opc = BO_Shl; break;
7324 case tok::greatergreater: Opc = BO_Shr; break;
7325 case tok::lessequal: Opc = BO_LE; break;
7326 case tok::less: Opc = BO_LT; break;
7327 case tok::greaterequal: Opc = BO_GE; break;
7328 case tok::greater: Opc = BO_GT; break;
7329 case tok::exclaimequal: Opc = BO_NE; break;
7330 case tok::equalequal: Opc = BO_EQ; break;
7331 case tok::amp: Opc = BO_And; break;
7332 case tok::caret: Opc = BO_Xor; break;
7333 case tok::pipe: Opc = BO_Or; break;
7334 case tok::ampamp: Opc = BO_LAnd; break;
7335 case tok::pipepipe: Opc = BO_LOr; break;
7336 case tok::equal: Opc = BO_Assign; break;
7337 case tok::starequal: Opc = BO_MulAssign; break;
7338 case tok::slashequal: Opc = BO_DivAssign; break;
7339 case tok::percentequal: Opc = BO_RemAssign; break;
7340 case tok::plusequal: Opc = BO_AddAssign; break;
7341 case tok::minusequal: Opc = BO_SubAssign; break;
7342 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7343 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7344 case tok::ampequal: Opc = BO_AndAssign; break;
7345 case tok::caretequal: Opc = BO_XorAssign; break;
7346 case tok::pipeequal: Opc = BO_OrAssign; break;
7347 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007348 }
7349 return Opc;
7350}
7351
John McCalle3027922010-08-25 11:45:40 +00007352static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007353 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007354 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007355 switch (Kind) {
7356 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007357 case tok::plusplus: Opc = UO_PreInc; break;
7358 case tok::minusminus: Opc = UO_PreDec; break;
7359 case tok::amp: Opc = UO_AddrOf; break;
7360 case tok::star: Opc = UO_Deref; break;
7361 case tok::plus: Opc = UO_Plus; break;
7362 case tok::minus: Opc = UO_Minus; break;
7363 case tok::tilde: Opc = UO_Not; break;
7364 case tok::exclaim: Opc = UO_LNot; break;
7365 case tok::kw___real: Opc = UO_Real; break;
7366 case tok::kw___imag: Opc = UO_Imag; break;
7367 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007368 }
7369 return Opc;
7370}
7371
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007372/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7373/// operator @p Opc at location @c TokLoc. This routine only supports
7374/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007375ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007376 unsigned Op,
7377 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007378 QualType ResultTy; // Result type of the binary operator.
John McCalle3027922010-08-25 11:45:40 +00007379 BinaryOperatorKind Opc = (BinaryOperatorKind) Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007380 // The following two variables are used for compound assignment operators
7381 QualType CompLHSTy; // Type of LHS after promotions for computation
7382 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007383 ExprValueKind VK = VK_RValue;
7384 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007385
7386 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007387 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007388 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007389 if (getLangOptions().CPlusPlus &&
7390 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007391 VK = lhs->getValueKind();
7392 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007393 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007394 break;
John McCalle3027922010-08-25 11:45:40 +00007395 case BO_PtrMemD:
7396 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007397 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007398 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007399 break;
John McCalle3027922010-08-25 11:45:40 +00007400 case BO_Mul:
7401 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007402 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007403 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007404 break;
John McCalle3027922010-08-25 11:45:40 +00007405 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007406 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7407 break;
John McCalle3027922010-08-25 11:45:40 +00007408 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007409 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7410 break;
John McCalle3027922010-08-25 11:45:40 +00007411 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007412 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7413 break;
John McCalle3027922010-08-25 11:45:40 +00007414 case BO_Shl:
7415 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007416 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7417 break;
John McCalle3027922010-08-25 11:45:40 +00007418 case BO_LE:
7419 case BO_LT:
7420 case BO_GE:
7421 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007422 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007423 break;
John McCalle3027922010-08-25 11:45:40 +00007424 case BO_EQ:
7425 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007426 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007427 break;
John McCalle3027922010-08-25 11:45:40 +00007428 case BO_And:
7429 case BO_Xor:
7430 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007431 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7432 break;
John McCalle3027922010-08-25 11:45:40 +00007433 case BO_LAnd:
7434 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007435 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007436 break;
John McCalle3027922010-08-25 11:45:40 +00007437 case BO_MulAssign:
7438 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007439 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007440 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007441 CompLHSTy = CompResultTy;
7442 if (!CompResultTy.isNull())
7443 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007444 break;
John McCalle3027922010-08-25 11:45:40 +00007445 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007446 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7447 CompLHSTy = CompResultTy;
7448 if (!CompResultTy.isNull())
7449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007450 break;
John McCalle3027922010-08-25 11:45:40 +00007451 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007452 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7453 if (!CompResultTy.isNull())
7454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007455 break;
John McCalle3027922010-08-25 11:45:40 +00007456 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007457 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7458 if (!CompResultTy.isNull())
7459 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007460 break;
John McCalle3027922010-08-25 11:45:40 +00007461 case BO_ShlAssign:
7462 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007463 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7464 CompLHSTy = CompResultTy;
7465 if (!CompResultTy.isNull())
7466 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007467 break;
John McCalle3027922010-08-25 11:45:40 +00007468 case BO_AndAssign:
7469 case BO_XorAssign:
7470 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007471 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7472 CompLHSTy = CompResultTy;
7473 if (!CompResultTy.isNull())
7474 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007475 break;
John McCalle3027922010-08-25 11:45:40 +00007476 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007477 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007478 if (getLangOptions().CPlusPlus) {
7479 VK = rhs->getValueKind();
7480 OK = rhs->getObjectKind();
7481 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007482 break;
7483 }
7484 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007485 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007486 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007487 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7488 VK, OK, OpLoc));
7489
John McCall34376a62010-12-04 03:47:34 +00007490 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007491 VK = VK_LValue;
7492 OK = lhs->getObjectKind();
7493 }
7494 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7495 VK, OK, CompLHSTy,
7496 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007497}
7498
Sebastian Redl44615072009-10-27 12:10:02 +00007499/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7500/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007501static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7502 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007503 const PartialDiagnostic &FirstNote,
7504 SourceRange FirstParenRange,
7505 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007506 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007507 Self.Diag(Loc, PD);
7508
7509 if (!FirstNote.getDiagID())
7510 return;
7511
7512 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7513 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7514 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007515 return;
7516 }
7517
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007518 Self.Diag(Loc, FirstNote)
7519 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007520 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007521
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007522 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007523 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007524
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007525 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7526 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7527 // We can't display the parentheses, so just dig the
7528 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007529 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007530 return;
7531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007532
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007533 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007534 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7535 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007536}
7537
Sebastian Redl44615072009-10-27 12:10:02 +00007538/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7539/// operators are mixed in a way that suggests that the programmer forgot that
7540/// comparison operators have higher precedence. The most typical example of
7541/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007542static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007543 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007544 typedef BinaryOperator BinOp;
7545 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7546 rhsopc = static_cast<BinOp::Opcode>(-1);
7547 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007548 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007549 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007550 rhsopc = BO->getOpcode();
7551
7552 // Subs are not binary operators.
7553 if (lhsopc == -1 && rhsopc == -1)
7554 return;
7555
7556 // Bitwise operations are sometimes used as eager logical ops.
7557 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007558 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7559 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007560 return;
7561
Sebastian Redl44615072009-10-27 12:10:02 +00007562 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007563 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007564 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007565 << SourceRange(lhs->getLocStart(), OpLoc)
7566 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007567 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007568 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007569 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7570 Self.PDiag(diag::note_precedence_bitwise_silence)
7571 << BinOp::getOpcodeStr(lhsopc),
7572 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007573 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007574 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007575 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007576 << SourceRange(OpLoc, rhs->getLocEnd())
7577 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007578 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007579 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007580 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7581 Self.PDiag(diag::note_precedence_bitwise_silence)
7582 << BinOp::getOpcodeStr(rhsopc),
7583 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007584}
7585
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007586/// \brief It accepts a '&&' expr that is inside a '||' one.
7587/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7588/// in parentheses.
7589static void
7590EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7591 Expr *E) {
7592 assert(isa<BinaryOperator>(E) &&
7593 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7594 SuggestParentheses(Self, OpLoc,
7595 Self.PDiag(diag::warn_logical_and_in_logical_or)
7596 << E->getSourceRange(),
7597 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7598 E->getSourceRange(),
7599 Self.PDiag(0), SourceRange());
7600}
7601
7602/// \brief Returns true if the given expression can be evaluated as a constant
7603/// 'true'.
7604static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7605 bool Res;
7606 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7607}
7608
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007609/// \brief Returns true if the given expression can be evaluated as a constant
7610/// 'false'.
7611static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7612 bool Res;
7613 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7614}
7615
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007616/// \brief Look for '&&' in the left hand of a '||' expr.
7617static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007618 Expr *OrLHS, Expr *OrRHS) {
7619 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007620 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007621 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7622 if (EvaluatesAsFalse(S, OrRHS))
7623 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007624 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7625 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7626 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7627 } else if (Bop->getOpcode() == BO_LOr) {
7628 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7629 // If it's "a || b && 1 || c" we didn't warn earlier for
7630 // "a || b && 1", but warn now.
7631 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7632 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7633 }
7634 }
7635 }
7636}
7637
7638/// \brief Look for '&&' in the right hand of a '||' expr.
7639static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007640 Expr *OrLHS, Expr *OrRHS) {
7641 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007642 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007643 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7644 if (EvaluatesAsFalse(S, OrLHS))
7645 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007646 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7647 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7648 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007649 }
7650 }
7651}
7652
Sebastian Redl43028242009-10-26 15:24:15 +00007653/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007654/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007655static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007656 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007657 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007658 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007659 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7660
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007661 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7662 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007663 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007664 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7665 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007666 }
Sebastian Redl43028242009-10-26 15:24:15 +00007667}
7668
Steve Naroff218bc2b2007-05-04 21:54:46 +00007669// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007670ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007671 tok::TokenKind Kind,
7672 Expr *lhs, Expr *rhs) {
7673 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007674 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7675 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007676
Sebastian Redl43028242009-10-26 15:24:15 +00007677 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7678 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7679
Douglas Gregor5287f092009-11-05 00:51:44 +00007680 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7681}
7682
John McCalldadc5752010-08-24 06:29:42 +00007683ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007684 BinaryOperatorKind Opc,
7685 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007686 if (getLangOptions().CPlusPlus) {
7687 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007688
John McCall622114c2010-12-06 05:26:58 +00007689 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7690 UseBuiltinOperator = false;
7691 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7692 UseBuiltinOperator = true;
7693 } else {
7694 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7695 !rhs->getType()->isOverloadableType();
7696 }
7697
7698 if (!UseBuiltinOperator) {
7699 // Find all of the overloaded operators visible from this
7700 // point. We perform both an operator-name lookup from the local
7701 // scope and an argument-dependent lookup based on the types of
7702 // the arguments.
7703 UnresolvedSet<16> Functions;
7704 OverloadedOperatorKind OverOp
7705 = BinaryOperator::getOverloadedOperator(Opc);
7706 if (S && OverOp != OO_None)
7707 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7708 Functions);
7709
7710 // Build the (potentially-overloaded, potentially-dependent)
7711 // binary operation.
7712 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7713 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007714 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007715
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007716 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007717 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007718}
7719
John McCalldadc5752010-08-24 06:29:42 +00007720ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
John McCall36226622010-10-12 02:09:17 +00007721 unsigned OpcIn,
7722 Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00007723 UnaryOperatorKind Opc = static_cast<UnaryOperatorKind>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00007724
John McCall7decc9e2010-11-18 06:31:45 +00007725 ExprValueKind VK = VK_RValue;
7726 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007727 QualType resultType;
7728 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007729 case UO_PreInc:
7730 case UO_PreDec:
7731 case UO_PostInc:
7732 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007733 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007734 Opc == UO_PreInc ||
7735 Opc == UO_PostInc,
7736 Opc == UO_PreInc ||
7737 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007738 break;
John McCalle3027922010-08-25 11:45:40 +00007739 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007740 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007741 break;
John McCalle3027922010-08-25 11:45:40 +00007742 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007743 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007744 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007745 break;
John McCalle3027922010-08-25 11:45:40 +00007746 case UO_Plus:
7747 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007748 UsualUnaryConversions(Input);
7749 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007750 if (resultType->isDependentType())
7751 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007752 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7753 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007754 break;
7755 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7756 resultType->isEnumeralType())
7757 break;
7758 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007759 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007760 resultType->isPointerType())
7761 break;
John McCall36226622010-10-12 02:09:17 +00007762 else if (resultType->isPlaceholderType()) {
7763 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7764 if (PR.isInvalid()) return ExprError();
7765 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7766 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007767
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007768 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7769 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007770 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007771 UsualUnaryConversions(Input);
7772 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007773 if (resultType->isDependentType())
7774 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007775 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7776 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7777 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007778 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007779 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007780 else if (resultType->hasIntegerRepresentation())
7781 break;
7782 else if (resultType->isPlaceholderType()) {
7783 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7784 if (PR.isInvalid()) return ExprError();
7785 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7786 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007787 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7788 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007789 }
Steve Naroff35d85152007-05-07 00:24:15 +00007790 break;
John McCalle3027922010-08-25 11:45:40 +00007791 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007792 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007793 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007794 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007795 if (resultType->isDependentType())
7796 break;
John McCall36226622010-10-12 02:09:17 +00007797 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7798 // ok, fallthrough
7799 } else if (resultType->isPlaceholderType()) {
7800 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7801 if (PR.isInvalid()) return ExprError();
7802 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take());
7803 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7805 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007806 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007807
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007808 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007809 // In C++, it's bool. C++ 5.3.1p8
7810 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007811 break;
John McCalle3027922010-08-25 11:45:40 +00007812 case UO_Real:
7813 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007814 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007815 // _Real and _Imag map ordinary l-values into ordinary l-values.
7816 if (Input->getValueKind() != VK_RValue &&
7817 Input->getObjectKind() == OK_Ordinary)
7818 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007819 break;
John McCalle3027922010-08-25 11:45:40 +00007820 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007821 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007822 VK = Input->getValueKind();
7823 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007824 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007825 }
7826 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007827 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007828
John McCall7decc9e2010-11-18 06:31:45 +00007829 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7830 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007831}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007832
John McCalldadc5752010-08-24 06:29:42 +00007833ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007834 UnaryOperatorKind Opc,
7835 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007836 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007837 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007838 // Find all of the overloaded operators visible from this
7839 // point. We perform both an operator-name lookup from the local
7840 // scope and an argument-dependent lookup based on the types of
7841 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007842 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007843 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007844 if (S && OverOp != OO_None)
7845 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7846 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007847
John McCallb268a282010-08-23 23:25:46 +00007848 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007849 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007850
John McCallb268a282010-08-23 23:25:46 +00007851 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007852}
7853
Douglas Gregor5287f092009-11-05 00:51:44 +00007854// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007855ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00007856 tok::TokenKind Op, Expr *Input) {
7857 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007858}
7859
Steve Naroff66356bd2007-09-16 14:56:35 +00007860/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00007861ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007862 SourceLocation LabLoc,
7863 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00007864 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00007865 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00007866
Daniel Dunbar88402ce2008-08-04 16:51:22 +00007867 // If we haven't seen this label yet, create a forward reference. It
7868 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00007869 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00007870 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007871
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00007872 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007873 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007874 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
7875 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007876}
7877
John McCalldadc5752010-08-24 06:29:42 +00007878ExprResult
John McCallb268a282010-08-23 23:25:46 +00007879Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007880 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007881 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7882 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7883
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007884 bool isFileScope
7885 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007886 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007887 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007888
Chris Lattner366727f2007-07-24 16:58:17 +00007889 // FIXME: there are a variety of strange constraints to enforce here, for
7890 // example, it is not possible to goto into a stmt expression apparently.
7891 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007892
Chris Lattner366727f2007-07-24 16:58:17 +00007893 // If there are sub stmts in the compound stmt, take the type of the last one
7894 // as the type of the stmtexpr.
7895 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007896 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00007897 if (!Compound->body_empty()) {
7898 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007899 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00007900 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007901 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7902 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00007903 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007904 }
7905 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00007906 // Do function/array conversion on the last expression, but not
7907 // lvalue-to-rvalue. However, initialize an unqualified type.
7908 DefaultFunctionArrayConversion(LastExpr);
7909 Ty = LastExpr->getType().getUnqualifiedType();
7910
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007911 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
7912 ExprResult Res = PerformCopyInitialization(
7913 InitializedEntity::InitializeResult(LPLoc,
7914 Ty,
7915 false),
7916 SourceLocation(),
7917 Owned(LastExpr));
7918 if (Res.isInvalid())
7919 return ExprError();
7920 if ((LastExpr = Res.takeAs<Expr>())) {
7921 if (!LastLabelStmt)
7922 Compound->setLastStmt(LastExpr);
7923 else
7924 LastLabelStmt->setSubStmt(LastExpr);
7925 StmtExprMayBindToTemp = true;
7926 }
7927 }
7928 }
Chris Lattner944d3062008-07-26 19:51:01 +00007929 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007930
Eli Friedmanba961a92009-03-23 00:24:07 +00007931 // FIXME: Check that expression type is complete/non-abstract; statement
7932 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007933 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
7934 if (StmtExprMayBindToTemp)
7935 return MaybeBindToTemporary(ResStmtExpr);
7936 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00007937}
Steve Naroff78864672007-08-01 22:05:33 +00007938
John McCalldadc5752010-08-24 06:29:42 +00007939ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00007940 TypeSourceInfo *TInfo,
7941 OffsetOfComponent *CompPtr,
7942 unsigned NumComponents,
7943 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007944 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007945 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007946 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00007947
Chris Lattnerf17bd422007-08-30 17:45:32 +00007948 // We must have at least one component that refers to the type, and the first
7949 // one is known to be a field designator. Verify that the ArgTy represents
7950 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007951 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00007952 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
7953 << ArgTy << TypeRange);
7954
7955 // Type must be complete per C99 7.17p3 because a declaring a variable
7956 // with an incomplete type would be ill-formed.
7957 if (!Dependent
7958 && RequireCompleteType(BuiltinLoc, ArgTy,
7959 PDiag(diag::err_offsetof_incomplete_type)
7960 << TypeRange))
7961 return ExprError();
7962
Chris Lattner78502cf2007-08-31 21:49:13 +00007963 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
7964 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00007965 // FIXME: This diagnostic isn't actually visible because the location is in
7966 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00007967 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00007968 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
7969 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00007970
7971 bool DidWarnAboutNonPOD = false;
7972 QualType CurrentType = ArgTy;
7973 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
7974 llvm::SmallVector<OffsetOfNode, 4> Comps;
7975 llvm::SmallVector<Expr*, 4> Exprs;
7976 for (unsigned i = 0; i != NumComponents; ++i) {
7977 const OffsetOfComponent &OC = CompPtr[i];
7978 if (OC.isBrackets) {
7979 // Offset of an array sub-field. TODO: Should we allow vector elements?
7980 if (!CurrentType->isDependentType()) {
7981 const ArrayType *AT = Context.getAsArrayType(CurrentType);
7982 if(!AT)
7983 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
7984 << CurrentType);
7985 CurrentType = AT->getElementType();
7986 } else
7987 CurrentType = Context.DependentTy;
7988
7989 // The expression must be an integral expression.
7990 // FIXME: An integral constant expression?
7991 Expr *Idx = static_cast<Expr*>(OC.U.E);
7992 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
7993 !Idx->getType()->isIntegerType())
7994 return ExprError(Diag(Idx->getLocStart(),
7995 diag::err_typecheck_subscript_not_integer)
7996 << Idx->getSourceRange());
7997
7998 // Record this array index.
7999 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8000 Exprs.push_back(Idx);
8001 continue;
8002 }
8003
8004 // Offset of a field.
8005 if (CurrentType->isDependentType()) {
8006 // We have the offset of a field, but we can't look into the dependent
8007 // type. Just record the identifier of the field.
8008 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8009 CurrentType = Context.DependentTy;
8010 continue;
8011 }
8012
8013 // We need to have a complete type to look into.
8014 if (RequireCompleteType(OC.LocStart, CurrentType,
8015 diag::err_offsetof_incomplete_type))
8016 return ExprError();
8017
8018 // Look for the designated field.
8019 const RecordType *RC = CurrentType->getAs<RecordType>();
8020 if (!RC)
8021 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8022 << CurrentType);
8023 RecordDecl *RD = RC->getDecl();
8024
8025 // C++ [lib.support.types]p5:
8026 // The macro offsetof accepts a restricted set of type arguments in this
8027 // International Standard. type shall be a POD structure or a POD union
8028 // (clause 9).
8029 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8030 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8031 DiagRuntimeBehavior(BuiltinLoc,
8032 PDiag(diag::warn_offsetof_non_pod_type)
8033 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8034 << CurrentType))
8035 DidWarnAboutNonPOD = true;
8036 }
8037
8038 // Look for the field.
8039 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8040 LookupQualifiedName(R, RD);
8041 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008042 IndirectFieldDecl *IndirectMemberDecl = 0;
8043 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008044 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008045 MemberDecl = IndirectMemberDecl->getAnonField();
8046 }
8047
Douglas Gregor882211c2010-04-28 22:16:22 +00008048 if (!MemberDecl)
8049 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8050 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8051 OC.LocEnd));
8052
Douglas Gregor10982ea2010-04-28 22:36:06 +00008053 // C99 7.17p3:
8054 // (If the specified member is a bit-field, the behavior is undefined.)
8055 //
8056 // We diagnose this as an error.
8057 if (MemberDecl->getBitWidth()) {
8058 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8059 << MemberDecl->getDeclName()
8060 << SourceRange(BuiltinLoc, RParenLoc);
8061 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8062 return ExprError();
8063 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008064
8065 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008066 if (IndirectMemberDecl)
8067 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008068
Douglas Gregord1702062010-04-29 00:18:15 +00008069 // If the member was found in a base class, introduce OffsetOfNodes for
8070 // the base class indirections.
8071 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8072 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008073 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008074 CXXBasePath &Path = Paths.front();
8075 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8076 B != BEnd; ++B)
8077 Comps.push_back(OffsetOfNode(B->Base));
8078 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008079
Francois Pichet783dd6e2010-11-21 06:08:52 +00008080 if (IndirectMemberDecl) {
8081 for (IndirectFieldDecl::chain_iterator FI =
8082 IndirectMemberDecl->chain_begin(),
8083 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8084 assert(isa<FieldDecl>(*FI));
8085 Comps.push_back(OffsetOfNode(OC.LocStart,
8086 cast<FieldDecl>(*FI), OC.LocEnd));
8087 }
8088 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008089 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008090
Douglas Gregor882211c2010-04-28 22:16:22 +00008091 CurrentType = MemberDecl->getType().getNonReferenceType();
8092 }
8093
8094 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8095 TInfo, Comps.data(), Comps.size(),
8096 Exprs.data(), Exprs.size(), RParenLoc));
8097}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008098
John McCalldadc5752010-08-24 06:29:42 +00008099ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008100 SourceLocation BuiltinLoc,
8101 SourceLocation TypeLoc,
8102 ParsedType argty,
8103 OffsetOfComponent *CompPtr,
8104 unsigned NumComponents,
8105 SourceLocation RPLoc) {
8106
Douglas Gregor882211c2010-04-28 22:16:22 +00008107 TypeSourceInfo *ArgTInfo;
8108 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8109 if (ArgTy.isNull())
8110 return ExprError();
8111
Eli Friedman06dcfd92010-08-05 10:15:45 +00008112 if (!ArgTInfo)
8113 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8114
8115 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8116 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008117}
8118
8119
John McCalldadc5752010-08-24 06:29:42 +00008120ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008121 ParsedType arg1, ParsedType arg2,
8122 SourceLocation RPLoc) {
Abramo Bagnara092990a2010-08-10 08:50:03 +00008123 TypeSourceInfo *argTInfo1;
8124 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
8125 TypeSourceInfo *argTInfo2;
8126 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008127
Steve Naroff78864672007-08-01 22:05:33 +00008128 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00008129
Abramo Bagnara092990a2010-08-10 08:50:03 +00008130 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
8131}
8132
John McCalldadc5752010-08-24 06:29:42 +00008133ExprResult
Abramo Bagnara092990a2010-08-10 08:50:03 +00008134Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
8135 TypeSourceInfo *argTInfo1,
8136 TypeSourceInfo *argTInfo2,
8137 SourceLocation RPLoc) {
Douglas Gregorf907cbf2009-05-19 22:28:02 +00008138 if (getLangOptions().CPlusPlus) {
8139 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
8140 << SourceRange(BuiltinLoc, RPLoc);
8141 return ExprError();
8142 }
8143
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008144 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara092990a2010-08-10 08:50:03 +00008145 argTInfo1, argTInfo2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00008146}
8147
Abramo Bagnara092990a2010-08-10 08:50:03 +00008148
John McCalldadc5752010-08-24 06:29:42 +00008149ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008150 Expr *CondExpr,
8151 Expr *LHSExpr, Expr *RHSExpr,
8152 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008153 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8154
John McCall7decc9e2010-11-18 06:31:45 +00008155 ExprValueKind VK = VK_RValue;
8156 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008157 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008158 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008159 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008160 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008161 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008162 } else {
8163 // The conditional expression is required to be a constant expression.
8164 llvm::APSInt condEval(32);
8165 SourceLocation ExpLoc;
8166 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008167 return ExprError(Diag(ExpLoc,
8168 diag::err_typecheck_choose_expr_requires_constant)
8169 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008170
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008171 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008172 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8173
8174 resType = ActiveExpr->getType();
8175 ValueDependent = ActiveExpr->isValueDependent();
8176 VK = ActiveExpr->getValueKind();
8177 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008178 }
8179
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008180 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008181 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008182 resType->isDependentType(),
8183 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008184}
8185
Steve Naroffc540d662008-09-03 18:15:37 +00008186//===----------------------------------------------------------------------===//
8187// Clang Extensions.
8188//===----------------------------------------------------------------------===//
8189
8190/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008191void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008192 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8193 PushBlockScope(BlockScope, Block);
8194 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008195 if (BlockScope)
8196 PushDeclContext(BlockScope, Block);
8197 else
8198 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008199}
8200
Mike Stump82f071f2009-02-04 22:31:32 +00008201void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008202 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00008203 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008204
John McCall8cb7bdf2010-06-04 23:28:52 +00008205 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00008206 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00008207 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008208
John McCall8e346702010-06-04 19:02:56 +00008209 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00008210 QualType RetTy;
8211 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00008212 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00008213 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00008214 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00008215 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
8216 } else {
8217 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00008218 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00008219 }
Mike Stump11289f42009-09-09 15:08:12 +00008220
John McCall8e346702010-06-04 19:02:56 +00008221 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008222
John McCalla3ccba02010-06-04 11:21:44 +00008223 // Don't allow returning an array by value.
8224 if (RetTy->isArrayType()) {
8225 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00008226 return;
8227 }
8228
John McCalla3ccba02010-06-04 11:21:44 +00008229 // Don't allow returning a objc interface by value.
8230 if (RetTy->isObjCObjectType()) {
8231 Diag(ParamInfo.getSourceRange().getBegin(),
8232 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8233 return;
8234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008235
John McCalla3ccba02010-06-04 11:21:44 +00008236 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008237 // return type. TODO: what should we do with declarators like:
8238 // ^ * { ... }
8239 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008240 if (RetTy != Context.DependentTy)
8241 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008242
John McCalla3ccba02010-06-04 11:21:44 +00008243 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008244 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCalla3ccba02010-06-04 11:21:44 +00008245 if (isa<FunctionProtoType>(T)) {
8246 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
8247 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
8248 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008249 if (Param->getIdentifier() == 0 &&
8250 !Param->isImplicit() &&
8251 !Param->isInvalidDecl() &&
8252 !getLangOptions().CPlusPlus)
8253 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008254 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008255 }
John McCalla3ccba02010-06-04 11:21:44 +00008256
8257 // Fake up parameter variables if we have a typedef, like
8258 // ^ fntype { ... }
8259 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8260 for (FunctionProtoType::arg_type_iterator
8261 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8262 ParmVarDecl *Param =
8263 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8264 ParamInfo.getSourceRange().getBegin(),
8265 *I);
John McCall8e346702010-06-04 19:02:56 +00008266 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008267 }
Steve Naroffc540d662008-09-03 18:15:37 +00008268 }
John McCalla3ccba02010-06-04 11:21:44 +00008269
John McCall8e346702010-06-04 19:02:56 +00008270 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008271 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008272 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008273 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8274 CurBlock->TheDecl->param_end(),
8275 /*CheckParameterNames=*/false);
8276 }
8277
John McCalla3ccba02010-06-04 11:21:44 +00008278 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008279 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008280
John McCall8e346702010-06-04 19:02:56 +00008281 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008282 Diag(ParamInfo.getAttributes()->getLoc(),
8283 diag::warn_attribute_sentinel_not_variadic) << 1;
8284 // FIXME: remove the attribute.
8285 }
8286
8287 // Put the parameter variables in scope. We can bail out immediately
8288 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008289 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008290 return;
8291
John McCalldf8b37c2010-03-22 09:20:08 +00008292 bool ShouldCheckShadow =
8293 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
8294
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008295 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008296 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8297 (*AI)->setOwningFunction(CurBlock->TheDecl);
8298
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008299 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008300 if ((*AI)->getIdentifier()) {
8301 if (ShouldCheckShadow)
8302 CheckShadow(CurBlock->TheScope, *AI);
8303
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008304 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008305 }
John McCallf7b2fb52010-01-22 00:28:27 +00008306 }
Steve Naroffc540d662008-09-03 18:15:37 +00008307}
8308
8309/// ActOnBlockError - If there is an error parsing a block, this callback
8310/// is invoked to pop the information about the block from the action impl.
8311void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008312 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008313 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008314 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008315}
8316
8317/// ActOnBlockStmtExpr - This is called when the body of a block statement
8318/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008319ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008320 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008321 // If blocks are disabled, emit an error.
8322 if (!LangOpts.Blocks)
8323 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008324
Douglas Gregor9a28e842010-03-01 23:15:13 +00008325 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008326
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008327 PopDeclContext();
8328
Steve Naroffc540d662008-09-03 18:15:37 +00008329 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008330 if (!BSI->ReturnType.isNull())
8331 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008332
Mike Stump3bf1ab42009-07-28 22:04:01 +00008333 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008334 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008335
8336 // If the user wrote a function type in some form, try to use that.
8337 if (!BSI->FunctionType.isNull()) {
8338 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8339
8340 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8341 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8342
8343 // Turn protoless block types into nullary block types.
8344 if (isa<FunctionNoProtoType>(FTy)) {
8345 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
8346 false, false, 0, 0, Ext);
8347
8348 // Otherwise, if we don't need to change anything about the function type,
8349 // preserve its sugar structure.
8350 } else if (FTy->getResultType() == RetTy &&
8351 (!NoReturn || FTy->getNoReturnAttr())) {
8352 BlockTy = BSI->FunctionType;
8353
8354 // Otherwise, make the minimal modifications to the function type.
8355 } else {
8356 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8357 BlockTy = Context.getFunctionType(RetTy,
8358 FPT->arg_type_begin(),
8359 FPT->getNumArgs(),
8360 FPT->isVariadic(),
8361 /*quals*/ 0,
8362 FPT->hasExceptionSpec(),
8363 FPT->hasAnyExceptionSpec(),
8364 FPT->getNumExceptions(),
8365 FPT->exception_begin(),
8366 Ext);
8367 }
8368
8369 // If we don't have a function type, just build one from nothing.
8370 } else {
8371 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
8372 false, false, 0, 0,
8373 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
8374 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008375
John McCall8e346702010-06-04 19:02:56 +00008376 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8377 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008378 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008379
Chris Lattner45542ea2009-04-19 05:28:12 +00008380 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008381 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008382 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008383
John McCallb268a282010-08-23 23:25:46 +00008384 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008385
8386 bool Good = true;
8387 // Check goto/label use.
8388 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8389 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8390 LabelStmt *L = I->second;
8391
8392 // Verify that we have no forward references left. If so, there was a goto
8393 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008394 if (L->getSubStmt() != 0) {
8395 if (!L->isUsed())
8396 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008397 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008398 }
Mike Stump314825b2010-01-19 23:08:01 +00008399
8400 // Emit error.
8401 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8402 Good = false;
8403 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008404 if (!Good) {
8405 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008406 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008407 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008408
John McCall1d570a72010-08-25 05:56:39 +00008409 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8410 BSI->hasBlockDeclRefExprs);
8411
Ted Kremenek918fe842010-03-20 21:06:02 +00008412 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008413 const sema::AnalysisBasedWarnings::Policy &WP =
8414 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008415 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008416
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008417 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008418 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008419}
8420
John McCalldadc5752010-08-24 06:29:42 +00008421ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008422 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008423 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008424 TypeSourceInfo *TInfo;
8425 QualType T = GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008426 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008427}
8428
John McCalldadc5752010-08-24 06:29:42 +00008429ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008430 Expr *E, TypeSourceInfo *TInfo,
8431 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008432 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008433
Eli Friedman121ba0c2008-08-09 23:32:40 +00008434 // Get the va_list type
8435 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008436 if (VaListType->isArrayType()) {
8437 // Deal with implicit array decay; for example, on x86-64,
8438 // va_list is an array, but it's supposed to decay to
8439 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008440 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008441 // Make sure the input expression also decays appropriately.
8442 UsualUnaryConversions(E);
8443 } else {
8444 // Otherwise, the va_list argument must be an l-value because
8445 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008446 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008447 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008448 return ExprError();
8449 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008450
Douglas Gregorad3150c2009-05-19 23:10:31 +00008451 if (!E->isTypeDependent() &&
8452 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008453 return ExprError(Diag(E->getLocStart(),
8454 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008455 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008456 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008457
Eli Friedmanba961a92009-03-23 00:24:07 +00008458 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008459 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008460
Abramo Bagnara27db2392010-08-10 10:06:15 +00008461 QualType T = TInfo->getType().getNonLValueExprType(Context);
8462 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008463}
8464
John McCalldadc5752010-08-24 06:29:42 +00008465ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008466 // The type of __null will be int or long, depending on the size of
8467 // pointers on the target.
8468 QualType Ty;
8469 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
8470 Ty = Context.IntTy;
8471 else
8472 Ty = Context.LongTy;
8473
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008474 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008475}
8476
Alexis Huntc46382e2010-04-28 23:02:27 +00008477static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008478 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008479 if (!SemaRef.getLangOptions().ObjC1)
8480 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008481
Anders Carlssonace5d072009-11-10 04:46:30 +00008482 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8483 if (!PT)
8484 return;
8485
8486 // Check if the destination is of type 'id'.
8487 if (!PT->isObjCIdType()) {
8488 // Check if the destination is the 'NSString' interface.
8489 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8490 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8491 return;
8492 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008493
Anders Carlssonace5d072009-11-10 04:46:30 +00008494 // Strip off any parens and casts.
8495 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8496 if (!SL || SL->isWide())
8497 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008498
Douglas Gregora771f462010-03-31 17:46:05 +00008499 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008500}
8501
Chris Lattner9bad62c2008-01-04 18:04:52 +00008502bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8503 SourceLocation Loc,
8504 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008505 Expr *SrcExpr, AssignmentAction Action,
8506 bool *Complained) {
8507 if (Complained)
8508 *Complained = false;
8509
Chris Lattner9bad62c2008-01-04 18:04:52 +00008510 // Decode the result (notice that AST's are still created for extensions).
8511 bool isInvalid = false;
8512 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008513 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008514
Chris Lattner9bad62c2008-01-04 18:04:52 +00008515 switch (ConvTy) {
8516 default: assert(0 && "Unknown conversion type");
8517 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008518 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008519 DiagKind = diag::ext_typecheck_convert_pointer_int;
8520 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008521 case IntToPointer:
8522 DiagKind = diag::ext_typecheck_convert_int_pointer;
8523 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008524 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008525 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008526 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8527 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008528 case IncompatiblePointerSign:
8529 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8530 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008531 case FunctionVoidPointer:
8532 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8533 break;
8534 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008535 // If the qualifiers lost were because we were applying the
8536 // (deprecated) C++ conversion from a string literal to a char*
8537 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8538 // Ideally, this check would be performed in
8539 // CheckPointerTypesForAssignment. However, that would require a
8540 // bit of refactoring (so that the second argument is an
8541 // expression, rather than a type), which should be done as part
8542 // of a larger effort to fix CheckPointerTypesForAssignment for
8543 // C++ semantics.
8544 if (getLangOptions().CPlusPlus &&
8545 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8546 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008547 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8548 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008549 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008550 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008551 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008552 case IntToBlockPointer:
8553 DiagKind = diag::err_int_to_block_pointer;
8554 break;
8555 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008556 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008557 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008558 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008559 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008560 // it can give a more specific diagnostic.
8561 DiagKind = diag::warn_incompatible_qualified_id;
8562 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008563 case IncompatibleVectors:
8564 DiagKind = diag::warn_incompatible_vectors;
8565 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008566 case Incompatible:
8567 DiagKind = diag::err_typecheck_convert_incompatible;
8568 isInvalid = true;
8569 break;
8570 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008571
Douglas Gregorc68e1402010-04-09 00:35:39 +00008572 QualType FirstType, SecondType;
8573 switch (Action) {
8574 case AA_Assigning:
8575 case AA_Initializing:
8576 // The destination type comes first.
8577 FirstType = DstType;
8578 SecondType = SrcType;
8579 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008580
Douglas Gregorc68e1402010-04-09 00:35:39 +00008581 case AA_Returning:
8582 case AA_Passing:
8583 case AA_Converting:
8584 case AA_Sending:
8585 case AA_Casting:
8586 // The source type comes first.
8587 FirstType = SrcType;
8588 SecondType = DstType;
8589 break;
8590 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008591
Douglas Gregorc68e1402010-04-09 00:35:39 +00008592 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008593 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008594 if (Complained)
8595 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008596 return isInvalid;
8597}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008598
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008599bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008600 llvm::APSInt ICEResult;
8601 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8602 if (Result)
8603 *Result = ICEResult;
8604 return false;
8605 }
8606
Anders Carlssone54e8a12008-11-30 19:50:32 +00008607 Expr::EvalResult EvalResult;
8608
Mike Stump4e1f26a2009-02-19 03:04:26 +00008609 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008610 EvalResult.HasSideEffects) {
8611 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8612
8613 if (EvalResult.Diag) {
8614 // We only show the note if it's not the usual "invalid subexpression"
8615 // or if it's actually in a subexpression.
8616 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8617 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8618 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8619 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008620
Anders Carlssone54e8a12008-11-30 19:50:32 +00008621 return true;
8622 }
8623
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008624 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8625 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008626
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008627 if (EvalResult.Diag &&
8628 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
8629 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008630
Anders Carlssone54e8a12008-11-30 19:50:32 +00008631 if (Result)
8632 *Result = EvalResult.Val.getInt();
8633 return false;
8634}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008635
Douglas Gregorff790f12009-11-26 00:44:06 +00008636void
Mike Stump11289f42009-09-09 15:08:12 +00008637Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008638 ExprEvalContexts.push_back(
8639 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008640}
8641
Mike Stump11289f42009-09-09 15:08:12 +00008642void
Douglas Gregorff790f12009-11-26 00:44:06 +00008643Sema::PopExpressionEvaluationContext() {
8644 // Pop the current expression evaluation context off the stack.
8645 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8646 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008647
Douglas Gregorfab31f42009-12-12 07:57:52 +00008648 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8649 if (Rec.PotentiallyReferenced) {
8650 // Mark any remaining declarations in the current position of the stack
8651 // as "referenced". If they were not meant to be referenced, semantic
8652 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008653 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008654 I = Rec.PotentiallyReferenced->begin(),
8655 IEnd = Rec.PotentiallyReferenced->end();
8656 I != IEnd; ++I)
8657 MarkDeclarationReferenced(I->first, I->second);
8658 }
8659
8660 if (Rec.PotentiallyDiagnosed) {
8661 // Emit any pending diagnostics.
8662 for (PotentiallyEmittedDiagnostics::iterator
8663 I = Rec.PotentiallyDiagnosed->begin(),
8664 IEnd = Rec.PotentiallyDiagnosed->end();
8665 I != IEnd; ++I)
8666 Diag(I->first, I->second);
8667 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008668 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008669
8670 // When are coming out of an unevaluated context, clear out any
8671 // temporaries that we may have created as part of the evaluation of
8672 // the expression in that context: they aren't relevant because they
8673 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008674 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008675 ExprTemporaries.size() > Rec.NumTemporaries)
8676 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8677 ExprTemporaries.end());
8678
8679 // Destroy the popped expression evaluation record.
8680 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008681}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008682
8683/// \brief Note that the given declaration was referenced in the source code.
8684///
8685/// This routine should be invoke whenever a given declaration is referenced
8686/// in the source code, and where that reference occurred. If this declaration
8687/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8688/// C99 6.9p3), then the declaration will be marked as used.
8689///
8690/// \param Loc the location where the declaration was referenced.
8691///
8692/// \param D the declaration that has been referenced by the source code.
8693void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8694 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008695
Douglas Gregorebada0772010-06-17 23:14:26 +00008696 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008697 return;
Mike Stump11289f42009-09-09 15:08:12 +00008698
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008699 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8700 // template or not. The reason for this is that unevaluated expressions
8701 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8702 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008703 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008704 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008705 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008706 return;
8707 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008708
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008709 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8710 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008711
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008712 // Do not mark anything as "used" within a dependent context; wait for
8713 // an instantiation.
8714 if (CurContext->isDependentContext())
8715 return;
Mike Stump11289f42009-09-09 15:08:12 +00008716
Douglas Gregorff790f12009-11-26 00:44:06 +00008717 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008718 case Unevaluated:
8719 // We are in an expression that is not potentially evaluated; do nothing.
8720 return;
Mike Stump11289f42009-09-09 15:08:12 +00008721
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008722 case PotentiallyEvaluated:
8723 // We are in a potentially-evaluated expression, so this declaration is
8724 // "used"; handle this below.
8725 break;
Mike Stump11289f42009-09-09 15:08:12 +00008726
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008727 case PotentiallyPotentiallyEvaluated:
8728 // We are in an expression that may be potentially evaluated; queue this
8729 // declaration reference until we know whether the expression is
8730 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008731 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008732 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008733
8734 case PotentiallyEvaluatedIfUsed:
8735 // Referenced declarations will only be used if the construct in the
8736 // containing expression is used.
8737 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008738 }
Mike Stump11289f42009-09-09 15:08:12 +00008739
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008740 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008742 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008743 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008744 if (Constructor->getParent()->hasTrivialConstructor())
8745 return;
8746 if (!Constructor->isUsed(false))
8747 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008748 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008749 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008750 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008751 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8752 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008753
Douglas Gregor88d292c2010-05-13 16:44:06 +00008754 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008755 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008756 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008757 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008758 if (Destructor->isVirtual())
8759 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008760 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8761 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8762 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008763 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008764 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008765 } else if (MethodDecl->isVirtual())
8766 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008767 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008768 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008769 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008770 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008771 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008772 bool AlreadyInstantiated = false;
8773 if (FunctionTemplateSpecializationInfo *SpecInfo
8774 = Function->getTemplateSpecializationInfo()) {
8775 if (SpecInfo->getPointOfInstantiation().isInvalid())
8776 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008777 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008778 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008779 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008780 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008781 = Function->getMemberSpecializationInfo()) {
8782 if (MSInfo->getPointOfInstantiation().isInvalid())
8783 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008784 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008785 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008786 AlreadyInstantiated = true;
8787 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008788
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008789 if (!AlreadyInstantiated) {
8790 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8791 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8792 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8793 Loc));
8794 else
Chandler Carruth54080172010-08-25 08:44:16 +00008795 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008796 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008797 } else // Walk redefinitions, as some of them may be instantiable.
8798 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8799 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008800 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008801 MarkDeclarationReferenced(Loc, *i);
8802 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008803
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008804 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008805
8806 // Recursive functions should be marked when used from another function.
8807 if (CurContext != Function)
8808 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008809
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008810 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008811 }
Mike Stump11289f42009-09-09 15:08:12 +00008812
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008813 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008814 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008815 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008816 Var->getInstantiatedFromStaticDataMember()) {
8817 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8818 assert(MSInfo && "Missing member specialization information?");
8819 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8820 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8821 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008822 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008823 }
8824 }
Mike Stump11289f42009-09-09 15:08:12 +00008825
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008826 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008827
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008828 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008829 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008830 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008831}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008832
Douglas Gregor5597ab42010-05-07 23:12:07 +00008833namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008834 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008835 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008836 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008837 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8838 Sema &S;
8839 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008840
Douglas Gregor5597ab42010-05-07 23:12:07 +00008841 public:
8842 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008843
Douglas Gregor5597ab42010-05-07 23:12:07 +00008844 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008845
8846 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8847 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008848 };
8849}
8850
Chandler Carruthaf80f662010-06-09 08:17:30 +00008851bool MarkReferencedDecls::TraverseTemplateArgument(
8852 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008853 if (Arg.getKind() == TemplateArgument::Declaration) {
8854 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8855 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008856
8857 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008858}
8859
Chandler Carruthaf80f662010-06-09 08:17:30 +00008860bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008861 if (ClassTemplateSpecializationDecl *Spec
8862 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8863 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008864 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008865 }
8866
Chandler Carruthc65667c2010-06-10 10:31:57 +00008867 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008868}
8869
8870void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8871 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00008872 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00008873}
8874
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008875namespace {
8876 /// \brief Helper class that marks all of the declarations referenced by
8877 /// potentially-evaluated subexpressions as "referenced".
8878 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8879 Sema &S;
8880
8881 public:
8882 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8883
8884 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8885
8886 void VisitDeclRefExpr(DeclRefExpr *E) {
8887 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8888 }
8889
8890 void VisitMemberExpr(MemberExpr *E) {
8891 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008892 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008893 }
8894
8895 void VisitCXXNewExpr(CXXNewExpr *E) {
8896 if (E->getConstructor())
8897 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
8898 if (E->getOperatorNew())
8899 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
8900 if (E->getOperatorDelete())
8901 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008902 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008903 }
8904
8905 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8906 if (E->getOperatorDelete())
8907 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00008908 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
8909 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8910 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8911 S.MarkDeclarationReferenced(E->getLocStart(),
8912 S.LookupDestructor(Record));
8913 }
8914
Douglas Gregor32b3de52010-09-11 23:32:50 +00008915 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008916 }
8917
8918 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8919 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00008920 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008921 }
8922
8923 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
8924 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8925 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00008926
8927 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8928 Visit(E->getExpr());
8929 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008930 };
8931}
8932
8933/// \brief Mark any declarations that appear within this expression or any
8934/// potentially-evaluated subexpressions as "referenced".
8935void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
8936 EvaluatedExprMarker(*this).Visit(E);
8937}
8938
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008939/// \brief Emit a diagnostic that describes an effect on the run-time behavior
8940/// of the program being compiled.
8941///
8942/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008943/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008944/// possibility that the code will actually be executable. Code in sizeof()
8945/// expressions, code used only during overload resolution, etc., are not
8946/// potentially evaluated. This routine will suppress such diagnostics or,
8947/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008948/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008949/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008950///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008951/// This routine should be used for all diagnostics that describe the run-time
8952/// behavior of a program, such as passing a non-POD value through an ellipsis.
8953/// Failure to do so will likely result in spurious diagnostics or failures
8954/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008955bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008956 const PartialDiagnostic &PD) {
8957 switch (ExprEvalContexts.back().Context ) {
8958 case Unevaluated:
8959 // The argument will never be evaluated, so don't complain.
8960 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008961
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008962 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008963 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008964 Diag(Loc, PD);
8965 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008966
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00008967 case PotentiallyPotentiallyEvaluated:
8968 ExprEvalContexts.back().addDiagnostic(Loc, PD);
8969 break;
8970 }
8971
8972 return false;
8973}
8974
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008975bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
8976 CallExpr *CE, FunctionDecl *FD) {
8977 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
8978 return false;
8979
8980 PartialDiagnostic Note =
8981 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
8982 << FD->getDeclName() : PDiag();
8983 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008984
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008985 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008986 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008987 PDiag(diag::err_call_function_incomplete_return)
8988 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008989 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008990 << CE->getSourceRange(),
8991 std::make_pair(NoteLoc, Note)))
8992 return true;
8993
8994 return false;
8995}
8996
John McCalld5707ab2009-10-12 21:59:07 +00008997// Diagnose the common s/=/==/ typo. Note that adding parentheses
8998// will prevent this condition from triggering, which is what we want.
8999void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9000 SourceLocation Loc;
9001
John McCall0506e4a2009-11-11 02:41:58 +00009002 unsigned diagnostic = diag::warn_condition_is_assignment;
9003
John McCalld5707ab2009-10-12 21:59:07 +00009004 if (isa<BinaryOperator>(E)) {
9005 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00009006 if (Op->getOpcode() != BO_Assign)
John McCalld5707ab2009-10-12 21:59:07 +00009007 return;
9008
John McCallb0e419e2009-11-12 00:06:05 +00009009 // Greylist some idioms by putting them into a warning subcategory.
9010 if (ObjCMessageExpr *ME
9011 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9012 Selector Sel = ME->getSelector();
9013
John McCallb0e419e2009-11-12 00:06:05 +00009014 // self = [<foo> init...]
9015 if (isSelfExpr(Op->getLHS())
9016 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9017 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9018
9019 // <foo> = [<bar> nextObject]
9020 else if (Sel.isUnarySelector() &&
9021 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9022 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9023 }
John McCall0506e4a2009-11-11 02:41:58 +00009024
John McCalld5707ab2009-10-12 21:59:07 +00009025 Loc = Op->getOperatorLoc();
9026 } else if (isa<CXXOperatorCallExpr>(E)) {
9027 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9028 if (Op->getOperator() != OO_Equal)
9029 return;
9030
9031 Loc = Op->getOperatorLoc();
9032 } else {
9033 // Not an assignment.
9034 return;
9035 }
9036
John McCalld5707ab2009-10-12 21:59:07 +00009037 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009038 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009039
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009040 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00009041 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00009042 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009043 Diag(Loc, diag::note_condition_assign_silence)
9044 << FixItHint::CreateInsertion(Open, "(")
9045 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009046}
9047
9048bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9049 DiagnoseAssignmentAsCondition(E);
9050
9051 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009052 if (E->isBoundMemberFunction(Context))
9053 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9054 << E->getSourceRange();
9055
John McCall34376a62010-12-04 03:47:34 +00009056 if (getLangOptions().CPlusPlus)
9057 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9058
9059 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009060
9061 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009062 if (!T->isScalarType()) // C99 6.8.4.1p1
9063 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9064 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009065 }
9066
9067 return false;
9068}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009069
John McCalldadc5752010-08-24 06:29:42 +00009070ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9071 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009072 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009073 return ExprError();
9074
Douglas Gregorb412e172010-07-25 18:17:45 +00009075 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009076 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009077
9078 return Owned(Sub);
9079}
John McCall36e7fe32010-10-12 00:20:44 +00009080
9081/// Check for operands with placeholder types and complain if found.
9082/// Returns true if there was an error and no recovery was possible.
9083ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9084 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9085 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9086
9087 // If this is overload, check for a single overload.
9088 if (BT->getKind() == BuiltinType::Overload) {
9089 if (FunctionDecl *Specialization
9090 = ResolveSingleFunctionTemplateSpecialization(E)) {
9091 // The access doesn't really matter in this case.
9092 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9093 Specialization->getAccess());
9094 E = FixOverloadedFunctionReference(E, Found, Specialization);
9095 if (!E) return ExprError();
9096 return Owned(E);
9097 }
9098
John McCall36226622010-10-12 02:09:17 +00009099 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009100 return ExprError();
9101 }
9102
9103 // Otherwise it's a use of undeduced auto.
9104 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9105
9106 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9107 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9108 << DRE->getDecl() << E->getSourceRange();
9109 return ExprError();
9110}