blob: b89e2bcc800f64349c1f72b031e804b15ca2a6e4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000042
David Chisnall0f436562009-08-17 16:35:33 +000043
Douglas Gregor48f3bb92009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000058///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith34b41d92011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000084 }
85
Douglas Gregor48f3bb92009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
90 Diag(D->getLocation(), diag::note_unavailable_here) << true;
91 return true;
92 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000093 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000094
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
107 if (Message.empty()) {
108 if (!UnknownObjCClass)
109 Diag(Loc, diag::err_unavailable) << D->getDeclName();
110 else
111 Diag(Loc, diag::warn_unavailable_fwdclass_message)
112 << D->getDeclName();
113 }
114 else
115 Diag(Loc, diag::err_unavailable_message)
116 << D->getDeclName() << Message;
117 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
118 break;
119 }
120
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000121 // Warn if this is used but marked unused.
122 if (D->hasAttr<UnusedAttr>())
123 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
124
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000125 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000126}
127
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000128/// \brief Retrieve the message suffix that should be added to a
129/// diagnostic complaining about the given function being deleted or
130/// unavailable.
131std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
132 // FIXME: C++0x implicitly-deleted special member functions could be
133 // detected here so that we could improve diagnostics to say, e.g.,
134 // "base class 'A' had a deleted copy constructor".
135 if (FD->isDeleted())
136 return std::string();
137
138 std::string Message;
139 if (FD->getAvailability(&Message))
140 return ": " + Message;
141
142 return std::string();
143}
144
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000145/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000146/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000147/// attribute. It warns if call does not have the sentinel argument.
148///
149void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000150 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000151 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000152 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000153 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000154
155 // FIXME: In C++0x, if any of the arguments are parameter pack
156 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 int sentinelPos = attr->getSentinel();
158 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Mike Stump390b4cc2009-05-16 07:39:55 +0000160 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
161 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000206 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000207 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
246 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
247 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000248}
249
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000250SourceRange Sema::getExprRange(ExprTy *E) const {
251 Expr *Ex = (Expr *)E;
252 return Ex? Ex->getSourceRange() : SourceRange();
253}
254
Chris Lattnere7a2e912008-07-25 21:10:04 +0000255//===----------------------------------------------------------------------===//
256// Standard Promotions and Conversions
257//===----------------------------------------------------------------------===//
258
Chris Lattnere7a2e912008-07-25 21:10:04 +0000259/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000260ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000261 QualType Ty = E->getType();
262 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
263
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000265 E = ImpCastExprToType(E, Context.getPointerType(Ty),
266 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000267 else if (Ty->isArrayType()) {
268 // In C90 mode, arrays only promote to pointers if the array expression is
269 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
270 // type 'array of type' is converted to an expression that has type 'pointer
271 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
272 // that has type 'array of type' ...". The relevant change is "an lvalue"
273 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000274 //
275 // C++ 4.2p1:
276 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
277 // T" can be converted to an rvalue of type "pointer to T".
278 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000279 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
281 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000282 }
John Wiegley429bb272011-04-08 18:41:53 +0000283 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284}
285
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000286static void CheckForNullPointerDereference(Sema &S, Expr *E) {
287 // Check to see if we are dereferencing a null pointer. If so,
288 // and if not volatile-qualified, this is undefined behavior that the
289 // optimizer will delete, so warn about it. People sometimes try to use this
290 // to get a deterministic trap and are surprised by clang's behavior. This
291 // only handles the pattern "*null", which is a very syntactic check.
292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
293 if (UO->getOpcode() == UO_Deref &&
294 UO->getSubExpr()->IgnoreParenCasts()->
295 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
296 !UO->getType().isVolatileQualified()) {
297 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
298 S.PDiag(diag::warn_indirection_through_null)
299 << UO->getSubExpr()->getSourceRange());
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::note_indirection_through_null));
302 }
303}
304
John Wiegley429bb272011-04-08 18:41:53 +0000305ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000306 // C++ [conv.lval]p1:
307 // A glvalue of a non-function, non-array type T can be
308 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000309 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000310
John McCall409fa9a2010-12-06 20:48:59 +0000311 QualType T = E->getType();
312 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000313
John McCall409fa9a2010-12-06 20:48:59 +0000314 // Create a load out of an ObjCProperty l-value, if necessary.
315 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000316 ExprResult Res = ConvertPropertyForRValue(E);
317 if (Res.isInvalid())
318 return Owned(E);
319 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000320 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000321 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000322 }
John McCall409fa9a2010-12-06 20:48:59 +0000323
324 // We don't want to throw lvalue-to-rvalue casts on top of
325 // expressions of certain types in C++.
326 if (getLangOptions().CPlusPlus &&
327 (E->getType() == Context.OverloadTy ||
328 T->isDependentType() ||
329 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000330 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000331
332 // The C standard is actually really unclear on this point, and
333 // DR106 tells us what the result should be but not why. It's
334 // generally best to say that void types just doesn't undergo
335 // lvalue-to-rvalue at all. Note that expressions of unqualified
336 // 'void' type are never l-values, but qualified void can be.
337 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000338 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000339
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000340 CheckForNullPointerDereference(*this, E);
341
John McCall409fa9a2010-12-06 20:48:59 +0000342 // C++ [conv.lval]p1:
343 // [...] If T is a non-class type, the type of the prvalue is the
344 // cv-unqualified version of T. Otherwise, the type of the
345 // rvalue is T.
346 //
347 // C99 6.3.2.1p2:
348 // If the lvalue has qualified type, the value has the unqualified
349 // version of the type of the lvalue; otherwise, the value has the
350 // type of the lvalue.
351 if (T.hasQualifiers())
352 T = T.getUnqualifiedType();
353
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000354 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000355
John Wiegley429bb272011-04-08 18:41:53 +0000356 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
357 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000358}
359
John Wiegley429bb272011-04-08 18:41:53 +0000360ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
361 ExprResult Res = DefaultFunctionArrayConversion(E);
362 if (Res.isInvalid())
363 return ExprError();
364 Res = DefaultLvalueConversion(Res.take());
365 if (Res.isInvalid())
366 return ExprError();
367 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000368}
369
370
Chris Lattnere7a2e912008-07-25 21:10:04 +0000371/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000372/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000373/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000374/// apply if the array is an argument to the sizeof or address (&) operators.
375/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000376ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000377 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000378 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
379 if (Res.isInvalid())
380 return Owned(E);
381 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000382
383 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000384 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000385
386 // Try to perform integral promotions if the object has a theoretically
387 // promotable type.
388 if (Ty->isIntegralOrUnscopedEnumerationType()) {
389 // C99 6.3.1.1p2:
390 //
391 // The following may be used in an expression wherever an int or
392 // unsigned int may be used:
393 // - an object or expression with an integer type whose integer
394 // conversion rank is less than or equal to the rank of int
395 // and unsigned int.
396 // - A bit-field of type _Bool, int, signed int, or unsigned int.
397 //
398 // If an int can represent all values of the original type, the
399 // value is converted to an int; otherwise, it is converted to an
400 // unsigned int. These are called the integer promotions. All
401 // other types are unchanged by the integer promotions.
402
403 QualType PTy = Context.isPromotableBitField(E);
404 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000405 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
406 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000407 }
408 if (Ty->isPromotableIntegerType()) {
409 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
411 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000412 }
Eli Friedman04e83572009-08-20 04:21:42 +0000413 }
John Wiegley429bb272011-04-08 18:41:53 +0000414 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000415}
416
Chris Lattner05faf172008-07-25 22:25:12 +0000417/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000418/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000419/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000420ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
421 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000422 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000423
John Wiegley429bb272011-04-08 18:41:53 +0000424 ExprResult Res = UsualUnaryConversions(E);
425 if (Res.isInvalid())
426 return Owned(E);
427 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000428
Chris Lattner05faf172008-07-25 22:25:12 +0000429 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000430 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
432
433 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000434}
435
Chris Lattner312531a2009-04-12 08:11:20 +0000436/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
437/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000438/// interfaces passed by value.
439ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattner40378332010-05-16 04:01:30 +0000440 FunctionDecl *FDecl) {
John Wiegley429bb272011-04-08 18:41:53 +0000441 ExprResult ExprRes = DefaultArgumentPromotion(E);
442 if (ExprRes.isInvalid())
443 return ExprError();
444 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner40378332010-05-16 04:01:30 +0000446 // __builtin_va_start takes the second argument as a "varargs" argument, but
447 // it doesn't actually do anything with it. It doesn't need to be non-pod
448 // etc.
449 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000450 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000451
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000452 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000453 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000454 DiagRuntimeBehavior(E->getLocStart(), 0,
455 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
456 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000457 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000458
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000459 if (!E->getType()->isPODType()) {
460 // C++0x [expr.call]p7:
461 // Passing a potentially-evaluated argument of class type (Clause 9)
462 // having a non-trivial copy constructor, a non-trivial move constructor,
463 // or a non-trivial destructor, with no corresponding parameter,
464 // is conditionally-supported with implementation-defined semantics.
465 bool TrivialEnough = false;
466 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
467 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
468 if (Record->hasTrivialCopyConstructor() &&
469 Record->hasTrivialMoveConstructor() &&
470 Record->hasTrivialDestructor())
471 TrivialEnough = true;
472 }
473 }
474
475 if (TrivialEnough) {
476 // Nothing to diagnose. This is okay.
477 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000478 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000479 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000480 << CT)) {
481 // Turn this into a trap.
482 CXXScopeSpec SS;
483 UnqualifiedId Name;
484 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
485 E->getLocStart());
486 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
487 if (TrapFn.isInvalid())
488 return ExprError();
489
490 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
491 MultiExprArg(), E->getLocEnd());
492 if (Call.isInvalid())
493 return ExprError();
494
495 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
496 Call.get(), E);
497 if (Comma.isInvalid())
498 return ExprError();
499
500 E = Comma.get();
501 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000502 }
503
John Wiegley429bb272011-04-08 18:41:53 +0000504 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000505}
506
Chris Lattnere7a2e912008-07-25 21:10:04 +0000507/// UsualArithmeticConversions - Performs various conversions that are common to
508/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000509/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000510/// responsible for emitting appropriate error diagnostics.
511/// FIXME: verify the conversion rules for "complex int" are consistent with
512/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000513QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000514 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000515 if (!isCompAssign) {
516 lhsExpr = UsualUnaryConversions(lhsExpr.take());
517 if (lhsExpr.isInvalid())
518 return QualType();
519 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000520
John Wiegley429bb272011-04-08 18:41:53 +0000521 rhsExpr = UsualUnaryConversions(rhsExpr.take());
522 if (rhsExpr.isInvalid())
523 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000524
Mike Stump1eb44332009-09-09 15:08:12 +0000525 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000526 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000527 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000528 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000529 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000530 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000531
532 // If both types are identical, no conversion is needed.
533 if (lhs == rhs)
534 return lhs;
535
536 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
537 // The caller can deal with this (e.g. pointer + int).
538 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
539 return lhs;
540
John McCallcf33b242010-11-13 08:17:45 +0000541 // Apply unary and bitfield promotions to the LHS's type.
542 QualType lhs_unpromoted = lhs;
543 if (lhs->isPromotableIntegerType())
544 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000545 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000546 if (!LHSBitfieldPromoteTy.isNull())
547 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000548 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000549 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000550
John McCallcf33b242010-11-13 08:17:45 +0000551 // If both types are identical, no conversion is needed.
552 if (lhs == rhs)
553 return lhs;
554
555 // At this point, we have two different arithmetic types.
556
557 // Handle complex types first (C99 6.3.1.8p1).
558 bool LHSComplexFloat = lhs->isComplexType();
559 bool RHSComplexFloat = rhs->isComplexType();
560 if (LHSComplexFloat || RHSComplexFloat) {
561 // if we have an integer operand, the result is the complex type.
562
John McCall2bb5d002010-11-13 09:02:35 +0000563 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
564 if (rhs->isIntegerType()) {
565 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000566 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
567 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000568 } else {
569 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000570 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000571 }
John McCallcf33b242010-11-13 08:17:45 +0000572 return lhs;
573 }
574
John McCall2bb5d002010-11-13 09:02:35 +0000575 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
576 if (!isCompAssign) {
577 // int -> float -> _Complex float
578 if (lhs->isIntegerType()) {
579 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000580 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
581 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000582 } else {
583 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000584 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000585 }
586 }
John McCallcf33b242010-11-13 08:17:45 +0000587 return rhs;
588 }
589
590 // This handles complex/complex, complex/float, or float/complex.
591 // When both operands are complex, the shorter operand is converted to the
592 // type of the longer, and that is the type of the result. This corresponds
593 // to what is done when combining two real floating-point operands.
594 // The fun begins when size promotion occur across type domains.
595 // From H&S 6.3.4: When one operand is complex and the other is a real
596 // floating-point type, the less precise type is converted, within it's
597 // real or complex domain, to the precision of the other type. For example,
598 // when combining a "long double" with a "double _Complex", the
599 // "double _Complex" is promoted to "long double _Complex".
600 int order = Context.getFloatingTypeOrder(lhs, rhs);
601
602 // If both are complex, just cast to the more precise type.
603 if (LHSComplexFloat && RHSComplexFloat) {
604 if (order > 0) {
605 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000606 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000607 return lhs;
608
609 } else if (order < 0) {
610 // _Complex float -> _Complex double
611 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000612 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000613 return rhs;
614 }
615 return lhs;
616 }
617
618 // If just the LHS is complex, the RHS needs to be converted,
619 // and the LHS might need to be promoted.
620 if (LHSComplexFloat) {
621 if (order > 0) { // LHS is wider
622 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000623 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000624 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
625 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000626 return lhs;
627 }
628
629 // RHS is at least as wide. Find its corresponding complex type.
630 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
631
632 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000633 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000634
635 // _Complex float -> _Complex double
636 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000637 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000638
639 return result;
640 }
641
642 // Just the RHS is complex, so the LHS needs to be converted
643 // and the RHS might need to be promoted.
644 assert(RHSComplexFloat);
645
646 if (order < 0) { // RHS is wider
647 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000648 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000649 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000650 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
651 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000652 }
John McCallcf33b242010-11-13 08:17:45 +0000653 return rhs;
654 }
655
656 // LHS is at least as wide. Find its corresponding complex type.
657 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
658
659 // double -> _Complex double
660 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000661 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000662
663 // _Complex float -> _Complex double
664 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000665 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000666
667 return result;
668 }
669
670 // Now handle "real" floating types (i.e. float, double, long double).
671 bool LHSFloat = lhs->isRealFloatingType();
672 bool RHSFloat = rhs->isRealFloatingType();
673 if (LHSFloat || RHSFloat) {
674 // If we have two real floating types, convert the smaller operand
675 // to the bigger result.
676 if (LHSFloat && RHSFloat) {
677 int order = Context.getFloatingTypeOrder(lhs, rhs);
678 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000679 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000680 return lhs;
681 }
682
683 assert(order < 0 && "illegal float comparison");
684 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000686 return rhs;
687 }
688
689 // If we have an integer operand, the result is the real floating type.
690 if (LHSFloat) {
691 if (rhs->isIntegerType()) {
692 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000693 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000694 return lhs;
695 }
696
697 // Convert both sides to the appropriate complex float.
698 assert(rhs->isComplexIntegerType());
699 QualType result = Context.getComplexType(lhs);
700
701 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000702 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000703
704 // float -> _Complex float
705 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000706 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000707
708 return result;
709 }
710
711 assert(RHSFloat);
712 if (lhs->isIntegerType()) {
713 // Convert lhs to the rhs floating point type.
714 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000715 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000716 return rhs;
717 }
718
719 // Convert both sides to the appropriate complex float.
720 assert(lhs->isComplexIntegerType());
721 QualType result = Context.getComplexType(rhs);
722
723 // _Complex int -> _Complex float
724 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000725 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000726
727 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000728 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000729
730 return result;
731 }
732
733 // Handle GCC complex int extension.
734 // FIXME: if the operands are (int, _Complex long), we currently
735 // don't promote the complex. Also, signedness?
736 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
737 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
738 if (lhsComplexInt && rhsComplexInt) {
739 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
740 rhsComplexInt->getElementType());
741 assert(order && "inequal types with equal element ordering");
742 if (order > 0) {
743 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000744 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000745 return lhs;
746 }
747
748 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000749 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000750 return rhs;
751 } else if (lhsComplexInt) {
752 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000753 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000754 return lhs;
755 } else if (rhsComplexInt) {
756 // int -> _Complex int
757 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000758 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000759 return rhs;
760 }
761
762 // Finally, we have two differing integer types.
763 // The rules for this case are in C99 6.3.1.8
764 int compare = Context.getIntegerTypeOrder(lhs, rhs);
765 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
766 rhsSigned = rhs->hasSignedIntegerRepresentation();
767 if (lhsSigned == rhsSigned) {
768 // Same signedness; use the higher-ranked type
769 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000770 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000771 return lhs;
772 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000773 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000774 return rhs;
775 } else if (compare != (lhsSigned ? 1 : -1)) {
776 // The unsigned type has greater than or equal rank to the
777 // signed type, so use the unsigned type
778 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000779 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000780 return lhs;
781 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000782 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000783 return rhs;
784 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
785 // The two types are different widths; if we are here, that
786 // means the signed type is larger than the unsigned type, so
787 // use the signed type.
788 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000789 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000790 return lhs;
791 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000792 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000793 return rhs;
794 } else {
795 // The signed type is higher-ranked than the unsigned type,
796 // but isn't actually any bigger (like unsigned int and long
797 // on most 32-bit systems). Use the unsigned type corresponding
798 // to the signed type.
799 QualType result =
800 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000802 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000803 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000804 return result;
805 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000806}
807
Chris Lattnere7a2e912008-07-25 21:10:04 +0000808//===----------------------------------------------------------------------===//
809// Semantic Analysis for various Expression Types
810//===----------------------------------------------------------------------===//
811
812
Peter Collingbournef111d932011-04-15 00:35:48 +0000813ExprResult
814Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
815 SourceLocation DefaultLoc,
816 SourceLocation RParenLoc,
817 Expr *ControllingExpr,
818 MultiTypeArg types,
819 MultiExprArg exprs) {
820 unsigned NumAssocs = types.size();
821 assert(NumAssocs == exprs.size());
822
823 ParsedType *ParsedTypes = types.release();
824 Expr **Exprs = exprs.release();
825
826 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
827 for (unsigned i = 0; i < NumAssocs; ++i) {
828 if (ParsedTypes[i])
829 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
830 else
831 Types[i] = 0;
832 }
833
834 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
835 ControllingExpr, Types, Exprs,
836 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000837 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000838 return ER;
839}
840
841ExprResult
842Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
843 SourceLocation DefaultLoc,
844 SourceLocation RParenLoc,
845 Expr *ControllingExpr,
846 TypeSourceInfo **Types,
847 Expr **Exprs,
848 unsigned NumAssocs) {
849 bool TypeErrorFound = false,
850 IsResultDependent = ControllingExpr->isTypeDependent(),
851 ContainsUnexpandedParameterPack
852 = ControllingExpr->containsUnexpandedParameterPack();
853
854 for (unsigned i = 0; i < NumAssocs; ++i) {
855 if (Exprs[i]->containsUnexpandedParameterPack())
856 ContainsUnexpandedParameterPack = true;
857
858 if (Types[i]) {
859 if (Types[i]->getType()->containsUnexpandedParameterPack())
860 ContainsUnexpandedParameterPack = true;
861
862 if (Types[i]->getType()->isDependentType()) {
863 IsResultDependent = true;
864 } else {
865 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
866 // complete object type other than a variably modified type."
867 unsigned D = 0;
868 if (Types[i]->getType()->isIncompleteType())
869 D = diag::err_assoc_type_incomplete;
870 else if (!Types[i]->getType()->isObjectType())
871 D = diag::err_assoc_type_nonobject;
872 else if (Types[i]->getType()->isVariablyModifiedType())
873 D = diag::err_assoc_type_variably_modified;
874
875 if (D != 0) {
876 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
877 << Types[i]->getTypeLoc().getSourceRange()
878 << Types[i]->getType();
879 TypeErrorFound = true;
880 }
881
882 // C1X 6.5.1.1p2 "No two generic associations in the same generic
883 // selection shall specify compatible types."
884 for (unsigned j = i+1; j < NumAssocs; ++j)
885 if (Types[j] && !Types[j]->getType()->isDependentType() &&
886 Context.typesAreCompatible(Types[i]->getType(),
887 Types[j]->getType())) {
888 Diag(Types[j]->getTypeLoc().getBeginLoc(),
889 diag::err_assoc_compatible_types)
890 << Types[j]->getTypeLoc().getSourceRange()
891 << Types[j]->getType()
892 << Types[i]->getType();
893 Diag(Types[i]->getTypeLoc().getBeginLoc(),
894 diag::note_compat_assoc)
895 << Types[i]->getTypeLoc().getSourceRange()
896 << Types[i]->getType();
897 TypeErrorFound = true;
898 }
899 }
900 }
901 }
902 if (TypeErrorFound)
903 return ExprError();
904
905 // If we determined that the generic selection is result-dependent, don't
906 // try to compute the result expression.
907 if (IsResultDependent)
908 return Owned(new (Context) GenericSelectionExpr(
909 Context, KeyLoc, ControllingExpr,
910 Types, Exprs, NumAssocs, DefaultLoc,
911 RParenLoc, ContainsUnexpandedParameterPack));
912
913 llvm::SmallVector<unsigned, 1> CompatIndices;
914 unsigned DefaultIndex = -1U;
915 for (unsigned i = 0; i < NumAssocs; ++i) {
916 if (!Types[i])
917 DefaultIndex = i;
918 else if (Context.typesAreCompatible(ControllingExpr->getType(),
919 Types[i]->getType()))
920 CompatIndices.push_back(i);
921 }
922
923 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
924 // type compatible with at most one of the types named in its generic
925 // association list."
926 if (CompatIndices.size() > 1) {
927 // We strip parens here because the controlling expression is typically
928 // parenthesized in macro definitions.
929 ControllingExpr = ControllingExpr->IgnoreParens();
930 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
931 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
932 << (unsigned) CompatIndices.size();
933 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
934 E = CompatIndices.end(); I != E; ++I) {
935 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
936 diag::note_compat_assoc)
937 << Types[*I]->getTypeLoc().getSourceRange()
938 << Types[*I]->getType();
939 }
940 return ExprError();
941 }
942
943 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
944 // its controlling expression shall have type compatible with exactly one of
945 // the types named in its generic association list."
946 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
947 // We strip parens here because the controlling expression is typically
948 // parenthesized in macro definitions.
949 ControllingExpr = ControllingExpr->IgnoreParens();
950 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
951 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
956 // type name that is compatible with the type of the controlling expression,
957 // then the result expression of the generic selection is the expression
958 // in that generic association. Otherwise, the result expression of the
959 // generic selection is the expression in the default generic association."
960 unsigned ResultIndex =
961 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
962
963 return Owned(new (Context) GenericSelectionExpr(
964 Context, KeyLoc, ControllingExpr,
965 Types, Exprs, NumAssocs, DefaultLoc,
966 RParenLoc, ContainsUnexpandedParameterPack,
967 ResultIndex));
968}
969
Steve Narofff69936d2007-09-16 03:34:24 +0000970/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000971/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
972/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
973/// multiple tokens. However, the common case is that StringToks points to one
974/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000975///
John McCall60d7b3a2010-08-24 06:29:42 +0000976ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000977Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 assert(NumStringToks && "Must have at least one string!");
979
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000980 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000982 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000983
984 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
985 for (unsigned i = 0; i != NumStringToks; ++i)
986 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000987
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000988 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000989 if (Literal.AnyWide)
990 StrTy = Context.getWCharType();
991 else if (Literal.Pascal)
992 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000993
994 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000995 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000996 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000997
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000998 // Get an array type for the string, according to C99 6.4.5. This includes
999 // the nul terminator character as well as the string length for pascal
1000 // strings.
1001 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001002 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001003 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001006 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1007 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +00001008 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001009 &StringTokLocs[0],
1010 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001011}
1012
John McCall469a1eb2011-02-02 13:00:07 +00001013enum CaptureResult {
1014 /// No capture is required.
1015 CR_NoCapture,
1016
1017 /// A capture is required.
1018 CR_Capture,
1019
John McCall6b5a61b2011-02-07 10:33:21 +00001020 /// A by-ref capture is required.
1021 CR_CaptureByRef,
1022
John McCall469a1eb2011-02-02 13:00:07 +00001023 /// An error occurred when trying to capture the given variable.
1024 CR_Error
1025};
1026
1027/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001028///
John McCall469a1eb2011-02-02 13:00:07 +00001029/// \param var - the variable referenced
1030/// \param DC - the context which we couldn't capture through
1031static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001032diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001033 VarDecl *var, DeclContext *DC) {
1034 switch (S.ExprEvalContexts.back().Context) {
1035 case Sema::Unevaluated:
1036 // The argument will never be evaluated, so don't complain.
1037 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001038
John McCall469a1eb2011-02-02 13:00:07 +00001039 case Sema::PotentiallyEvaluated:
1040 case Sema::PotentiallyEvaluatedIfUsed:
1041 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001042
John McCall469a1eb2011-02-02 13:00:07 +00001043 case Sema::PotentiallyPotentiallyEvaluated:
1044 // FIXME: delay these!
1045 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John McCall469a1eb2011-02-02 13:00:07 +00001048 // Don't diagnose about capture if we're not actually in code right
1049 // now; in general, there are more appropriate places that will
1050 // diagnose this.
1051 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1052
John McCall4f38f412011-03-22 23:15:50 +00001053 // Certain madnesses can happen with parameter declarations, which
1054 // we want to ignore.
1055 if (isa<ParmVarDecl>(var)) {
1056 // - If the parameter still belongs to the translation unit, then
1057 // we're actually just using one parameter in the declaration of
1058 // the next. This is useful in e.g. VLAs.
1059 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1060 return CR_NoCapture;
1061
1062 // - This particular madness can happen in ill-formed default
1063 // arguments; claim it's okay and let downstream code handle it.
1064 if (S.CurContext == var->getDeclContext()->getParent())
1065 return CR_NoCapture;
1066 }
John McCall469a1eb2011-02-02 13:00:07 +00001067
1068 DeclarationName functionName;
1069 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1070 functionName = fn->getDeclName();
1071 // FIXME: variable from enclosing block that we couldn't capture from!
1072
1073 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1074 << var->getIdentifier() << functionName;
1075 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1076 << var->getIdentifier();
1077
1078 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001079}
1080
John McCall6b5a61b2011-02-07 10:33:21 +00001081/// There is a well-formed capture at a particular scope level;
1082/// propagate it through all the nested blocks.
1083static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1084 const BlockDecl::Capture &capture) {
1085 VarDecl *var = capture.getVariable();
1086
1087 // Update all the inner blocks with the capture information.
1088 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1089 i != e; ++i) {
1090 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1091 innerBlock->Captures.push_back(
1092 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1093 /*nested*/ true, capture.getCopyExpr()));
1094 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1095 }
1096
1097 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1098}
1099
1100/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001101/// given value in the current context requires a variable capture.
1102///
1103/// This also keeps the captures set in the BlockScopeInfo records
1104/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001105static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001106 ValueDecl *value) {
1107 // Only variables ever require capture.
1108 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001109 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001110
1111 // Fast path: variables from the current context never require capture.
1112 DeclContext *DC = S.CurContext;
1113 if (var->getDeclContext() == DC) return CR_NoCapture;
1114
1115 // Only variables with local storage require capture.
1116 // FIXME: What about 'const' variables in C++?
1117 if (!var->hasLocalStorage()) return CR_NoCapture;
1118
1119 // Otherwise, we need to capture.
1120
1121 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001122 do {
1123 // Only blocks (and eventually C++0x closures) can capture; other
1124 // scopes don't work.
1125 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001126 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001127
1128 BlockScopeInfo *blockScope =
1129 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1130 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1131
John McCall6b5a61b2011-02-07 10:33:21 +00001132 // Check whether we've already captured it in this block. If so,
1133 // we're done.
1134 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1135 return propagateCapture(S, functionScopesIndex,
1136 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001137
1138 functionScopesIndex--;
1139 DC = cast<BlockDecl>(DC)->getDeclContext();
1140 } while (var->getDeclContext() != DC);
1141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 // Okay, we descended all the way to the block that defines the variable.
1143 // Actually try to capture it.
1144 QualType type = var->getType();
1145
1146 // Prohibit variably-modified types.
1147 if (type->isVariablyModifiedType()) {
1148 S.Diag(loc, diag::err_ref_vm_type);
1149 S.Diag(var->getLocation(), diag::note_declared_at);
1150 return CR_Error;
1151 }
1152
1153 // Prohibit arrays, even in __block variables, but not references to
1154 // them.
1155 if (type->isArrayType()) {
1156 S.Diag(loc, diag::err_ref_array_type);
1157 S.Diag(var->getLocation(), diag::note_declared_at);
1158 return CR_Error;
1159 }
1160
1161 S.MarkDeclarationReferenced(loc, var);
1162
1163 // The BlocksAttr indicates the variable is bound by-reference.
1164 bool byRef = var->hasAttr<BlocksAttr>();
1165
1166 // Build a copy expression.
1167 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001168 const RecordType *rtype;
1169 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1170 (rtype = type->getAs<RecordType>())) {
1171
1172 // The capture logic needs the destructor, so make sure we mark it.
1173 // Usually this is unnecessary because most local variables have
1174 // their destructors marked at declaration time, but parameters are
1175 // an exception because it's technically only the call site that
1176 // actually requires the destructor.
1177 if (isa<ParmVarDecl>(var))
1178 S.FinalizeVarWithDestructor(var, rtype);
1179
John McCall6b5a61b2011-02-07 10:33:21 +00001180 // According to the blocks spec, the capture of a variable from
1181 // the stack requires a const copy constructor. This is not true
1182 // of the copy/move done to move a __block variable to the heap.
1183 type.addConst();
1184
1185 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1186 ExprResult result =
1187 S.PerformCopyInitialization(
1188 InitializedEntity::InitializeBlock(var->getLocation(),
1189 type, false),
1190 loc, S.Owned(declRef));
1191
1192 // Build a full-expression copy expression if initialization
1193 // succeeded and used a non-trivial constructor. Recover from
1194 // errors by pretending that the copy isn't necessary.
1195 if (!result.isInvalid() &&
1196 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1197 result = S.MaybeCreateExprWithCleanups(result);
1198 copyExpr = result.take();
1199 }
1200 }
1201
1202 // We're currently at the declarer; go back to the closure.
1203 functionScopesIndex++;
1204 BlockScopeInfo *blockScope =
1205 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1206
1207 // Build a valid capture in this scope.
1208 blockScope->Captures.push_back(
1209 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1210 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1211
1212 // Propagate that to inner captures if necessary.
1213 return propagateCapture(S, functionScopesIndex,
1214 blockScope->Captures.back());
1215}
1216
1217static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1218 const DeclarationNameInfo &NameInfo,
1219 bool byRef) {
1220 assert(isa<VarDecl>(vd) && "capturing non-variable");
1221
1222 VarDecl *var = cast<VarDecl>(vd);
1223 assert(var->hasLocalStorage() && "capturing non-local");
1224 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1225
1226 QualType exprType = var->getType().getNonReferenceType();
1227
1228 BlockDeclRefExpr *BDRE;
1229 if (!byRef) {
1230 // The variable will be bound by copy; make it const within the
1231 // closure, but record that this was done in the expression.
1232 bool constAdded = !exprType.isConstQualified();
1233 exprType.addConst();
1234
1235 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1236 NameInfo.getLoc(), false,
1237 constAdded);
1238 } else {
1239 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1240 NameInfo.getLoc(), true);
1241 }
1242
1243 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001244}
Chris Lattner639e2d32008-10-20 05:16:36 +00001245
John McCall60d7b3a2010-08-24 06:29:42 +00001246ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001247Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001248 SourceLocation Loc,
1249 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001250 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001251 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001252}
1253
John McCall76a40212011-02-09 01:13:10 +00001254/// BuildDeclRefExpr - Build an expression that references a
1255/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001256ExprResult
John McCall76a40212011-02-09 01:13:10 +00001257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001258 const DeclarationNameInfo &NameInfo,
1259 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001260 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John McCall7eb0a9e2010-11-24 05:12:34 +00001262 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001263 SS? SS->getWithLocInContext(Context)
1264 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001265 D, NameInfo, Ty, VK);
1266
1267 // Just in case we're building an illegal pointer-to-member.
1268 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1269 E->setObjectKind(OK_BitField);
1270
1271 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001272}
1273
John McCalldfa1edb2010-11-23 20:48:44 +00001274static ExprResult
1275BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1276 const CXXScopeSpec &SS, FieldDecl *Field,
1277 DeclAccessPair FoundDecl,
1278 const DeclarationNameInfo &MemberNameInfo);
1279
John McCall60d7b3a2010-08-24 06:29:42 +00001280ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001281Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1282 SourceLocation loc,
1283 IndirectFieldDecl *indirectField,
1284 Expr *baseObjectExpr,
1285 SourceLocation opLoc) {
1286 // First, build the expression that refers to the base object.
1287
1288 bool baseObjectIsPointer = false;
1289 Qualifiers baseQuals;
1290
1291 // Case 1: the base of the indirect field is not a field.
1292 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001293 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001294 if (baseVariable) {
1295 assert(baseVariable->getType()->isRecordType());
1296
1297 // In principle we could have a member access expression that
1298 // accesses an anonymous struct/union that's a static member of
1299 // the base object's class. However, under the current standard,
1300 // static data members cannot be anonymous structs or unions.
1301 // Supporting this is as easy as building a MemberExpr here.
1302 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1303
1304 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1305
1306 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001307 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001308 if (result.isInvalid()) return ExprError();
1309
1310 baseObjectExpr = result.take();
1311 baseObjectIsPointer = false;
1312 baseQuals = baseObjectExpr->getType().getQualifiers();
1313
1314 // Case 2: the base of the indirect field is a field and the user
1315 // wrote a member expression.
1316 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001317 // The caller provided the base object expression. Determine
1318 // whether its a pointer and whether it adds any qualifiers to the
1319 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001320 QualType objectType = baseObjectExpr->getType();
1321
1322 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1323 baseObjectIsPointer = true;
1324 objectType = ptr->getPointeeType();
1325 } else {
1326 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001327 }
John McCall5808ce42011-02-03 08:15:49 +00001328 baseQuals = objectType.getQualifiers();
1329
1330 // Case 3: the base of the indirect field is a field and we should
1331 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001332 } else {
1333 // We've found a member of an anonymous struct/union that is
1334 // inside a non-anonymous struct/union, so in a well-formed
1335 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001336 CXXMethodDecl *method = tryCaptureCXXThis();
1337 if (!method) {
1338 Diag(loc, diag::err_invalid_member_use_in_static_method)
1339 << indirectField->getDeclName();
1340 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001341 }
1342
John McCall5808ce42011-02-03 08:15:49 +00001343 // Our base object expression is "this".
1344 baseObjectExpr =
1345 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1346 /*isImplicit=*/ true);
1347 baseObjectIsPointer = true;
1348 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001349 }
1350
1351 // Build the implicit member references to the field of the
1352 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001353 Expr *result = baseObjectExpr;
1354 IndirectFieldDecl::chain_iterator
1355 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001356
John McCall5808ce42011-02-03 08:15:49 +00001357 // Build the first member access in the chain with full information.
1358 if (!baseVariable) {
1359 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001360
John McCall5808ce42011-02-03 08:15:49 +00001361 // FIXME: use the real found-decl info!
1362 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001363
John McCall5808ce42011-02-03 08:15:49 +00001364 // Make a nameInfo that properly uses the anonymous name.
1365 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001366
John McCall5808ce42011-02-03 08:15:49 +00001367 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001368 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001369 memberNameInfo).take();
1370 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001371
John McCall5808ce42011-02-03 08:15:49 +00001372 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001373 }
1374
John McCall5808ce42011-02-03 08:15:49 +00001375 // In all cases, we should now skip the first declaration in the chain.
1376 ++FI;
1377
Douglas Gregorf5848322011-02-18 02:44:58 +00001378 while (FI != FEnd) {
1379 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001380
1381 // FIXME: these are somewhat meaningless
1382 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1383 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001384
1385 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001386 (FI == FEnd? SS : EmptySS), field,
1387 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001388 .take();
1389 }
1390
1391 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001392}
1393
Abramo Bagnara25777432010-08-11 22:01:17 +00001394/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001395/// possibly a list of template arguments.
1396///
1397/// If this produces template arguments, it is permitted to call
1398/// DecomposeTemplateName.
1399///
1400/// This actually loses a lot of source location information for
1401/// non-standard name kinds; we should consider preserving that in
1402/// some way.
1403static void DecomposeUnqualifiedId(Sema &SemaRef,
1404 const UnqualifiedId &Id,
1405 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001406 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001407 const TemplateArgumentListInfo *&TemplateArgs) {
1408 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1409 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1410 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1411
1412 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1413 Id.TemplateId->getTemplateArgs(),
1414 Id.TemplateId->NumArgs);
1415 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1416 TemplateArgsPtr.release();
1417
John McCall2b5289b2010-08-23 07:28:44 +00001418 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001419 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1420 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001421 TemplateArgs = &Buffer;
1422 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001423 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001424 TemplateArgs = 0;
1425 }
1426}
1427
John McCallaa81e162009-12-01 22:10:20 +00001428/// Determines if the given class is provably not derived from all of
1429/// the prospective base classes.
1430static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1431 CXXRecordDecl *Record,
1432 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001433 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001434 return false;
1435
Douglas Gregor952b0172010-02-11 01:04:33 +00001436 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001437 if (!RD) return false;
1438 Record = cast<CXXRecordDecl>(RD);
1439
John McCallaa81e162009-12-01 22:10:20 +00001440 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1441 E = Record->bases_end(); I != E; ++I) {
1442 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1443 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1444 if (!BaseRT) return false;
1445
1446 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001447 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1448 return false;
1449 }
1450
1451 return true;
1452}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001453
John McCallaa81e162009-12-01 22:10:20 +00001454enum IMAKind {
1455 /// The reference is definitely not an instance member access.
1456 IMA_Static,
1457
1458 /// The reference may be an implicit instance member access.
1459 IMA_Mixed,
1460
1461 /// The reference may be to an instance member, but it is invalid if
1462 /// so, because the context is not an instance method.
1463 IMA_Mixed_StaticContext,
1464
1465 /// The reference may be to an instance member, but it is invalid if
1466 /// so, because the context is from an unrelated class.
1467 IMA_Mixed_Unrelated,
1468
1469 /// The reference is definitely an implicit instance member access.
1470 IMA_Instance,
1471
1472 /// The reference may be to an unresolved using declaration.
1473 IMA_Unresolved,
1474
1475 /// The reference may be to an unresolved using declaration and the
1476 /// context is not an instance method.
1477 IMA_Unresolved_StaticContext,
1478
John McCallaa81e162009-12-01 22:10:20 +00001479 /// All possible referrents are instance members and the current
1480 /// context is not an instance method.
1481 IMA_Error_StaticContext,
1482
1483 /// All possible referrents are instance members of an unrelated
1484 /// class.
1485 IMA_Error_Unrelated
1486};
1487
1488/// The given lookup names class member(s) and is not being used for
1489/// an address-of-member expression. Classify the type of access
1490/// according to whether it's possible that this reference names an
1491/// instance member. This is best-effort; it is okay to
1492/// conservatively answer "yes", in which case some errors will simply
1493/// not be caught until template-instantiation.
1494static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1495 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001496 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001497
John McCallea1471e2010-05-20 01:18:31 +00001498 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001499 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001500 (!isa<CXXMethodDecl>(DC) ||
1501 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001502
1503 if (R.isUnresolvableResult())
1504 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1505
1506 // Collect all the declaring classes of instance members we find.
1507 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001508 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001509 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001511 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001512
John McCall161755a2010-04-06 21:38:20 +00001513 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001514 if (dyn_cast<FieldDecl>(D))
1515 hasField = true;
1516
John McCallaa81e162009-12-01 22:10:20 +00001517 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001518 Classes.insert(R->getCanonicalDecl());
1519 }
1520 else
1521 hasNonInstance = true;
1522 }
1523
1524 // If we didn't find any instance members, it can't be an implicit
1525 // member reference.
1526 if (Classes.empty())
1527 return IMA_Static;
1528
1529 // If the current context is not an instance method, it can't be
1530 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001531 if (isStaticContext) {
1532 if (hasNonInstance)
1533 return IMA_Mixed_StaticContext;
1534
1535 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1536 // C++0x [expr.prim.general]p10:
1537 // An id-expression that denotes a non-static data member or non-static
1538 // member function of a class can only be used:
1539 // (...)
1540 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1541 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1542 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1543 if (isUnevaluatedExpression)
1544 return IMA_Mixed_StaticContext;
1545 }
1546
1547 return IMA_Error_StaticContext;
1548 }
John McCallaa81e162009-12-01 22:10:20 +00001549
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001550 CXXRecordDecl *
1551 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1552
1553 // [class.mfct.non-static]p3:
1554 // ...is used in the body of a non-static member function of class X,
1555 // if name lookup (3.4.1) resolves the name in the id-expression to a
1556 // non-static non-type member of some class C [...]
1557 // ...if C is not X or a base class of X, the class member access expression
1558 // is ill-formed.
1559 if (R.getNamingClass() &&
1560 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1561 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1562 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1563
John McCallaa81e162009-12-01 22:10:20 +00001564 // If we can prove that the current context is unrelated to all the
1565 // declaring classes, it can't be an implicit member reference (in
1566 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001567 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001568 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1569
1570 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1571}
1572
1573/// Diagnose a reference to a field with no object available.
1574static void DiagnoseInstanceReference(Sema &SemaRef,
1575 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001576 NamedDecl *rep,
1577 const DeclarationNameInfo &nameInfo) {
1578 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001579 SourceRange Range(Loc);
1580 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1581
John McCall5808ce42011-02-03 08:15:49 +00001582 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001583 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1584 if (MD->isStatic()) {
1585 // "invalid use of member 'x' in static member function"
1586 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001587 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001588 return;
1589 }
1590 }
1591
1592 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001593 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001594 return;
1595 }
1596
1597 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001598}
1599
John McCall578b69b2009-12-16 08:11:27 +00001600/// Diagnose an empty lookup.
1601///
1602/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001603bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1604 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001605 DeclarationName Name = R.getLookupName();
1606
John McCall578b69b2009-12-16 08:11:27 +00001607 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001608 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001609 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1610 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001611 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001612 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001613 diagnostic_suggest = diag::err_undeclared_use_suggest;
1614 }
John McCall578b69b2009-12-16 08:11:27 +00001615
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001616 // If the original lookup was an unqualified lookup, fake an
1617 // unqualified lookup. This is useful when (for example) the
1618 // original lookup would not have found something because it was a
1619 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001620 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001621 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001622 if (isa<CXXRecordDecl>(DC)) {
1623 LookupQualifiedName(R, DC);
1624
1625 if (!R.empty()) {
1626 // Don't give errors about ambiguities in this lookup.
1627 R.suppressDiagnostics();
1628
1629 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1630 bool isInstance = CurMethod &&
1631 CurMethod->isInstance() &&
1632 DC == CurMethod->getParent();
1633
1634 // Give a code modification hint to insert 'this->'.
1635 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1636 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001637 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001638 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1639 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001640 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001641 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001642 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001643 Diag(R.getNameLoc(), diagnostic) << Name
1644 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1645 QualType DepThisType = DepMethod->getThisType(Context);
1646 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1647 R.getNameLoc(), DepThisType, false);
1648 TemplateArgumentListInfo TList;
1649 if (ULE->hasExplicitTemplateArgs())
1650 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001651
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001652 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001653 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001654 CXXDependentScopeMemberExpr *DepExpr =
1655 CXXDependentScopeMemberExpr::Create(
1656 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001657 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001658 R.getLookupNameInfo(), &TList);
1659 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001660 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001661 // FIXME: we should be able to handle this case too. It is correct
1662 // to add this-> here. This is a workaround for PR7947.
1663 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001664 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001665 } else {
John McCall578b69b2009-12-16 08:11:27 +00001666 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001667 }
John McCall578b69b2009-12-16 08:11:27 +00001668
1669 // Do we really want to note all of these?
1670 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1671 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1672
1673 // Tell the callee to try to recover.
1674 return false;
1675 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001676
1677 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001678 }
1679 }
1680
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001681 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001682 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001683 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001684 if (!R.empty()) {
1685 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1686 if (SS.isEmpty())
1687 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1688 << FixItHint::CreateReplacement(R.getNameLoc(),
1689 R.getLookupName().getAsString());
1690 else
1691 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1692 << Name << computeDeclContext(SS, false) << R.getLookupName()
1693 << SS.getRange()
1694 << FixItHint::CreateReplacement(R.getNameLoc(),
1695 R.getLookupName().getAsString());
1696 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1697 Diag(ND->getLocation(), diag::note_previous_decl)
1698 << ND->getDeclName();
1699
1700 // Tell the callee to try to recover.
1701 return false;
1702 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001703
Douglas Gregoraaf87162010-04-14 20:04:41 +00001704 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1705 // FIXME: If we ended up with a typo for a type name or
1706 // Objective-C class name, we're in trouble because the parser
1707 // is in the wrong place to recover. Suggest the typo
1708 // correction, but don't make it a fix-it since we're not going
1709 // to recover well anyway.
1710 if (SS.isEmpty())
1711 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1712 else
1713 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1714 << Name << computeDeclContext(SS, false) << R.getLookupName()
1715 << SS.getRange();
1716
1717 // Don't try to recover; it won't work.
1718 return true;
1719 }
1720 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001721 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001722 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001723 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001724 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001725 else
Douglas Gregord203a162010-01-01 00:15:04 +00001726 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001727 << Name << computeDeclContext(SS, false) << Corrected
1728 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001729 return true;
1730 }
Douglas Gregord203a162010-01-01 00:15:04 +00001731 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001732 }
1733
1734 // Emit a special diagnostic for failed member lookups.
1735 // FIXME: computing the declaration context might fail here (?)
1736 if (!SS.isEmpty()) {
1737 Diag(R.getNameLoc(), diag::err_no_member)
1738 << Name << computeDeclContext(SS, false)
1739 << SS.getRange();
1740 return true;
1741 }
1742
John McCall578b69b2009-12-16 08:11:27 +00001743 // Give up, we can't recover.
1744 Diag(R.getNameLoc(), diagnostic) << Name;
1745 return true;
1746}
1747
Douglas Gregorca45da02010-11-02 20:36:02 +00001748ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1749 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001750 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1751 if (!IDecl)
1752 return 0;
1753 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1754 if (!ClassImpDecl)
1755 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001756 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001757 if (!property)
1758 return 0;
1759 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001760 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1761 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001762 return 0;
1763 return property;
1764}
1765
Douglas Gregorca45da02010-11-02 20:36:02 +00001766bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1767 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1768 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1769 if (!IDecl)
1770 return false;
1771 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1772 if (!ClassImpDecl)
1773 return false;
1774 if (ObjCPropertyImplDecl *PIDecl
1775 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1776 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1777 PIDecl->getPropertyIvarDecl())
1778 return false;
1779
1780 return true;
1781}
1782
Douglas Gregor312eadb2011-04-24 05:37:28 +00001783ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1784 IdentifierInfo *II,
1785 SourceLocation NameLoc) {
1786 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001787 bool LookForIvars;
1788 if (Lookup.empty())
1789 LookForIvars = true;
1790 else if (CurMeth->isClassMethod())
1791 LookForIvars = false;
1792 else
1793 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001794 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1795 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001796 if (!LookForIvars)
1797 return 0;
1798
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001799 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1800 if (!IDecl)
1801 return 0;
1802 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001803 if (!ClassImpDecl)
1804 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001805 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001806 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001807 if (!property)
1808 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001809 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001810 DynamicImplSeen =
1811 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001812 // property implementation has a designated ivar. No need to assume a new
1813 // one.
1814 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1815 return 0;
1816 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001817 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001818 QualType PropType = Context.getCanonicalType(property->getType());
1819 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001820 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001821 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001822 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001823 (Expr *)0, true);
1824 ClassImpDecl->addDecl(Ivar);
1825 IDecl->makeDeclVisibleInContext(Ivar, false);
1826 property->setPropertyIvarDecl(Ivar);
1827 return Ivar;
1828 }
1829 return 0;
1830}
1831
John McCall60d7b3a2010-08-24 06:29:42 +00001832ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001833 CXXScopeSpec &SS,
1834 UnqualifiedId &Id,
1835 bool HasTrailingLParen,
1836 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001837 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1838 "cannot be direct & operand and have a trailing lparen");
1839
1840 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001841 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001842
John McCall129e2df2009-11-30 22:42:35 +00001843 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001844
1845 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001846 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001847 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001848 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001849
Abramo Bagnara25777432010-08-11 22:01:17 +00001850 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001851 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001852 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001853
John McCallf7a1a742009-11-24 19:00:30 +00001854 // C++ [temp.dep.expr]p3:
1855 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001856 // -- an identifier that was declared with a dependent type,
1857 // (note: handled after lookup)
1858 // -- a template-id that is dependent,
1859 // (note: handled in BuildTemplateIdExpr)
1860 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001861 // -- a nested-name-specifier that contains a class-name that
1862 // names a dependent type.
1863 // Determine whether this is a member of an unknown specialization;
1864 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001865 bool DependentID = false;
1866 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1867 Name.getCXXNameType()->isDependentType()) {
1868 DependentID = true;
1869 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001870 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001871 if (RequireCompleteDeclContext(SS, DC))
1872 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001873 } else {
1874 DependentID = true;
1875 }
1876 }
1877
Chris Lattner337e5502011-02-18 01:27:55 +00001878 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001879 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001880 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001881
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001882 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001883 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001884 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001885 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001886 // Lookup the template name again to correctly establish the context in
1887 // which it was found. This is really unfortunate as we already did the
1888 // lookup to determine that it was a template name in the first place. If
1889 // this becomes a performance hit, we can work harder to preserve those
1890 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001891 bool MemberOfUnknownSpecialization;
1892 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1893 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001894
1895 if (MemberOfUnknownSpecialization ||
1896 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1897 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1898 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001899 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001900 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001901 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001903 // If the result might be in a dependent base class, this is a dependent
1904 // id-expression.
1905 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1906 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1907 TemplateArgs);
1908
John McCallf7a1a742009-11-24 19:00:30 +00001909 // If this reference is in an Objective-C method, then we need to do
1910 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001911 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001912 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001913 if (E.isInvalid())
1914 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Chris Lattner337e5502011-02-18 01:27:55 +00001916 if (Expr *Ex = E.takeAs<Expr>())
1917 return Owned(Ex);
1918
1919 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001920 if (getLangOptions().ObjCDefaultSynthProperties &&
1921 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001922 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001923 if (const ObjCPropertyDecl *Property =
1924 canSynthesizeProvisionalIvar(II)) {
1925 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1926 Diag(Property->getLocation(), diag::note_property_declare);
1927 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001928 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1929 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001930 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001931 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001932 // for further use, this must be set to false if in class method.
1933 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001934 }
Chris Lattner8a934232008-03-31 00:36:02 +00001935 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001936
John McCallf7a1a742009-11-24 19:00:30 +00001937 if (R.isAmbiguous())
1938 return ExprError();
1939
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001940 // Determine whether this name might be a candidate for
1941 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001942 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001943
John McCallf7a1a742009-11-24 19:00:30 +00001944 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001946 // in C90, extension in C99, forbidden in C++).
1947 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1948 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1949 if (D) R.addDecl(D);
1950 }
1951
1952 // If this name wasn't predeclared and if this is not a function
1953 // call, diagnose the problem.
1954 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001955 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001956 return ExprError();
1957
1958 assert(!R.empty() &&
1959 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001960
1961 // If we found an Objective-C instance variable, let
1962 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001963 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001964 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1965 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001966 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001967 assert(E.isInvalid() || E.get());
1968 return move(E);
1969 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 }
1971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
John McCallf7a1a742009-11-24 19:00:30 +00001973 // This is guaranteed from this point on.
1974 assert(!R.empty() || ADL);
1975
John McCallaa81e162009-12-01 22:10:20 +00001976 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001977 // C++ [class.mfct.non-static]p3:
1978 // When an id-expression that is not part of a class member access
1979 // syntax and not used to form a pointer to member is used in the
1980 // body of a non-static member function of class X, if name lookup
1981 // resolves the name in the id-expression to a non-static non-type
1982 // member of some class C, the id-expression is transformed into a
1983 // class member access expression using (*this) as the
1984 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001985 //
1986 // But we don't actually need to do this for '&' operands if R
1987 // resolved to a function or overloaded function set, because the
1988 // expression is ill-formed if it actually works out to be a
1989 // non-static member function:
1990 //
1991 // C++ [expr.ref]p4:
1992 // Otherwise, if E1.E2 refers to a non-static member function. . .
1993 // [t]he expression can be used only as the left-hand operand of a
1994 // member function call.
1995 //
1996 // There are other safeguards against such uses, but it's important
1997 // to get this right here so that we don't end up making a
1998 // spuriously dependent expression if we're inside a dependent
1999 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00002000 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00002001 bool MightBeImplicitMember;
2002 if (!isAddressOfOperand)
2003 MightBeImplicitMember = true;
2004 else if (!SS.isEmpty())
2005 MightBeImplicitMember = false;
2006 else if (R.isOverloadedResult())
2007 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00002008 else if (R.isUnresolvableResult())
2009 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00002010 else
Francois Pichet87c2e122010-11-21 06:08:52 +00002011 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2012 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00002013
2014 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00002015 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002016 }
2017
John McCallf7a1a742009-11-24 19:00:30 +00002018 if (TemplateArgs)
2019 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002020
John McCallf7a1a742009-11-24 19:00:30 +00002021 return BuildDeclarationNameExpr(SS, R, ADL);
2022}
2023
John McCall3b4294e2009-12-16 12:17:52 +00002024/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00002025ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00002026Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2027 LookupResult &R,
2028 const TemplateArgumentListInfo *TemplateArgs) {
2029 switch (ClassifyImplicitMemberAccess(*this, R)) {
2030 case IMA_Instance:
2031 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2032
John McCall3b4294e2009-12-16 12:17:52 +00002033 case IMA_Mixed:
2034 case IMA_Mixed_Unrelated:
2035 case IMA_Unresolved:
2036 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2037
2038 case IMA_Static:
2039 case IMA_Mixed_StaticContext:
2040 case IMA_Unresolved_StaticContext:
2041 if (TemplateArgs)
2042 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2043 return BuildDeclarationNameExpr(SS, R, false);
2044
2045 case IMA_Error_StaticContext:
2046 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00002047 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2048 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00002049 return ExprError();
2050 }
2051
2052 llvm_unreachable("unexpected instance member access kind");
2053 return ExprError();
2054}
2055
John McCall129e2df2009-11-30 22:42:35 +00002056/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2057/// declaration name, generally during template instantiation.
2058/// There's a large number of things which don't need to be done along
2059/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002060ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002061Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002062 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00002063 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002064 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00002065 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00002066
John McCall77bb1aa2010-05-01 00:40:08 +00002067 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002068 return ExprError();
2069
Abramo Bagnara25777432010-08-11 22:01:17 +00002070 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002071 LookupQualifiedName(R, DC);
2072
2073 if (R.isAmbiguous())
2074 return ExprError();
2075
2076 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002077 Diag(NameInfo.getLoc(), diag::err_no_member)
2078 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002079 return ExprError();
2080 }
2081
2082 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2083}
2084
2085/// LookupInObjCMethod - The parser has read a name in, and Sema has
2086/// detected that we're currently inside an ObjC method. Perform some
2087/// additional lookup.
2088///
2089/// Ideally, most of this would be done by lookup, but there's
2090/// actually quite a lot of extra work involved.
2091///
2092/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002093ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002094Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002095 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002096 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002097 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002098
John McCallf7a1a742009-11-24 19:00:30 +00002099 // There are two cases to handle here. 1) scoped lookup could have failed,
2100 // in which case we should look for an ivar. 2) scoped lookup could have
2101 // found a decl, but that decl is outside the current instance method (i.e.
2102 // a global variable). In these two cases, we do a lookup for an ivar with
2103 // this name, if the lookup sucedes, we replace it our current decl.
2104
2105 // If we're in a class method, we don't normally want to look for
2106 // ivars. But if we don't find anything else, and there's an
2107 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002108 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002109
2110 bool LookForIvars;
2111 if (Lookup.empty())
2112 LookForIvars = true;
2113 else if (IsClassMethod)
2114 LookForIvars = false;
2115 else
2116 LookForIvars = (Lookup.isSingleResult() &&
2117 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002118 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002119 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002120 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002121 ObjCInterfaceDecl *ClassDeclared;
2122 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2123 // Diagnose using an ivar in a class method.
2124 if (IsClassMethod)
2125 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2126 << IV->getDeclName());
2127
2128 // If we're referencing an invalid decl, just return this as a silent
2129 // error node. The error diagnostic was already emitted on the decl.
2130 if (IV->isInvalidDecl())
2131 return ExprError();
2132
2133 // Check if referencing a field with __attribute__((deprecated)).
2134 if (DiagnoseUseOfDecl(IV, Loc))
2135 return ExprError();
2136
2137 // Diagnose the use of an ivar outside of the declaring class.
2138 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2139 ClassDeclared != IFace)
2140 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2141
2142 // FIXME: This should use a new expr for a direct reference, don't
2143 // turn this into Self->ivar, just return a BareIVarExpr or something.
2144 IdentifierInfo &II = Context.Idents.get("self");
2145 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002146 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002147 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002148 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002149 SelfName, false, false);
2150 if (SelfExpr.isInvalid())
2151 return ExprError();
2152
John Wiegley429bb272011-04-08 18:41:53 +00002153 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2154 if (SelfExpr.isInvalid())
2155 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002156
John McCallf7a1a742009-11-24 19:00:30 +00002157 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002158 Expr *base = SelfExpr.take();
2159 base = base->IgnoreParenImpCasts();
2160 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2161 const NamedDecl *ND = DE->getDecl();
2162 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002163 // relax the rule such that it is allowed to have a shadow 'self'
2164 // where stand-alone ivar can be found in this 'self' object.
2165 // This is to match gcc's behavior.
2166 ObjCInterfaceDecl *selfIFace = 0;
2167 if (const ObjCObjectPointerType *OPT =
2168 base->getType()->getAsObjCInterfacePointerType())
2169 selfIFace = OPT->getInterfaceDecl();
2170 if (!selfIFace ||
2171 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002172 Diag(Loc, diag::error_implicit_ivar_access)
2173 << IV->getDeclName();
2174 Diag(ND->getLocation(), diag::note_declared_at);
2175 return ExprError();
2176 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002177 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002178 }
John McCallf7a1a742009-11-24 19:00:30 +00002179 return Owned(new (Context)
2180 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002181 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002182 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002183 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002184 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002185 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002186 ObjCInterfaceDecl *ClassDeclared;
2187 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2188 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2189 IFace == ClassDeclared)
2190 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2191 }
2192 }
2193
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002194 if (Lookup.empty() && II && AllowBuiltinCreation) {
2195 // FIXME. Consolidate this with similar code in LookupName.
2196 if (unsigned BuiltinID = II->getBuiltinID()) {
2197 if (!(getLangOptions().CPlusPlus &&
2198 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2199 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2200 S, Lookup.isForRedeclaration(),
2201 Lookup.getNameLoc());
2202 if (D) Lookup.addDecl(D);
2203 }
2204 }
2205 }
John McCallf7a1a742009-11-24 19:00:30 +00002206 // Sentinel value saying that we didn't do anything special.
2207 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002208}
John McCallba135432009-11-21 08:51:07 +00002209
John McCall6bb80172010-03-30 21:47:33 +00002210/// \brief Cast a base object to a member's actual type.
2211///
2212/// Logically this happens in three phases:
2213///
2214/// * First we cast from the base type to the naming class.
2215/// The naming class is the class into which we were looking
2216/// when we found the member; it's the qualifier type if a
2217/// qualifier was provided, and otherwise it's the base type.
2218///
2219/// * Next we cast from the naming class to the declaring class.
2220/// If the member we found was brought into a class's scope by
2221/// a using declaration, this is that class; otherwise it's
2222/// the class declaring the member.
2223///
2224/// * Finally we cast from the declaring class to the "true"
2225/// declaring class of the member. This conversion does not
2226/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002227ExprResult
2228Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002229 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002230 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002231 NamedDecl *Member) {
2232 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2233 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002234 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002235
Douglas Gregor5fccd362010-03-03 23:55:11 +00002236 QualType DestRecordType;
2237 QualType DestType;
2238 QualType FromRecordType;
2239 QualType FromType = From->getType();
2240 bool PointerConversions = false;
2241 if (isa<FieldDecl>(Member)) {
2242 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002243
Douglas Gregor5fccd362010-03-03 23:55:11 +00002244 if (FromType->getAs<PointerType>()) {
2245 DestType = Context.getPointerType(DestRecordType);
2246 FromRecordType = FromType->getPointeeType();
2247 PointerConversions = true;
2248 } else {
2249 DestType = DestRecordType;
2250 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002251 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002252 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2253 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002254 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002255
Douglas Gregor5fccd362010-03-03 23:55:11 +00002256 DestType = Method->getThisType(Context);
2257 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002258
Douglas Gregor5fccd362010-03-03 23:55:11 +00002259 if (FromType->getAs<PointerType>()) {
2260 FromRecordType = FromType->getPointeeType();
2261 PointerConversions = true;
2262 } else {
2263 FromRecordType = FromType;
2264 DestType = DestRecordType;
2265 }
2266 } else {
2267 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002268 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002270
Douglas Gregor5fccd362010-03-03 23:55:11 +00002271 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002272 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002273
Douglas Gregor5fccd362010-03-03 23:55:11 +00002274 // If the unqualified types are the same, no conversion is necessary.
2275 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002276 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002277
John McCall6bb80172010-03-30 21:47:33 +00002278 SourceRange FromRange = From->getSourceRange();
2279 SourceLocation FromLoc = FromRange.getBegin();
2280
John McCall5baba9d2010-08-25 10:28:54 +00002281 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002282
Douglas Gregor5fccd362010-03-03 23:55:11 +00002283 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002284 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002285 // class name.
2286 //
2287 // If the member was a qualified name and the qualified referred to a
2288 // specific base subobject type, we'll cast to that intermediate type
2289 // first and then to the object in which the member is declared. That allows
2290 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2291 //
2292 // class Base { public: int x; };
2293 // class Derived1 : public Base { };
2294 // class Derived2 : public Base { };
2295 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2296 //
2297 // void VeryDerived::f() {
2298 // x = 17; // error: ambiguous base subobjects
2299 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2300 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002301 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002302 QualType QType = QualType(Qualifier->getAsType(), 0);
2303 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2304 assert(QType->isRecordType() && "lookup done with non-record type");
2305
2306 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2307
2308 // In C++98, the qualifier type doesn't actually have to be a base
2309 // type of the object type, in which case we just ignore it.
2310 // Otherwise build the appropriate casts.
2311 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002312 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002313 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002314 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002315 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002316
Douglas Gregor5fccd362010-03-03 23:55:11 +00002317 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002318 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002319 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2320 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002321
2322 FromType = QType;
2323 FromRecordType = QRecordType;
2324
2325 // If the qualifier type was the same as the destination type,
2326 // we're done.
2327 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002328 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002329 }
2330 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002331
John McCall6bb80172010-03-30 21:47:33 +00002332 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002333
John McCall6bb80172010-03-30 21:47:33 +00002334 // If we actually found the member through a using declaration, cast
2335 // down to the using declaration's type.
2336 //
2337 // Pointer equality is fine here because only one declaration of a
2338 // class ever has member declarations.
2339 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2340 assert(isa<UsingShadowDecl>(FoundDecl));
2341 QualType URecordType = Context.getTypeDeclType(
2342 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2343
2344 // We only need to do this if the naming-class to declaring-class
2345 // conversion is non-trivial.
2346 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2347 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002348 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002349 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002350 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002351 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002352
John McCall6bb80172010-03-30 21:47:33 +00002353 QualType UType = URecordType;
2354 if (PointerConversions)
2355 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002356 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2357 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002358 FromType = UType;
2359 FromRecordType = URecordType;
2360 }
2361
2362 // We don't do access control for the conversion from the
2363 // declaring class to the true declaring class.
2364 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002365 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002366
John McCallf871d0c2010-08-07 06:22:56 +00002367 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002368 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2369 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002370 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002371 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002372
John Wiegley429bb272011-04-08 18:41:53 +00002373 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2374 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002375}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002376
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002377/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002378static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002379 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002380 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002381 const DeclarationNameInfo &MemberNameInfo,
2382 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002383 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002384 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002385 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002386 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002387 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002388}
2389
John McCalldfa1edb2010-11-23 20:48:44 +00002390static ExprResult
2391BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2392 const CXXScopeSpec &SS, FieldDecl *Field,
2393 DeclAccessPair FoundDecl,
2394 const DeclarationNameInfo &MemberNameInfo) {
2395 // x.a is an l-value if 'a' has a reference type. Otherwise:
2396 // x.a is an l-value/x-value/pr-value if the base is (and note
2397 // that *x is always an l-value), except that if the base isn't
2398 // an ordinary object then we must have an rvalue.
2399 ExprValueKind VK = VK_LValue;
2400 ExprObjectKind OK = OK_Ordinary;
2401 if (!IsArrow) {
2402 if (BaseExpr->getObjectKind() == OK_Ordinary)
2403 VK = BaseExpr->getValueKind();
2404 else
2405 VK = VK_RValue;
2406 }
2407 if (VK != VK_RValue && Field->isBitField())
2408 OK = OK_BitField;
2409
2410 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2411 QualType MemberType = Field->getType();
2412 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2413 MemberType = Ref->getPointeeType();
2414 VK = VK_LValue;
2415 } else {
2416 QualType BaseType = BaseExpr->getType();
2417 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2418
2419 Qualifiers BaseQuals = BaseType.getQualifiers();
2420
2421 // GC attributes are never picked up by members.
2422 BaseQuals.removeObjCGCAttr();
2423
2424 // CVR attributes from the base are picked up by members,
2425 // except that 'mutable' members don't pick up 'const'.
2426 if (Field->isMutable()) BaseQuals.removeConst();
2427
2428 Qualifiers MemberQuals
2429 = S.Context.getCanonicalType(MemberType).getQualifiers();
2430
2431 // TR 18037 does not allow fields to be declared with address spaces.
2432 assert(!MemberQuals.hasAddressSpace());
2433
2434 Qualifiers Combined = BaseQuals + MemberQuals;
2435 if (Combined != MemberQuals)
2436 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2437 }
2438
2439 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002440 ExprResult Base =
2441 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2442 FoundDecl, Field);
2443 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002444 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002445 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002446 Field, FoundDecl, MemberNameInfo,
2447 MemberType, VK, OK));
2448}
2449
John McCallaa81e162009-12-01 22:10:20 +00002450/// Builds an implicit member access expression. The current context
2451/// is known to be an instance method, and the given unqualified lookup
2452/// set is known to contain only instance members, at least one of which
2453/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002454ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002455Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2456 LookupResult &R,
2457 const TemplateArgumentListInfo *TemplateArgs,
2458 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002459 assert(!R.empty() && !R.isAmbiguous());
2460
John McCall5808ce42011-02-03 08:15:49 +00002461 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002462
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002463 // We may have found a field within an anonymous union or struct
2464 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002465 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002466 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002467 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002468
John McCall5808ce42011-02-03 08:15:49 +00002469 // If this is known to be an instance access, go ahead and build an
2470 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002471 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002472 CXXMethodDecl *method = tryCaptureCXXThis();
2473 assert(method && "didn't correctly pre-flight capture of 'this'");
2474
2475 QualType thisType = method->getThisType(Context);
2476 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002477 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002478 SourceLocation Loc = R.getNameLoc();
2479 if (SS.getRange().isValid())
2480 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002481 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002482 }
2483
John McCall5808ce42011-02-03 08:15:49 +00002484 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002485 /*OpLoc*/ SourceLocation(),
2486 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002487 SS,
2488 /*FirstQualifierInScope*/ 0,
2489 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002490}
2491
John McCallf7a1a742009-11-24 19:00:30 +00002492bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002493 const LookupResult &R,
2494 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002495 // Only when used directly as the postfix-expression of a call.
2496 if (!HasTrailingLParen)
2497 return false;
2498
2499 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002500 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002501 return false;
2502
2503 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002504 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002505 return false;
2506
2507 // Turn off ADL when we find certain kinds of declarations during
2508 // normal lookup:
2509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2510 NamedDecl *D = *I;
2511
2512 // C++0x [basic.lookup.argdep]p3:
2513 // -- a declaration of a class member
2514 // Since using decls preserve this property, we check this on the
2515 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002516 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002517 return false;
2518
2519 // C++0x [basic.lookup.argdep]p3:
2520 // -- a block-scope function declaration that is not a
2521 // using-declaration
2522 // NOTE: we also trigger this for function templates (in fact, we
2523 // don't check the decl type at all, since all other decl types
2524 // turn off ADL anyway).
2525 if (isa<UsingShadowDecl>(D))
2526 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2527 else if (D->getDeclContext()->isFunctionOrMethod())
2528 return false;
2529
2530 // C++0x [basic.lookup.argdep]p3:
2531 // -- a declaration that is neither a function or a function
2532 // template
2533 // And also for builtin functions.
2534 if (isa<FunctionDecl>(D)) {
2535 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2536
2537 // But also builtin functions.
2538 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2539 return false;
2540 } else if (!isa<FunctionTemplateDecl>(D))
2541 return false;
2542 }
2543
2544 return true;
2545}
2546
2547
John McCallba135432009-11-21 08:51:07 +00002548/// Diagnoses obvious problems with the use of the given declaration
2549/// as an expression. This is only actually called for lookups that
2550/// were not overloaded, and it doesn't promise that the declaration
2551/// will in fact be used.
2552static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002553 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002554 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2555 return true;
2556 }
2557
2558 if (isa<ObjCInterfaceDecl>(D)) {
2559 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2560 return true;
2561 }
2562
2563 if (isa<NamespaceDecl>(D)) {
2564 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2565 return true;
2566 }
2567
2568 return false;
2569}
2570
John McCall60d7b3a2010-08-24 06:29:42 +00002571ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002572Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002573 LookupResult &R,
2574 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002575 // If this is a single, fully-resolved result and we don't need ADL,
2576 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002577 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002578 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2579 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002580
2581 // We only need to check the declaration if there's exactly one
2582 // result, because in the overloaded case the results can only be
2583 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002584 if (R.isSingleResult() &&
2585 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002586 return ExprError();
2587
John McCallc373d482010-01-27 01:50:18 +00002588 // Otherwise, just build an unresolved lookup expression. Suppress
2589 // any lookup-related diagnostics; we'll hash these out later, when
2590 // we've picked a target.
2591 R.suppressDiagnostics();
2592
John McCallba135432009-11-21 08:51:07 +00002593 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002594 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002595 SS.getWithLocInContext(Context),
2596 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002597 NeedsADL, R.isOverloadedResult(),
2598 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002599
2600 return Owned(ULE);
2601}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002602
John McCallba135432009-11-21 08:51:07 +00002603/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002604ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002605Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002606 const DeclarationNameInfo &NameInfo,
2607 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002608 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002609 assert(!isa<FunctionTemplateDecl>(D) &&
2610 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002611
Abramo Bagnara25777432010-08-11 22:01:17 +00002612 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002613 if (CheckDeclInExpr(*this, Loc, D))
2614 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002615
Douglas Gregor9af2f522009-12-01 16:58:18 +00002616 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2617 // Specifically diagnose references to class templates that are missing
2618 // a template argument list.
2619 Diag(Loc, diag::err_template_decl_ref)
2620 << Template << SS.getRange();
2621 Diag(Template->getLocation(), diag::note_template_decl_here);
2622 return ExprError();
2623 }
2624
2625 // Make sure that we're referring to a value.
2626 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2627 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002628 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002629 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002630 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002631 return ExprError();
2632 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002633
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002634 // Check whether this declaration can be used. Note that we suppress
2635 // this check when we're going to perform argument-dependent lookup
2636 // on this function name, because this might not be the function
2637 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002638 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002639 return ExprError();
2640
Steve Naroffdd972f22008-09-05 22:11:13 +00002641 // Only create DeclRefExpr's for valid Decl's.
2642 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002643 return ExprError();
2644
John McCall5808ce42011-02-03 08:15:49 +00002645 // Handle members of anonymous structs and unions. If we got here,
2646 // and the reference is to a class member indirect field, then this
2647 // must be the subject of a pointer-to-member expression.
2648 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2649 if (!indirectField->isCXXClassMember())
2650 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2651 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002652
Chris Lattner639e2d32008-10-20 05:16:36 +00002653 // If the identifier reference is inside a block, and it refers to a value
2654 // that is outside the block, create a BlockDeclRefExpr instead of a
2655 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2656 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002657 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002658 // We do not do this for things like enum constants, global variables, etc,
2659 // as they do not get snapshotted.
2660 //
John McCall6b5a61b2011-02-07 10:33:21 +00002661 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002662 case CR_Error:
2663 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002664
John McCall469a1eb2011-02-02 13:00:07 +00002665 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002666 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2667 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2668
2669 case CR_CaptureByRef:
2670 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2671 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002672
2673 case CR_NoCapture: {
2674 // If this reference is not in a block or if the referenced
2675 // variable is within the block, create a normal DeclRefExpr.
2676
2677 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002678 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002679
2680 switch (D->getKind()) {
2681 // Ignore all the non-ValueDecl kinds.
2682#define ABSTRACT_DECL(kind)
2683#define VALUE(type, base)
2684#define DECL(type, base) \
2685 case Decl::type:
2686#include "clang/AST/DeclNodes.inc"
2687 llvm_unreachable("invalid value decl kind");
2688 return ExprError();
2689
2690 // These shouldn't make it here.
2691 case Decl::ObjCAtDefsField:
2692 case Decl::ObjCIvar:
2693 llvm_unreachable("forming non-member reference to ivar?");
2694 return ExprError();
2695
2696 // Enum constants are always r-values and never references.
2697 // Unresolved using declarations are dependent.
2698 case Decl::EnumConstant:
2699 case Decl::UnresolvedUsingValue:
2700 valueKind = VK_RValue;
2701 break;
2702
2703 // Fields and indirect fields that got here must be for
2704 // pointer-to-member expressions; we just call them l-values for
2705 // internal consistency, because this subexpression doesn't really
2706 // exist in the high-level semantics.
2707 case Decl::Field:
2708 case Decl::IndirectField:
2709 assert(getLangOptions().CPlusPlus &&
2710 "building reference to field in C?");
2711
2712 // These can't have reference type in well-formed programs, but
2713 // for internal consistency we do this anyway.
2714 type = type.getNonReferenceType();
2715 valueKind = VK_LValue;
2716 break;
2717
2718 // Non-type template parameters are either l-values or r-values
2719 // depending on the type.
2720 case Decl::NonTypeTemplateParm: {
2721 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2722 type = reftype->getPointeeType();
2723 valueKind = VK_LValue; // even if the parameter is an r-value reference
2724 break;
2725 }
2726
2727 // For non-references, we need to strip qualifiers just in case
2728 // the template parameter was declared as 'const int' or whatever.
2729 valueKind = VK_RValue;
2730 type = type.getUnqualifiedType();
2731 break;
2732 }
2733
2734 case Decl::Var:
2735 // In C, "extern void blah;" is valid and is an r-value.
2736 if (!getLangOptions().CPlusPlus &&
2737 !type.hasQualifiers() &&
2738 type->isVoidType()) {
2739 valueKind = VK_RValue;
2740 break;
2741 }
2742 // fallthrough
2743
2744 case Decl::ImplicitParam:
2745 case Decl::ParmVar:
2746 // These are always l-values.
2747 valueKind = VK_LValue;
2748 type = type.getNonReferenceType();
2749 break;
2750
2751 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002752 const FunctionType *fty = type->castAs<FunctionType>();
2753
2754 // If we're referring to a function with an __unknown_anytype
2755 // result type, make the entire expression __unknown_anytype.
2756 if (fty->getResultType() == Context.UnknownAnyTy) {
2757 type = Context.UnknownAnyTy;
2758 valueKind = VK_RValue;
2759 break;
2760 }
2761
John McCall76a40212011-02-09 01:13:10 +00002762 // Functions are l-values in C++.
2763 if (getLangOptions().CPlusPlus) {
2764 valueKind = VK_LValue;
2765 break;
2766 }
2767
2768 // C99 DR 316 says that, if a function type comes from a
2769 // function definition (without a prototype), that type is only
2770 // used for checking compatibility. Therefore, when referencing
2771 // the function, we pretend that we don't have the full function
2772 // type.
John McCall755d8492011-04-12 00:42:48 +00002773 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2774 isa<FunctionProtoType>(fty))
2775 type = Context.getFunctionNoProtoType(fty->getResultType(),
2776 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002777
2778 // Functions are r-values in C.
2779 valueKind = VK_RValue;
2780 break;
2781 }
2782
2783 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002784 // If we're referring to a method with an __unknown_anytype
2785 // result type, make the entire expression __unknown_anytype.
2786 // This should only be possible with a type written directly.
2787 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2788 if (proto->getResultType() == Context.UnknownAnyTy) {
2789 type = Context.UnknownAnyTy;
2790 valueKind = VK_RValue;
2791 break;
2792 }
2793
John McCall76a40212011-02-09 01:13:10 +00002794 // C++ methods are l-values if static, r-values if non-static.
2795 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2796 valueKind = VK_LValue;
2797 break;
2798 }
2799 // fallthrough
2800
2801 case Decl::CXXConversion:
2802 case Decl::CXXDestructor:
2803 case Decl::CXXConstructor:
2804 valueKind = VK_RValue;
2805 break;
2806 }
2807
2808 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2809 }
2810
John McCall469a1eb2011-02-02 13:00:07 +00002811 }
John McCallf89e55a2010-11-18 06:31:45 +00002812
John McCall6b5a61b2011-02-07 10:33:21 +00002813 llvm_unreachable("unknown capture result");
2814 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002815}
2816
John McCall755d8492011-04-12 00:42:48 +00002817ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002818 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002819
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002821 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002822 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2823 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2824 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002826
Chris Lattnerfa28b302008-01-12 08:14:25 +00002827 // Pre-defined identifiers are of type char[x], where x is the length of the
2828 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Anders Carlsson3a082d82009-09-08 18:24:21 +00002830 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002831 if (!currentDecl && getCurBlock())
2832 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002833 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002834 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002835 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002836 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002837
Anders Carlsson773f3972009-09-11 01:22:35 +00002838 QualType ResTy;
2839 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2840 ResTy = Context.DependentTy;
2841 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002842 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002843
Anders Carlsson773f3972009-09-11 01:22:35 +00002844 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002845 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002846 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2847 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002848 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002849}
2850
John McCall60d7b3a2010-08-24 06:29:42 +00002851ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002853 bool Invalid = false;
2854 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2855 if (Invalid)
2856 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002857
Benjamin Kramerddeea562010-02-27 13:44:12 +00002858 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2859 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002861 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002862
Chris Lattnere8337df2009-12-30 21:19:39 +00002863 QualType Ty;
2864 if (!getLangOptions().CPlusPlus)
2865 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2866 else if (Literal.isWide())
2867 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002868 else if (Literal.isMultiChar())
2869 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002870 else
2871 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002872
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002873 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2874 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002875 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002876}
2877
John McCall60d7b3a2010-08-24 06:29:42 +00002878ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002879 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2881 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002882 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002883 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002884 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002885 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 }
Ted Kremenek28396602009-01-13 23:19:12 +00002887
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002889 // Add padding so that NumericLiteralParser can overread by one character.
2890 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002892
Reid Spencer5f016e22007-07-11 17:01:13 +00002893 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002894 bool Invalid = false;
2895 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2896 if (Invalid)
2897 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002898
Mike Stump1eb44332009-09-09 15:08:12 +00002899 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 Tok.getLocation(), PP);
2901 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002902 return ExprError();
2903
Chris Lattner5d661452007-08-26 03:42:43 +00002904 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002905
Chris Lattner5d661452007-08-26 03:42:43 +00002906 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002907 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002908 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002909 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002910 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002911 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002912 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002913 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002914
2915 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2916
John McCall94c939d2009-12-24 09:08:04 +00002917 using llvm::APFloat;
2918 APFloat Val(Format);
2919
2920 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002921
2922 // Overflow is always an error, but underflow is only an error if
2923 // we underflowed to zero (APFloat reports denormals as underflow).
2924 if ((result & APFloat::opOverflow) ||
2925 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002926 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002927 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002928 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002929 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002930 APFloat::getLargest(Format).toString(buffer);
2931 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002932 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002933 APFloat::getSmallest(Format).toString(buffer);
2934 }
2935
2936 Diag(Tok.getLocation(), diagnostic)
2937 << Ty
2938 << llvm::StringRef(buffer.data(), buffer.size());
2939 }
2940
2941 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002942 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002943
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002944 if (Ty == Context.DoubleTy) {
2945 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002946 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002947 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2948 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002949 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002950 }
2951 }
Chris Lattner5d661452007-08-26 03:42:43 +00002952 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002953 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002954 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002955 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002956
Neil Boothb9449512007-08-29 22:00:19 +00002957 // long long is a C99 feature.
2958 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002959 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002960 Diag(Tok.getLocation(), diag::ext_longlong);
2961
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002963 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002964
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 if (Literal.GetIntegerValue(ResultVal)) {
2966 // If this value didn't fit into uintmax_t, warn and force to ull.
2967 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002968 Ty = Context.UnsignedLongLongTy;
2969 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002970 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 } else {
2972 // If this value fits into a ULL, try to figure out what else it fits into
2973 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002974
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2976 // be an unsigned int.
2977 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2978
2979 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002980 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002981 if (!Literal.isLong && !Literal.isLongLong) {
2982 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002983 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002984
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 // Does it fit in a unsigned int?
2986 if (ResultVal.isIntN(IntSize)) {
2987 // Does it fit in a signed int?
2988 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002989 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002991 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002992 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002994 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002995
Reid Spencer5f016e22007-07-11 17:01:13 +00002996 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002997 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002998 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002999
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 // Does it fit in a unsigned long?
3001 if (ResultVal.isIntN(LongSize)) {
3002 // Does it fit in a signed long?
3003 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003004 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003006 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003007 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003008 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003009 }
3010
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003012 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003013 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003014
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 // Does it fit in a unsigned long long?
3016 if (ResultVal.isIntN(LongLongSize)) {
3017 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00003018 // To be compatible with MSVC, hex integer literals ending with the
3019 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00003020 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3021 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00003022 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003024 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003025 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 }
3027 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003028
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 // If we still couldn't decide a type, we probably have something that
3030 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003031 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003033 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003034 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003036
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003037 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003038 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003040 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003042
Chris Lattner5d661452007-08-26 03:42:43 +00003043 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3044 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003045 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003046 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003047
3048 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00003049}
3050
John McCall60d7b3a2010-08-24 06:29:42 +00003051ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00003052 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003053 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003054 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003055}
3056
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003057static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3058 SourceLocation Loc,
3059 SourceRange ArgRange) {
3060 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3061 // scalar or vector data type argument..."
3062 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3063 // type (C99 6.2.5p18) or void.
3064 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3065 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3066 << T << ArgRange;
3067 return true;
3068 }
3069
3070 assert((T->isVoidType() || !T->isIncompleteType()) &&
3071 "Scalar types should always be complete");
3072 return false;
3073}
3074
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003075static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3076 SourceLocation Loc,
3077 SourceRange ArgRange,
3078 UnaryExprOrTypeTrait TraitKind) {
3079 // C99 6.5.3.4p1:
3080 if (T->isFunctionType()) {
3081 // alignof(function) is allowed as an extension.
3082 if (TraitKind == UETT_SizeOf)
3083 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3084 return false;
3085 }
3086
3087 // Allow sizeof(void)/alignof(void) as an extension.
3088 if (T->isVoidType()) {
3089 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3090 return false;
3091 }
3092
3093 return true;
3094}
3095
3096static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3097 SourceLocation Loc,
3098 SourceRange ArgRange,
3099 UnaryExprOrTypeTrait TraitKind) {
3100 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3101 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3102 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3103 << T << (TraitKind == UETT_SizeOf)
3104 << ArgRange;
3105 return true;
3106 }
3107
3108 return false;
3109}
3110
Chandler Carruth9d342d02011-05-26 08:53:10 +00003111/// \brief Check the constrains on expression operands to unary type expression
3112/// and type traits.
3113///
3114/// This is just a convenience wrapper around
3115/// Sema::CheckUnaryExprOrTypeTraitOperand.
3116bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3117 UnaryExprOrTypeTrait ExprKind) {
3118 return CheckUnaryExprOrTypeTraitOperand(Op->getType(),
3119 Op->getExprLoc(),
3120 Op->getSourceRange(),
3121 ExprKind);
3122}
3123
3124/// \brief Check the constraints on operands to unary expression and type
3125/// traits.
3126///
3127/// This will complete any types necessary, and validate the various constraints
3128/// on those operands.
3129///
Reid Spencer5f016e22007-07-11 17:01:13 +00003130/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003131/// C99 6.3.2.1p[2-4] all state:
3132/// Except when it is the operand of the sizeof operator ...
3133///
3134/// C++ [expr.sizeof]p4
3135/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3136/// standard conversions are not applied to the operand of sizeof.
3137///
3138/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003139bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3140 SourceLocation OpLoc,
3141 SourceRange ExprRange,
3142 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00003143 if (exprType->isDependentType())
3144 return false;
3145
Sebastian Redl5d484e82009-11-23 17:18:46 +00003146 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3147 // the result is the size of the referenced type."
3148 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3149 // result shall be the alignment of the referenced type."
3150 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3151 exprType = Ref->getPointeeType();
3152
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003153 if (ExprKind == UETT_VecStep)
3154 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003155
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003156 // Whitelist some types as extensions
3157 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3158 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003159 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Chris Lattner1efaa952009-04-24 00:30:45 +00003161 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003162 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003163 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003164 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003166 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3167 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003168 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Chris Lattner1efaa952009-04-24 00:30:45 +00003170 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003171}
3172
Chandler Carruth9d342d02011-05-26 08:53:10 +00003173static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003174 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003175
Mike Stump1eb44332009-09-09 15:08:12 +00003176 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003177 if (isa<DeclRefExpr>(E))
3178 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003179
3180 // Cannot know anything else if the expression is dependent.
3181 if (E->isTypeDependent())
3182 return false;
3183
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003184 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003185 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3186 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003187 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003188 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003189
3190 // Alignment of a field access is always okay, so long as it isn't a
3191 // bit-field.
3192 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003193 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003194 return false;
3195
Chandler Carruth9d342d02011-05-26 08:53:10 +00003196 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003197}
3198
Chandler Carruth9d342d02011-05-26 08:53:10 +00003199bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003200 E = E->IgnoreParens();
3201
3202 // Cannot know anything else if the expression is dependent.
3203 if (E->isTypeDependent())
3204 return false;
3205
Chandler Carruth9d342d02011-05-26 08:53:10 +00003206 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003207}
3208
Douglas Gregorba498172009-03-13 21:01:28 +00003209/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003210ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003211Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3212 SourceLocation OpLoc,
3213 UnaryExprOrTypeTrait ExprKind,
3214 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003215 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003216 return ExprError();
3217
John McCalla93c9342009-12-07 02:54:59 +00003218 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003219
Douglas Gregorba498172009-03-13 21:01:28 +00003220 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003221 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003222 return ExprError();
3223
3224 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003225 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3226 Context.getSizeType(),
3227 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003228}
3229
3230/// \brief Build a sizeof or alignof expression given an expression
3231/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003232ExprResult
Chandler Carruth9d342d02011-05-26 08:53:10 +00003233Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, UnaryExprOrTypeTrait ExprKind) {
Douglas Gregorba498172009-03-13 21:01:28 +00003234 // Verify that the operand is valid.
3235 bool isInvalid = false;
3236 if (E->isTypeDependent()) {
3237 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003238 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003239 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003240 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003241 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003242 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003243 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003244 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003245 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003246 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003247 if (PE.isInvalid()) return ExprError();
Chandler Carruth9d342d02011-05-26 08:53:10 +00003248 return CreateUnaryExprOrTypeTraitExpr(PE.take(), ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003249 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003250 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003251 }
3252
3253 if (isInvalid)
3254 return ExprError();
3255
3256 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003257 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3258 ExprKind, E, Context.getSizeType(), E->getExprLoc(),
3259 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003260}
3261
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003262/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3263/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003264/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003265ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003266Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3267 UnaryExprOrTypeTrait ExprKind, bool isType,
3268 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003269 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003270 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003271
Sebastian Redl05189992008-11-11 17:56:53 +00003272 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003273 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003274 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003275 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003276 }
Sebastian Redl05189992008-11-11 17:56:53 +00003277
Douglas Gregorba498172009-03-13 21:01:28 +00003278 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003279
3280 // Make sure the location is accurately represented in the Expr node.
3281 // FIXME: Is this really needed?
3282 assert(ArgEx->getExprLoc() != OpLoc && "Mismatched locations");
3283
3284 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003285
Douglas Gregorba498172009-03-13 21:01:28 +00003286 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003287}
3288
John Wiegley429bb272011-04-08 18:41:53 +00003289static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003290 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003291 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003292 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003293
John McCallf6a16482010-12-04 03:47:34 +00003294 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003295 if (V.get()->getObjectKind() != OK_Ordinary) {
3296 V = S.DefaultLvalueConversion(V.take());
3297 if (V.isInvalid())
3298 return QualType();
3299 }
John McCallf6a16482010-12-04 03:47:34 +00003300
Chris Lattnercc26ed72007-08-26 05:39:26 +00003301 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003302 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003303 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Chris Lattnercc26ed72007-08-26 05:39:26 +00003305 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003306 if (V.get()->getType()->isArithmeticType())
3307 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003308
John McCall2cd11fe2010-10-12 02:09:17 +00003309 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003310 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003311 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003312 if (PR.get() != V.get()) {
3313 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003314 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003315 }
3316
Chris Lattnercc26ed72007-08-26 05:39:26 +00003317 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003318 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003319 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003320 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003321}
3322
3323
Reid Spencer5f016e22007-07-11 17:01:13 +00003324
John McCall60d7b3a2010-08-24 06:29:42 +00003325ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003326Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003327 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003328 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003329 switch (Kind) {
3330 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003331 case tok::plusplus: Opc = UO_PostInc; break;
3332 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003333 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003334
John McCall9ae2f072010-08-23 23:25:46 +00003335 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003336}
3337
John McCall09431682010-11-18 19:01:18 +00003338/// Expressions of certain arbitrary types are forbidden by C from
3339/// having l-value type. These are:
3340/// - 'void', but not qualified void
3341/// - function types
3342///
3343/// The exact rule here is C99 6.3.2.1:
3344/// An lvalue is an expression with an object type or an incomplete
3345/// type other than void.
3346static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3347 return ((T->isVoidType() && !T.hasQualifiers()) ||
3348 T->isFunctionType());
3349}
3350
John McCall60d7b3a2010-08-24 06:29:42 +00003351ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003352Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3353 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003354 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003355 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003356 if (Result.isInvalid()) return ExprError();
3357 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003358
John McCall9ae2f072010-08-23 23:25:46 +00003359 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Douglas Gregor337c6b92008-11-19 17:17:41 +00003361 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003362 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003363 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003364 Context.DependentTy,
3365 VK_LValue, OK_Ordinary,
3366 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003367 }
3368
Mike Stump1eb44332009-09-09 15:08:12 +00003369 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003370 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003371 LHSExp->getType()->isEnumeralType() ||
3372 RHSExp->getType()->isRecordType() ||
3373 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003374 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003375 }
3376
John McCall9ae2f072010-08-23 23:25:46 +00003377 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003378}
3379
3380
John McCall60d7b3a2010-08-24 06:29:42 +00003381ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003382Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3383 Expr *Idx, SourceLocation RLoc) {
3384 Expr *LHSExp = Base;
3385 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003386
Chris Lattner12d9ff62007-07-16 00:14:47 +00003387 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003388 if (!LHSExp->getType()->getAs<VectorType>()) {
3389 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3390 if (Result.isInvalid())
3391 return ExprError();
3392 LHSExp = Result.take();
3393 }
3394 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3395 if (Result.isInvalid())
3396 return ExprError();
3397 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003398
Chris Lattner12d9ff62007-07-16 00:14:47 +00003399 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003400 ExprValueKind VK = VK_LValue;
3401 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003402
Reid Spencer5f016e22007-07-11 17:01:13 +00003403 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003404 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003405 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003406 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003407 Expr *BaseExpr, *IndexExpr;
3408 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003409 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3410 BaseExpr = LHSExp;
3411 IndexExpr = RHSExp;
3412 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003413 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003414 BaseExpr = LHSExp;
3415 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003416 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003417 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003418 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003419 BaseExpr = RHSExp;
3420 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003421 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003422 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003423 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003424 BaseExpr = LHSExp;
3425 IndexExpr = RHSExp;
3426 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003427 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003428 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003429 // Handle the uncommon case of "123[Ptr]".
3430 BaseExpr = RHSExp;
3431 IndexExpr = LHSExp;
3432 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003433 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003434 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003435 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003436 VK = LHSExp->getValueKind();
3437 if (VK != VK_RValue)
3438 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003439
Chris Lattner12d9ff62007-07-16 00:14:47 +00003440 // FIXME: need to deal with const...
3441 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003442 } else if (LHSTy->isArrayType()) {
3443 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003444 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003445 // wasn't promoted because of the C90 rule that doesn't
3446 // allow promoting non-lvalue arrays. Warn, then
3447 // force the promotion here.
3448 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3449 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003450 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3451 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003452 LHSTy = LHSExp->getType();
3453
3454 BaseExpr = LHSExp;
3455 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003456 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003457 } else if (RHSTy->isArrayType()) {
3458 // Same as previous, except for 123[f().a] case
3459 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3460 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003461 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3462 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003463 RHSTy = RHSExp->getType();
3464
3465 BaseExpr = RHSExp;
3466 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003467 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003468 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003469 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3470 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003472 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003473 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003474 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3475 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003476
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003477 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003478 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3479 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003480 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3481
Douglas Gregore7450f52009-03-24 19:52:54 +00003482 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003483 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3484 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003485 // incomplete types are not object types.
3486 if (ResultType->isFunctionType()) {
3487 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3488 << ResultType << BaseExpr->getSourceRange();
3489 return ExprError();
3490 }
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Abramo Bagnara46358452010-09-13 06:50:07 +00003492 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3493 // GNU extension: subscripting on pointer to void
3494 Diag(LLoc, diag::ext_gnu_void_ptr)
3495 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003496
3497 // C forbids expressions of unqualified void type from being l-values.
3498 // See IsCForbiddenLValueType.
3499 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003500 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003501 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003502 PDiag(diag::err_subscript_incomplete_type)
3503 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003504 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Chris Lattner1efaa952009-04-24 00:30:45 +00003506 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003507 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003508 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3509 << ResultType << BaseExpr->getSourceRange();
3510 return ExprError();
3511 }
Mike Stump1eb44332009-09-09 15:08:12 +00003512
John McCall09431682010-11-18 19:01:18 +00003513 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3514 !IsCForbiddenLValueType(Context, ResultType));
3515
Mike Stumpeed9cac2009-02-19 03:04:26 +00003516 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003517 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003518}
3519
John McCall09431682010-11-18 19:01:18 +00003520/// Check an ext-vector component access expression.
3521///
3522/// VK should be set in advance to the value kind of the base
3523/// expression.
3524static QualType
3525CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3526 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003527 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003528 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3529 // see FIXME there.
3530 //
3531 // FIXME: This logic can be greatly simplified by splitting it along
3532 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003533 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003534
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003535 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003536 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003537
Mike Stumpeed9cac2009-02-19 03:04:26 +00003538 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003539 // special names that indicate a subset of exactly half the elements are
3540 // to be selected.
3541 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003542
Nate Begeman353417a2009-01-18 01:47:54 +00003543 // This flag determines whether or not CompName has an 's' char prefix,
3544 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003545 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003546
John McCall09431682010-11-18 19:01:18 +00003547 bool HasRepeated = false;
3548 bool HasIndex[16] = {};
3549
3550 int Idx;
3551
Nate Begeman8a997642008-05-09 06:41:27 +00003552 // Check that we've found one of the special components, or that the component
3553 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003554 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003555 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3556 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003557 } else if (!HexSwizzle &&
3558 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3559 do {
3560 if (HasIndex[Idx]) HasRepeated = true;
3561 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003562 compStr++;
John McCall09431682010-11-18 19:01:18 +00003563 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3564 } else {
3565 if (HexSwizzle) compStr++;
3566 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3567 if (HasIndex[Idx]) HasRepeated = true;
3568 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003569 compStr++;
John McCall09431682010-11-18 19:01:18 +00003570 }
Chris Lattner88dca042007-08-02 22:33:49 +00003571 }
Nate Begeman353417a2009-01-18 01:47:54 +00003572
Mike Stumpeed9cac2009-02-19 03:04:26 +00003573 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003574 // We didn't get to the end of the string. This means the component names
3575 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003576 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003577 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003578 return QualType();
3579 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003580
Nate Begeman353417a2009-01-18 01:47:54 +00003581 // Ensure no component accessor exceeds the width of the vector type it
3582 // operates on.
3583 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003584 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003585
3586 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003587 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003588
3589 while (*compStr) {
3590 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003591 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003592 << baseType << SourceRange(CompLoc);
3593 return QualType();
3594 }
3595 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003596 }
Nate Begeman8a997642008-05-09 06:41:27 +00003597
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003598 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003599 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003600 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003601 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003602 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003603 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003604 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003605 if (HexSwizzle)
3606 CompSize--;
3607
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003608 if (CompSize == 1)
3609 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003610
John McCall09431682010-11-18 19:01:18 +00003611 if (HasRepeated) VK = VK_RValue;
3612
3613 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003614 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003615 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003616 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3617 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3618 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003619 }
3620 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003621}
3622
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003623static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003624 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003625 const Selector &Sel,
3626 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003627 if (Member)
3628 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3629 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003630 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003631 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003633 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3634 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003635 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3636 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003637 return D;
3638 }
3639 return 0;
3640}
3641
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003642static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3643 IdentifierInfo *Member,
3644 const Selector &Sel,
3645 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003646 // Check protocols on qualified interfaces.
3647 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003648 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003649 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003650 if (Member)
3651 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3652 GDecl = PD;
3653 break;
3654 }
3655 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003656 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003657 GDecl = OMD;
3658 break;
3659 }
3660 }
3661 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003662 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003663 E = QIdTy->qual_end(); I != E; ++I) {
3664 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003665 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3666 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003667 if (GDecl)
3668 return GDecl;
3669 }
3670 }
3671 return GDecl;
3672}
Chris Lattner76a642f2009-02-15 22:43:40 +00003673
John McCall60d7b3a2010-08-24 06:29:42 +00003674ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003675Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003676 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003677 const CXXScopeSpec &SS,
3678 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003679 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003680 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003681 // Even in dependent contexts, try to diagnose base expressions with
3682 // obviously wrong types, e.g.:
3683 //
3684 // T* t;
3685 // t.f;
3686 //
3687 // In Obj-C++, however, the above expression is valid, since it could be
3688 // accessing the 'f' property if T is an Obj-C interface. The extra check
3689 // allows this, while still reporting an error if T is a struct pointer.
3690 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003691 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003692 if (PT && (!getLangOptions().ObjC1 ||
3693 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003694 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003695 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003696 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003697 return ExprError();
3698 }
3699 }
3700
Abramo Bagnara25777432010-08-11 22:01:17 +00003701 assert(BaseType->isDependentType() ||
3702 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003703 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003704
3705 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3706 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003707 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003708 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003709 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003710 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003711 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003712}
3713
3714/// We know that the given qualified member reference points only to
3715/// declarations which do not belong to the static type of the base
3716/// expression. Diagnose the problem.
3717static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3718 Expr *BaseExpr,
3719 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003720 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003721 NamedDecl *rep,
3722 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003723 // If this is an implicit member access, use a different set of
3724 // diagnostics.
3725 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003726 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003727
John McCall5808ce42011-02-03 08:15:49 +00003728 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3729 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003730}
3731
3732// Check whether the declarations we found through a nested-name
3733// specifier in a member expression are actually members of the base
3734// type. The restriction here is:
3735//
3736// C++ [expr.ref]p2:
3737// ... In these cases, the id-expression shall name a
3738// member of the class or of one of its base classes.
3739//
3740// So it's perfectly legitimate for the nested-name specifier to name
3741// an unrelated class, and for us to find an overload set including
3742// decls from classes which are not superclasses, as long as the decl
3743// we actually pick through overload resolution is from a superclass.
3744bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3745 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003746 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003747 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003748 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3749 if (!BaseRT) {
3750 // We can't check this yet because the base type is still
3751 // dependent.
3752 assert(BaseType->isDependentType());
3753 return false;
3754 }
3755 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003756
3757 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003758 // If this is an implicit member reference and we find a
3759 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003760 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003761 return false;
John McCall129e2df2009-11-30 22:42:35 +00003762
John McCallaa81e162009-12-01 22:10:20 +00003763 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003764 DeclContext *DC = (*I)->getDeclContext();
3765 while (DC->isTransparentContext())
3766 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003767
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003768 if (!DC->isRecord())
3769 continue;
3770
John McCallaa81e162009-12-01 22:10:20 +00003771 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003772 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003773
3774 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3775 return false;
3776 }
3777
John McCall5808ce42011-02-03 08:15:49 +00003778 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3779 R.getRepresentativeDecl(),
3780 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003781 return true;
3782}
3783
3784static bool
3785LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3786 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003787 SourceLocation OpLoc, CXXScopeSpec &SS,
3788 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003789 RecordDecl *RDecl = RTy->getDecl();
3790 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003791 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003792 << BaseRange))
3793 return true;
3794
John McCallad00b772010-06-16 08:42:20 +00003795 if (HasTemplateArgs) {
3796 // LookupTemplateName doesn't expect these both to exist simultaneously.
3797 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3798
3799 bool MOUS;
3800 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3801 return false;
3802 }
3803
John McCallaa81e162009-12-01 22:10:20 +00003804 DeclContext *DC = RDecl;
3805 if (SS.isSet()) {
3806 // If the member name was a qualified-id, look into the
3807 // nested-name-specifier.
3808 DC = SemaRef.computeDeclContext(SS, false);
3809
John McCall77bb1aa2010-05-01 00:40:08 +00003810 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003811 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3812 << SS.getRange() << DC;
3813 return true;
3814 }
3815
John McCallaa81e162009-12-01 22:10:20 +00003816 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003817
John McCallaa81e162009-12-01 22:10:20 +00003818 if (!isa<TypeDecl>(DC)) {
3819 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3820 << DC << SS.getRange();
3821 return true;
John McCall129e2df2009-11-30 22:42:35 +00003822 }
3823 }
3824
John McCallaa81e162009-12-01 22:10:20 +00003825 // The record definition is complete, now look up the member.
3826 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003827
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003828 if (!R.empty())
3829 return false;
3830
3831 // We didn't find anything with the given name, so try to correct
3832 // for typos.
3833 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003834 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003835 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003836 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3837 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3838 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003839 << FixItHint::CreateReplacement(R.getNameLoc(),
3840 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003841 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3842 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3843 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003844 return false;
3845 } else {
3846 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003847 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003848 }
3849
John McCall129e2df2009-11-30 22:42:35 +00003850 return false;
3851}
3852
John McCall60d7b3a2010-08-24 06:29:42 +00003853ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003854Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003855 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003856 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003857 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003858 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003859 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003860 if (BaseType->isDependentType() ||
3861 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003862 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003863 IsArrow, OpLoc,
3864 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003865 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003866
Abramo Bagnara25777432010-08-11 22:01:17 +00003867 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003868
John McCallaa81e162009-12-01 22:10:20 +00003869 // Implicit member accesses.
3870 if (!Base) {
3871 QualType RecordTy = BaseType;
3872 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3873 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3874 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003875 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003876 return ExprError();
3877
3878 // Explicit member accesses.
3879 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003880 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003881 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003882 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003883 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003884
John Wiegley429bb272011-04-08 18:41:53 +00003885 if (BaseResult.isInvalid())
3886 return ExprError();
3887 Base = BaseResult.take();
3888
John McCallaa81e162009-12-01 22:10:20 +00003889 if (Result.isInvalid()) {
3890 Owned(Base);
3891 return ExprError();
3892 }
3893
3894 if (Result.get())
3895 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003896
3897 // LookupMemberExpr can modify Base, and thus change BaseType
3898 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003899 }
3900
John McCall9ae2f072010-08-23 23:25:46 +00003901 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003902 OpLoc, IsArrow, SS, FirstQualifierInScope,
3903 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003904}
3905
John McCall60d7b3a2010-08-24 06:29:42 +00003906ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003907Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003908 SourceLocation OpLoc, bool IsArrow,
3909 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003910 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003911 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003912 const TemplateArgumentListInfo *TemplateArgs,
3913 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003914 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003915 if (IsArrow) {
3916 assert(BaseType->isPointerType());
3917 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3918 }
John McCall161755a2010-04-06 21:38:20 +00003919 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003920
Abramo Bagnara25777432010-08-11 22:01:17 +00003921 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3922 DeclarationName MemberName = MemberNameInfo.getName();
3923 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003924
3925 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003926 return ExprError();
3927
John McCall129e2df2009-11-30 22:42:35 +00003928 if (R.empty()) {
3929 // Rederive where we looked up.
3930 DeclContext *DC = (SS.isSet()
3931 ? computeDeclContext(SS, false)
3932 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003933
John McCall129e2df2009-11-30 22:42:35 +00003934 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003935 << MemberName << DC
3936 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003937 return ExprError();
3938 }
3939
John McCallc2233c52010-01-15 08:34:02 +00003940 // Diagnose lookups that find only declarations from a non-base
3941 // type. This is possible for either qualified lookups (which may
3942 // have been qualified with an unrelated type) or implicit member
3943 // expressions (which were found with unqualified lookup and thus
3944 // may have come from an enclosing scope). Note that it's okay for
3945 // lookup to find declarations from a non-base type as long as those
3946 // aren't the ones picked by overload resolution.
3947 if ((SS.isSet() || !BaseExpr ||
3948 (isa<CXXThisExpr>(BaseExpr) &&
3949 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003950 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003951 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003952 return ExprError();
3953
3954 // Construct an unresolved result if we in fact got an unresolved
3955 // result.
3956 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003957 // Suppress any lookup-related diagnostics; we'll do these when we
3958 // pick a member.
3959 R.suppressDiagnostics();
3960
John McCall129e2df2009-11-30 22:42:35 +00003961 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003962 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003963 BaseExpr, BaseExprType,
3964 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003965 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003966 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003967 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003968
3969 return Owned(MemExpr);
3970 }
3971
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003972 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003973 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003974 NamedDecl *MemberDecl = R.getFoundDecl();
3975
3976 // FIXME: diagnose the presence of template arguments now.
3977
3978 // If the decl being referenced had an error, return an error for this
3979 // sub-expr without emitting another error, in order to avoid cascading
3980 // error cases.
3981 if (MemberDecl->isInvalidDecl())
3982 return ExprError();
3983
John McCallaa81e162009-12-01 22:10:20 +00003984 // Handle the implicit-member-access case.
3985 if (!BaseExpr) {
3986 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003987 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003988 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003989
Douglas Gregor828a1972010-01-07 23:12:05 +00003990 SourceLocation Loc = R.getNameLoc();
3991 if (SS.getRange().isValid())
3992 Loc = SS.getRange().getBegin();
3993 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003994 }
3995
John McCall129e2df2009-11-30 22:42:35 +00003996 bool ShouldCheckUse = true;
3997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3998 // Don't diagnose the use of a virtual member function unless it's
3999 // explicitly qualified.
4000 if (MD->isVirtual() && !SS.isSet())
4001 ShouldCheckUse = false;
4002 }
4003
4004 // Check the use of this member.
4005 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4006 Owned(BaseExpr);
4007 return ExprError();
4008 }
4009
John McCallf6a16482010-12-04 03:47:34 +00004010 // Perform a property load on the base regardless of whether we
4011 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00004012 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4013 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4014 if (Result.isInvalid())
4015 return ExprError();
4016 BaseExpr = Result.take();
4017 }
John McCallf6a16482010-12-04 03:47:34 +00004018
John McCalldfa1edb2010-11-23 20:48:44 +00004019 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4020 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4021 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00004022
Francois Pichet87c2e122010-11-21 06:08:52 +00004023 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4024 // We may have found a field within an anonymous union or struct
4025 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00004026 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00004027 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00004028
John McCall129e2df2009-11-30 22:42:35 +00004029 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4030 MarkDeclarationReferenced(MemberLoc, Var);
4031 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004032 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004033 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00004034 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004035 }
4036
John McCallf89e55a2010-11-18 06:31:45 +00004037 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall864c0412011-04-26 20:42:42 +00004038 ExprValueKind valueKind;
4039 QualType type;
4040 if (MemberFn->isInstance()) {
4041 valueKind = VK_RValue;
4042 type = Context.BoundMemberTy;
4043 } else {
4044 valueKind = VK_LValue;
4045 type = MemberFn->getType();
4046 }
4047
John McCall129e2df2009-11-30 22:42:35 +00004048 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4049 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004050 MemberFn, FoundDecl, MemberNameInfo,
John McCall864c0412011-04-26 20:42:42 +00004051 type, valueKind, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004052 }
John McCallf89e55a2010-11-18 06:31:45 +00004053 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00004054
4055 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4056 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4057 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004058 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004059 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004060 }
4061
4062 Owned(BaseExpr);
4063
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004064 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00004065 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00004066 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004067 << MemberName << BaseType << int(IsArrow);
4068 else
4069 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4070 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00004071
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004072 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4073 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00004074 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004075 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00004076}
4077
John McCall028d3972010-12-15 16:46:44 +00004078/// Given that normal member access failed on the given expression,
4079/// and given that the expression's type involves builtin-id or
4080/// builtin-Class, decide whether substituting in the redefinition
4081/// types would be profitable. The redefinition type is whatever
4082/// this translation unit tried to typedef to id/Class; we store
4083/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00004084static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00004085 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00004086 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00004087 if (!opty) return false;
4088
4089 const ObjCObjectType *ty = opty->getObjectType();
4090
4091 QualType redef;
4092 if (ty->isObjCId()) {
4093 redef = S.Context.ObjCIdRedefinitionType;
4094 } else if (ty->isObjCClass()) {
4095 redef = S.Context.ObjCClassRedefinitionType;
4096 } else {
4097 return false;
4098 }
4099
4100 // Do the substitution as long as the redefinition type isn't just a
4101 // possibly-qualified pointer to builtin-id or builtin-Class again.
4102 opty = redef->getAs<ObjCObjectPointerType>();
4103 if (opty && !opty->getObjectType()->getInterface() != 0)
4104 return false;
4105
John Wiegley429bb272011-04-08 18:41:53 +00004106 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004107 return true;
4108}
4109
John McCall129e2df2009-11-30 22:42:35 +00004110/// Look up the given member of the given non-type-dependent
4111/// expression. This can return in one of two ways:
4112/// * If it returns a sentinel null-but-valid result, the caller will
4113/// assume that lookup was performed and the results written into
4114/// the provided structure. It will take over from there.
4115/// * Otherwise, the returned expression will be produced in place of
4116/// an ordinary member expression.
4117///
4118/// The ObjCImpDecl bit is a gross hack that will need to be properly
4119/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00004120ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00004121Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00004122 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004123 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00004124 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00004125 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Steve Naroff3cc4af82007-12-16 21:42:28 +00004127 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00004128 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004129
John Wiegley429bb272011-04-08 18:41:53 +00004130 if (IsArrow) {
4131 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4132 if (BaseExpr.isInvalid())
4133 return ExprError();
4134 }
4135
4136 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00004137 assert(!BaseType->isDependentType());
4138
4139 DeclarationName MemberName = R.getLookupName();
4140 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004141
John McCall028d3972010-12-15 16:46:44 +00004142 // For later type-checking purposes, turn arrow accesses into dot
4143 // accesses. The only access type we support that doesn't follow
4144 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4145 // and those never use arrows, so this is unaffected.
4146 if (IsArrow) {
4147 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4148 BaseType = Ptr->getPointeeType();
4149 else if (const ObjCObjectPointerType *Ptr
4150 = BaseType->getAs<ObjCObjectPointerType>())
4151 BaseType = Ptr->getPointeeType();
4152 else if (BaseType->isRecordType()) {
4153 // Recover from arrow accesses to records, e.g.:
4154 // struct MyRecord foo;
4155 // foo->bar
4156 // This is actually well-formed in C++ if MyRecord has an
4157 // overloaded operator->, but that should have been dealt with
4158 // by now.
4159 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004160 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004161 << FixItHint::CreateReplacement(OpLoc, ".");
4162 IsArrow = false;
John McCall864c0412011-04-26 20:42:42 +00004163 } else if (BaseType == Context.BoundMemberTy) {
4164 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004165 } else {
4166 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004167 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004168 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004169 }
4170 }
4171
John McCall028d3972010-12-15 16:46:44 +00004172 // Handle field access to simple records.
4173 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004174 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004175 RTy, OpLoc, SS, HasTemplateArgs))
4176 return ExprError();
4177
4178 // Returning valid-but-null is how we indicate to the caller that
4179 // the lookup result was filled in.
4180 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004181 }
John McCall129e2df2009-11-30 22:42:35 +00004182
John McCall028d3972010-12-15 16:46:44 +00004183 // Handle ivar access to Objective-C objects.
4184 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004185 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004186
4187 // There are three cases for the base type:
4188 // - builtin id (qualified or unqualified)
4189 // - builtin Class (qualified or unqualified)
4190 // - an interface
4191 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4192 if (!IDecl) {
4193 // There's an implicit 'isa' ivar on all objects.
4194 // But we only actually find it this way on objects of type 'id',
4195 // apparently.
4196 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004197 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004198 Context.getObjCClassType()));
4199
4200 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4201 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4202 ObjCImpDecl, HasTemplateArgs);
4203 goto fail;
4204 }
4205
4206 ObjCInterfaceDecl *ClassDeclared;
4207 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4208
4209 if (!IV) {
4210 // Attempt to correct for typos in ivar names.
4211 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4212 LookupMemberName);
4213 if (CorrectTypo(Res, 0, 0, IDecl, false,
4214 IsArrow ? CTC_ObjCIvarLookup
4215 : CTC_ObjCPropertyLookup) &&
4216 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4217 Diag(R.getNameLoc(),
4218 diag::err_typecheck_member_reference_ivar_suggest)
4219 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4220 << FixItHint::CreateReplacement(R.getNameLoc(),
4221 IV->getNameAsString());
4222 Diag(IV->getLocation(), diag::note_previous_decl)
4223 << IV->getDeclName();
4224 } else {
4225 Res.clear();
4226 Res.setLookupName(Member);
4227
4228 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4229 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004230 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004231 return ExprError();
4232 }
4233 }
4234
4235 // If the decl being referenced had an error, return an error for this
4236 // sub-expr without emitting another error, in order to avoid cascading
4237 // error cases.
4238 if (IV->isInvalidDecl())
4239 return ExprError();
4240
4241 // Check whether we can reference this field.
4242 if (DiagnoseUseOfDecl(IV, MemberLoc))
4243 return ExprError();
4244 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4245 IV->getAccessControl() != ObjCIvarDecl::Package) {
4246 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4247 if (ObjCMethodDecl *MD = getCurMethodDecl())
4248 ClassOfMethodDecl = MD->getClassInterface();
4249 else if (ObjCImpDecl && getCurFunctionDecl()) {
4250 // Case of a c-function declared inside an objc implementation.
4251 // FIXME: For a c-style function nested inside an objc implementation
4252 // class, there is no implementation context available, so we pass
4253 // down the context as argument to this routine. Ideally, this context
4254 // need be passed down in the AST node and somehow calculated from the
4255 // AST for a function decl.
4256 if (ObjCImplementationDecl *IMPD =
4257 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4258 ClassOfMethodDecl = IMPD->getClassInterface();
4259 else if (ObjCCategoryImplDecl* CatImplClass =
4260 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4261 ClassOfMethodDecl = CatImplClass->getClassInterface();
4262 }
4263
4264 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4265 if (ClassDeclared != IDecl ||
4266 ClassOfMethodDecl != ClassDeclared)
4267 Diag(MemberLoc, diag::error_private_ivar_access)
4268 << IV->getDeclName();
4269 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4270 // @protected
4271 Diag(MemberLoc, diag::error_protected_ivar_access)
4272 << IV->getDeclName();
4273 }
4274
4275 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004276 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004277 IsArrow));
4278 }
4279
4280 // Objective-C property access.
4281 const ObjCObjectPointerType *OPT;
4282 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4283 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004284 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4285 if (BaseExpr.isInvalid())
4286 return ExprError();
4287
4288 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004289
4290 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4291
4292 const ObjCObjectType *OT = OPT->getObjectType();
4293
4294 // id, with and without qualifiers.
4295 if (OT->isObjCId()) {
4296 // Check protocols on qualified interfaces.
4297 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4298 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4299 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4300 // Check the use of this declaration
4301 if (DiagnoseUseOfDecl(PD, MemberLoc))
4302 return ExprError();
4303
4304 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4305 VK_LValue,
4306 OK_ObjCProperty,
4307 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004308 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004309 }
4310
4311 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4312 // Check the use of this method.
4313 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4314 return ExprError();
4315 Selector SetterSel =
4316 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4317 PP.getSelectorTable(), Member);
4318 ObjCMethodDecl *SMD = 0;
4319 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4320 SetterSel, Context))
4321 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4322 QualType PType = OMD->getSendResultType();
4323
4324 ExprValueKind VK = VK_LValue;
4325 if (!getLangOptions().CPlusPlus &&
4326 IsCForbiddenLValueType(Context, PType))
4327 VK = VK_RValue;
4328 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4329
4330 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4331 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004332 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004333 }
4334 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004335 // Use of id.member can only be for a property reference. Do not
4336 // use the 'id' redefinition in this case.
4337 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004338 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4339 ObjCImpDecl, HasTemplateArgs);
4340
4341 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4342 << MemberName << BaseType);
4343 }
4344
4345 // 'Class', unqualified only.
4346 if (OT->isObjCClass()) {
4347 // Only works in a method declaration (??!).
4348 ObjCMethodDecl *MD = getCurMethodDecl();
4349 if (!MD) {
4350 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4351 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4352 ObjCImpDecl, HasTemplateArgs);
4353
4354 goto fail;
4355 }
4356
4357 // Also must look for a getter name which uses property syntax.
4358 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004359 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4360 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004361 if ((Getter = IFace->lookupClassMethod(Sel))) {
4362 // Check the use of this method.
4363 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4364 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004365 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004366 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004367 // If we found a getter then this may be a valid dot-reference, we
4368 // will look for the matching setter, in case it is needed.
4369 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004370 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4371 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004372 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4373 if (!Setter) {
4374 // If this reference is in an @implementation, also check for 'private'
4375 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004376 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004377 }
4378 // Look through local category implementations associated with the class.
4379 if (!Setter)
4380 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004381
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004382 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4383 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004384
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004385 if (Getter || Setter) {
4386 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004387
John McCall09431682010-11-18 19:01:18 +00004388 ExprValueKind VK = VK_LValue;
4389 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004390 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00004391 if (!getLangOptions().CPlusPlus &&
4392 IsCForbiddenLValueType(Context, PType))
4393 VK = VK_RValue;
4394 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004395 // Get the expression type from Setter's incoming parameter.
4396 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004397 }
4398 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4399
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004400 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004401 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4402 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004403 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004404 }
John McCall028d3972010-12-15 16:46:44 +00004405
4406 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4407 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4408 ObjCImpDecl, HasTemplateArgs);
4409
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004410 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004411 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004412 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004413
John McCall028d3972010-12-15 16:46:44 +00004414 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004415 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004416 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004417 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004418
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004419 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004420 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004421 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004422 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004423 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004424 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4425 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004426 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004427 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004428
John Wiegley429bb272011-04-08 18:41:53 +00004429 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004430 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004431 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004432
John McCall028d3972010-12-15 16:46:44 +00004433 // Adjust builtin-sel to the appropriate redefinition type if that's
4434 // not just a pointer to builtin-sel again.
4435 if (IsArrow &&
4436 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4437 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004438 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4439 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004440 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4441 ObjCImpDecl, HasTemplateArgs);
4442 }
4443
4444 // Failure cases.
4445 fail:
4446
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004447 // Recover from dot accesses to pointers, e.g.:
4448 // type *foo;
4449 // foo.bar
4450 // This is actually well-formed in two cases:
4451 // - 'type' is an Objective C type
4452 // - 'bar' is a pseudo-destructor name which happens to refer to
4453 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004454 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004455 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4456 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004457 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004458 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004459 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004460
4461 // Recurse as an -> access.
4462 IsArrow = true;
4463 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4464 ObjCImpDecl, HasTemplateArgs);
4465 }
John McCall028d3972010-12-15 16:46:44 +00004466 }
4467
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004468 // If the user is trying to apply -> or . to a function name, it's probably
4469 // because they forgot parentheses to call that function.
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004470 QualType ZeroArgCallTy;
4471 UnresolvedSet<4> Overloads;
4472 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4473 if (ZeroArgCallTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00004474 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004475 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4476 UnresolvedSet<2> PlausibleOverloads;
4477 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4478 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4479 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4480 QualType OverloadResultTy = OverloadDecl->getResultType();
4481 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4482 (IsArrow && OverloadResultTy->isPointerType() &&
4483 OverloadResultTy->getPointeeType()->isRecordType()))
4484 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004485 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004486 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004487 return ExprError();
4488 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004489 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4490 (IsArrow && ZeroArgCallTy->isPointerType() &&
4491 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4492 // At this point, we know BaseExpr looks like it's potentially callable
4493 // with 0 arguments, and that it returns something of a reasonable type,
4494 // so we can emit a fixit and carry on pretending that BaseExpr was
4495 // actually a CallExpr.
4496 SourceLocation ParenInsertionLoc =
4497 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4498 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4499 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4500 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4501 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4502 // while doing so.
4503 ExprResult NewBase =
4504 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4505 MultiExprArg(*this, 0, 0),
4506 ParenInsertionLoc.getFileLocWithOffset(1));
4507 if (NewBase.isInvalid())
4508 return ExprError();
4509 BaseExpr = NewBase;
4510 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4511 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4512 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004513 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004514 }
4515
Douglas Gregor214f31a2009-03-27 06:00:30 +00004516 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004517 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004518
Douglas Gregor214f31a2009-03-27 06:00:30 +00004519 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004520}
4521
John McCall129e2df2009-11-30 22:42:35 +00004522/// The main callback when the parser finds something like
4523/// expression . [nested-name-specifier] identifier
4524/// expression -> [nested-name-specifier] identifier
4525/// where 'identifier' encompasses a fairly broad spectrum of
4526/// possibilities, including destructor and operator references.
4527///
4528/// \param OpKind either tok::arrow or tok::period
4529/// \param HasTrailingLParen whether the next token is '(', which
4530/// is used to diagnose mis-uses of special members that can
4531/// only be called
4532/// \param ObjCImpDecl the current ObjC @implementation decl;
4533/// this is an ugly hack around the fact that ObjC @implementations
4534/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004535ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004536 SourceLocation OpLoc,
4537 tok::TokenKind OpKind,
4538 CXXScopeSpec &SS,
4539 UnqualifiedId &Id,
4540 Decl *ObjCImpDecl,
4541 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004542 if (SS.isSet() && SS.isInvalid())
4543 return ExprError();
4544
Francois Pichetdbee3412011-01-18 05:04:39 +00004545 // Warn about the explicit constructor calls Microsoft extension.
4546 if (getLangOptions().Microsoft &&
4547 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4548 Diag(Id.getSourceRange().getBegin(),
4549 diag::ext_ms_explicit_constructor_call);
4550
John McCall129e2df2009-11-30 22:42:35 +00004551 TemplateArgumentListInfo TemplateArgsBuffer;
4552
4553 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004554 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004555 const TemplateArgumentListInfo *TemplateArgs;
4556 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004557 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004558
Abramo Bagnara25777432010-08-11 22:01:17 +00004559 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004560 bool IsArrow = (OpKind == tok::arrow);
4561
4562 NamedDecl *FirstQualifierInScope
4563 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4564 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4565
4566 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004567 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004568 if (Result.isInvalid()) return ExprError();
4569 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004570
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004571 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4572 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004573 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004574 IsArrow, OpLoc,
4575 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004576 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004577 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004578 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004579 ExprResult BaseResult = Owned(Base);
4580 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004581 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004582 if (BaseResult.isInvalid())
4583 return ExprError();
4584 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004585
John McCallad00b772010-06-16 08:42:20 +00004586 if (Result.isInvalid()) {
4587 Owned(Base);
4588 return ExprError();
4589 }
John McCall129e2df2009-11-30 22:42:35 +00004590
John McCallad00b772010-06-16 08:42:20 +00004591 if (Result.get()) {
4592 // The only way a reference to a destructor can be used is to
4593 // immediately call it, which falls into this case. If the
4594 // next token is not a '(', produce a diagnostic and build the
4595 // call now.
4596 if (!HasTrailingLParen &&
4597 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004598 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004599
John McCallad00b772010-06-16 08:42:20 +00004600 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004601 }
4602
John McCall9ae2f072010-08-23 23:25:46 +00004603 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004604 OpLoc, IsArrow, SS, FirstQualifierInScope,
4605 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004606 }
4607
4608 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004609}
4610
John McCall60d7b3a2010-08-24 06:29:42 +00004611ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004612 FunctionDecl *FD,
4613 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004614 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004615 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004616 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004617 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004618 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004619 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004620 return ExprError();
4621 }
4622
4623 if (Param->hasUninstantiatedDefaultArg()) {
4624 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004625
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004626 // Instantiate the expression.
4627 MultiLevelTemplateArgumentList ArgList
4628 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004629
Nico Weber08e41a62010-11-29 18:19:25 +00004630 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004631 = ArgList.getInnermost();
4632 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4633 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004634
Nico Weber08e41a62010-11-29 18:19:25 +00004635 ExprResult Result;
4636 {
4637 // C++ [dcl.fct.default]p5:
4638 // The names in the [default argument] expression are bound, and
4639 // the semantic constraints are checked, at the point where the
4640 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004641 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004642 Result = SubstExpr(UninstExpr, ArgList);
4643 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004644 if (Result.isInvalid())
4645 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004647 // Check the expression as an initializer for the parameter.
4648 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004649 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004650 InitializationKind Kind
4651 = InitializationKind::CreateCopy(Param->getLocation(),
4652 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4653 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004654
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004655 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4656 Result = InitSeq.Perform(*this, Entity, Kind,
4657 MultiExprArg(*this, &ResultE, 1));
4658 if (Result.isInvalid())
4659 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004660
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004661 // Build the default argument expression.
4662 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4663 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004664 }
4665
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004666 // If the default expression creates temporaries, we need to
4667 // push them to the current stack of expression temporaries so they'll
4668 // be properly destroyed.
4669 // FIXME: We should really be rebuilding the default argument with new
4670 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004671 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4672 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4673 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4674 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4675 ExprTemporaries.push_back(Temporary);
4676 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004677
4678 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004679 // Just mark all of the declarations in this potentially-evaluated expression
4680 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004681 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004682 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004683}
4684
Douglas Gregor88a35142008-12-22 05:46:06 +00004685/// ConvertArgumentsForCall - Converts the arguments specified in
4686/// Args/NumArgs to the parameter types of the function FDecl with
4687/// function prototype Proto. Call is the call expression itself, and
4688/// Fn is the function expression. For a C++ member function, this
4689/// routine does not attempt to convert the object argument. Returns
4690/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004691bool
4692Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004693 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004694 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004695 Expr **Args, unsigned NumArgs,
4696 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004697 // Bail out early if calling a builtin with custom typechecking.
4698 // We don't need to do this in the
4699 if (FDecl)
4700 if (unsigned ID = FDecl->getBuiltinID())
4701 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4702 return false;
4703
Mike Stumpeed9cac2009-02-19 03:04:26 +00004704 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004705 // assignment, to the types of the corresponding parameter, ...
4706 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004707 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004708
Douglas Gregor88a35142008-12-22 05:46:06 +00004709 // If too few arguments are available (and we don't have default
4710 // arguments for the remaining parameters), don't make the call.
4711 if (NumArgs < NumArgsInProto) {
4712 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4713 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004714 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004715 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004716 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004717 }
4718
4719 // If too many are passed and not variadic, error on the extras and drop
4720 // them.
4721 if (NumArgs > NumArgsInProto) {
4722 if (!Proto->isVariadic()) {
4723 Diag(Args[NumArgsInProto]->getLocStart(),
4724 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004725 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004726 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004727 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4728 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004729
4730 // Emit the location of the prototype.
4731 if (FDecl && !FDecl->getBuiltinID())
4732 Diag(FDecl->getLocStart(),
4733 diag::note_typecheck_call_too_many_args)
4734 << FDecl;
4735
Douglas Gregor88a35142008-12-22 05:46:06 +00004736 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004737 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004738 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004739 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004740 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004741 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004742 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004743 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4744 if (Fn->getType()->isBlockPointerType())
4745 CallType = VariadicBlock; // Block
4746 else if (isa<MemberExpr>(Fn))
4747 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004748 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004749 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004750 if (Invalid)
4751 return true;
4752 unsigned TotalNumArgs = AllArgs.size();
4753 for (unsigned i = 0; i < TotalNumArgs; ++i)
4754 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004755
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004756 return false;
4757}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004758
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004759bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4760 FunctionDecl *FDecl,
4761 const FunctionProtoType *Proto,
4762 unsigned FirstProtoArg,
4763 Expr **Args, unsigned NumArgs,
4764 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004765 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004766 unsigned NumArgsInProto = Proto->getNumArgs();
4767 unsigned NumArgsToCheck = NumArgs;
4768 bool Invalid = false;
4769 if (NumArgs != NumArgsInProto)
4770 // Use default arguments for missing arguments
4771 NumArgsToCheck = NumArgsInProto;
4772 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004773 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004774 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004775 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004776
Douglas Gregor88a35142008-12-22 05:46:06 +00004777 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004778 if (ArgIx < NumArgs) {
4779 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004780
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004781 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4782 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004783 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004784 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004785 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004786
Douglas Gregora188ff22009-12-22 16:09:06 +00004787 // Pass the argument
4788 ParmVarDecl *Param = 0;
4789 if (FDecl && i < FDecl->getNumParams())
4790 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004791
Douglas Gregora188ff22009-12-22 16:09:06 +00004792 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004793 Param? InitializedEntity::InitializeParameter(Context, Param)
4794 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004795 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004796 SourceLocation(),
4797 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004798 if (ArgE.isInvalid())
4799 return true;
4800
4801 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004802 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004803 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004804
John McCall60d7b3a2010-08-24 06:29:42 +00004805 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004806 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004807 if (ArgExpr.isInvalid())
4808 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004809
Anders Carlsson56c5e332009-08-25 03:49:14 +00004810 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004811 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004812 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004813 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004814
Douglas Gregor88a35142008-12-22 05:46:06 +00004815 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004816 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004817
4818 // Assume that extern "C" functions with variadic arguments that
4819 // return __unknown_anytype aren't *really* variadic.
4820 if (Proto->getResultType() == Context.UnknownAnyTy &&
4821 FDecl && FDecl->isExternC()) {
4822 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4823 ExprResult arg;
4824 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4825 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4826 else
4827 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4828 Invalid |= arg.isInvalid();
4829 AllArgs.push_back(arg.take());
4830 }
4831
4832 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4833 } else {
4834 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4835 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4836 Invalid |= Arg.isInvalid();
4837 AllArgs.push_back(Arg.take());
4838 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004839 }
4840 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004841 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004842}
4843
John McCall755d8492011-04-12 00:42:48 +00004844/// Given a function expression of unknown-any type, try to rebuild it
4845/// to have a function type.
4846static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4847
Steve Narofff69936d2007-09-16 03:34:24 +00004848/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004849/// This provides the location of the left/right parens and a list of comma
4850/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004851ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004852Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004853 MultiExprArg args, SourceLocation RParenLoc,
4854 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004855 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004856
4857 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004858 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004859 if (Result.isInvalid()) return ExprError();
4860 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004861
John McCall9ae2f072010-08-23 23:25:46 +00004862 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Douglas Gregor88a35142008-12-22 05:46:06 +00004864 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004865 // If this is a pseudo-destructor expression, build the call immediately.
4866 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4867 if (NumArgs > 0) {
4868 // Pseudo-destructor calls should not have any arguments.
4869 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004870 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004871 SourceRange(Args[0]->getLocStart(),
4872 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004873
Douglas Gregora71d8192009-09-04 17:36:40 +00004874 NumArgs = 0;
4875 }
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Douglas Gregora71d8192009-09-04 17:36:40 +00004877 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004878 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004879 }
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Douglas Gregor17330012009-02-04 15:01:18 +00004881 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004882 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004883 // FIXME: Will need to cache the results of name lookup (including ADL) in
4884 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004885 bool Dependent = false;
4886 if (Fn->isTypeDependent())
4887 Dependent = true;
4888 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4889 Dependent = true;
4890
Peter Collingbournee08ce652011-02-09 21:07:24 +00004891 if (Dependent) {
4892 if (ExecConfig) {
4893 return Owned(new (Context) CUDAKernelCallExpr(
4894 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4895 Context.DependentTy, VK_RValue, RParenLoc));
4896 } else {
4897 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4898 Context.DependentTy, VK_RValue,
4899 RParenLoc));
4900 }
4901 }
Douglas Gregor17330012009-02-04 15:01:18 +00004902
4903 // Determine whether this is a call to an object (C++ [over.call.object]).
4904 if (Fn->getType()->isRecordType())
4905 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004906 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004907
John McCall755d8492011-04-12 00:42:48 +00004908 if (Fn->getType() == Context.UnknownAnyTy) {
4909 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4910 if (result.isInvalid()) return ExprError();
4911 Fn = result.take();
4912 }
4913
John McCall864c0412011-04-26 20:42:42 +00004914 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00004915 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004916 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004917 }
John McCall864c0412011-04-26 20:42:42 +00004918 }
John McCall129e2df2009-11-30 22:42:35 +00004919
John McCall864c0412011-04-26 20:42:42 +00004920 // Check for overloaded calls. This can happen even in C due to extensions.
4921 if (Fn->getType() == Context.OverloadTy) {
4922 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4923
4924 // We aren't supposed to apply this logic if there's an '&' involved.
4925 if (!find.IsAddressOfOperand) {
4926 OverloadExpr *ovl = find.Expression;
4927 if (isa<UnresolvedLookupExpr>(ovl)) {
4928 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4929 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4930 RParenLoc, ExecConfig);
4931 } else {
John McCallaa81e162009-12-01 22:10:20 +00004932 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004933 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004934 }
4935 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004936 }
4937
Douglas Gregorfa047642009-02-04 00:32:51 +00004938 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004939
Eli Friedmanefa42f72009-12-26 03:35:45 +00004940 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004941
John McCall3b4294e2009-12-16 12:17:52 +00004942 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004943 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4944 if (UnOp->getOpcode() == UO_AddrOf)
4945 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4946
John McCall3b4294e2009-12-16 12:17:52 +00004947 if (isa<DeclRefExpr>(NakedFn))
4948 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00004949 else if (isa<MemberExpr>(NakedFn))
4950 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004951
Peter Collingbournee08ce652011-02-09 21:07:24 +00004952 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4953 ExecConfig);
4954}
4955
4956ExprResult
4957Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4958 MultiExprArg execConfig, SourceLocation GGGLoc) {
4959 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4960 if (!ConfigDecl)
4961 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4962 << "cudaConfigureCall");
4963 QualType ConfigQTy = ConfigDecl->getType();
4964
4965 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4966 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4967
4968 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004969}
4970
John McCall3b4294e2009-12-16 12:17:52 +00004971/// BuildResolvedCallExpr - Build a call to a resolved expression,
4972/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004973/// unary-convert to an expression of function-pointer or
4974/// block-pointer type.
4975///
4976/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004977ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004978Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4979 SourceLocation LParenLoc,
4980 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004981 SourceLocation RParenLoc,
4982 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004983 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4984
Chris Lattner04421082008-04-08 04:40:51 +00004985 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00004986 ExprResult Result = UsualUnaryConversions(Fn);
4987 if (Result.isInvalid())
4988 return ExprError();
4989 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004990
Chris Lattner925e60d2007-12-28 05:29:59 +00004991 // Make the call expr early, before semantic checks. This guarantees cleanup
4992 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004993 CallExpr *TheCall;
4994 if (Config) {
4995 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4996 cast<CallExpr>(Config),
4997 Args, NumArgs,
4998 Context.BoolTy,
4999 VK_RValue,
5000 RParenLoc);
5001 } else {
5002 TheCall = new (Context) CallExpr(Context, Fn,
5003 Args, NumArgs,
5004 Context.BoolTy,
5005 VK_RValue,
5006 RParenLoc);
5007 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005008
John McCall8e10f3b2011-02-26 05:39:39 +00005009 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5010
5011 // Bail out early if calling a builtin with custom typechecking.
5012 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5013 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5014
John McCall1de4d4e2011-04-07 08:22:57 +00005015 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00005016 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00005017 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00005018 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5019 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00005020 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00005021 if (FuncT == 0)
5022 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5023 << Fn->getType() << Fn->getSourceRange());
5024 } else if (const BlockPointerType *BPT =
5025 Fn->getType()->getAs<BlockPointerType>()) {
5026 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5027 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00005028 // Handle calls to expressions of unknown-any type.
5029 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00005030 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005031 if (rewrite.isInvalid()) return ExprError();
5032 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005033 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005034 goto retry;
5035 }
5036
Sebastian Redl0eb23302009-01-19 00:08:26 +00005037 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5038 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005039 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005040
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005041 if (getLangOptions().CUDA) {
5042 if (Config) {
5043 // CUDA: Kernel calls must be to global functions
5044 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5045 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5046 << FDecl->getName() << Fn->getSourceRange());
5047
5048 // CUDA: Kernel function must have 'void' return type
5049 if (!FuncT->getResultType()->isVoidType())
5050 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5051 << Fn->getType() << Fn->getSourceRange());
5052 }
5053 }
5054
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005055 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005056 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005057 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005058 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005059 return ExprError();
5060
Chris Lattner925e60d2007-12-28 05:29:59 +00005061 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005062 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005063 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005064
Douglas Gregor72564e72009-02-26 23:50:07 +00005065 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005066 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005067 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005068 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005069 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005070 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005071
Douglas Gregor74734d52009-04-02 15:37:10 +00005072 if (FDecl) {
5073 // Check if we have too few/too many template arguments, based
5074 // on our knowledge of the function definition.
5075 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005076 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005077 const FunctionProtoType *Proto
5078 = Def->getType()->getAs<FunctionProtoType>();
5079 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005080 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5081 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005082 }
Douglas Gregor46542412010-10-25 20:39:23 +00005083
5084 // If the function we're calling isn't a function prototype, but we have
5085 // a function prototype from a prior declaratiom, use that prototype.
5086 if (!FDecl->hasPrototype())
5087 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005088 }
5089
Steve Naroffb291ab62007-08-28 23:30:39 +00005090 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005091 for (unsigned i = 0; i != NumArgs; i++) {
5092 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005093
5094 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005095 InitializedEntity Entity
5096 = InitializedEntity::InitializeParameter(Context,
5097 Proto->getArgType(i));
5098 ExprResult ArgE = PerformCopyInitialization(Entity,
5099 SourceLocation(),
5100 Owned(Arg));
5101 if (ArgE.isInvalid())
5102 return true;
5103
5104 Arg = ArgE.takeAs<Expr>();
5105
5106 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005107 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5108
5109 if (ArgE.isInvalid())
5110 return true;
5111
5112 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005113 }
5114
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005115 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5116 Arg->getType(),
5117 PDiag(diag::err_call_incomplete_argument)
5118 << Arg->getSourceRange()))
5119 return ExprError();
5120
Chris Lattner925e60d2007-12-28 05:29:59 +00005121 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005122 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005123 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005124
Douglas Gregor88a35142008-12-22 05:46:06 +00005125 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5126 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005127 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5128 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005129
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005130 // Check for sentinels
5131 if (NDecl)
5132 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005133
Chris Lattner59907c42007-08-10 20:18:51 +00005134 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005135 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005136 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005137 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005138
John McCall8e10f3b2011-02-26 05:39:39 +00005139 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005140 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005141 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005142 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005143 return ExprError();
5144 }
Chris Lattner59907c42007-08-10 20:18:51 +00005145
John McCall9ae2f072010-08-23 23:25:46 +00005146 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005147}
5148
John McCall60d7b3a2010-08-24 06:29:42 +00005149ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005150Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005151 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005152 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005153 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005154 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005155
5156 TypeSourceInfo *TInfo;
5157 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5158 if (!TInfo)
5159 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5160
John McCall9ae2f072010-08-23 23:25:46 +00005161 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005162}
5163
John McCall60d7b3a2010-08-24 06:29:42 +00005164ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005165Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005166 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005167 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005168
Eli Friedman6223c222008-05-20 05:22:08 +00005169 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005170 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5171 PDiag(diag::err_illegal_decl_array_incomplete_type)
5172 << SourceRange(LParenLoc,
5173 literalExpr->getSourceRange().getEnd())))
5174 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005175 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005176 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5177 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005178 } else if (!literalType->isDependentType() &&
5179 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005180 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005181 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005182 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005183 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005184
Douglas Gregor99a2e602009-12-16 01:38:02 +00005185 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005186 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005187 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005188 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005189 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00005190 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005191 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005192 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005193 &literalType);
5194 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005195 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005196 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005197
Chris Lattner371f2582008-12-04 23:50:19 +00005198 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005199 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005200 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005201 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005202 }
Eli Friedman08544622009-12-22 02:35:53 +00005203
John McCallf89e55a2010-11-18 06:31:45 +00005204 // In C, compound literals are l-values for some reason.
5205 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5206
John McCall1d7d8d62010-01-19 22:33:45 +00005207 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00005208 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005209}
5210
John McCall60d7b3a2010-08-24 06:29:42 +00005211ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005212Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005213 SourceLocation RBraceLoc) {
5214 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005215 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005216
Steve Naroff08d92e42007-09-15 18:49:24 +00005217 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005218 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005219
Ted Kremenek709210f2010-04-13 23:39:13 +00005220 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5221 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005222 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005223 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005224}
5225
John McCallf3ea8cf2010-11-14 08:17:51 +00005226/// Prepares for a scalar cast, performing all the necessary stages
5227/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005228static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005229 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5230 // Also, callers should have filtered out the invalid cases with
5231 // pointers. Everything else should be possible.
5232
John Wiegley429bb272011-04-08 18:41:53 +00005233 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005234 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005235 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005236
John McCalldaa8e4e2010-11-15 09:13:47 +00005237 switch (SrcTy->getScalarTypeKind()) {
5238 case Type::STK_MemberPointer:
5239 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005240
John McCalldaa8e4e2010-11-15 09:13:47 +00005241 case Type::STK_Pointer:
5242 switch (DestTy->getScalarTypeKind()) {
5243 case Type::STK_Pointer:
5244 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005245 CK_AnyPointerToObjCPointerCast :
5246 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005247 case Type::STK_Bool:
5248 return CK_PointerToBoolean;
5249 case Type::STK_Integral:
5250 return CK_PointerToIntegral;
5251 case Type::STK_Floating:
5252 case Type::STK_FloatingComplex:
5253 case Type::STK_IntegralComplex:
5254 case Type::STK_MemberPointer:
5255 llvm_unreachable("illegal cast from pointer");
5256 }
5257 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005258
John McCalldaa8e4e2010-11-15 09:13:47 +00005259 case Type::STK_Bool: // casting from bool is like casting from an integer
5260 case Type::STK_Integral:
5261 switch (DestTy->getScalarTypeKind()) {
5262 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005263 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005264 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005265 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005266 case Type::STK_Bool:
5267 return CK_IntegralToBoolean;
5268 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005269 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005270 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005271 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005272 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005273 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5274 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005275 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005276 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005277 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5278 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005279 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005280 case Type::STK_MemberPointer:
5281 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005282 }
5283 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005284
John McCalldaa8e4e2010-11-15 09:13:47 +00005285 case Type::STK_Floating:
5286 switch (DestTy->getScalarTypeKind()) {
5287 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005288 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005289 case Type::STK_Bool:
5290 return CK_FloatingToBoolean;
5291 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005292 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005293 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005294 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5295 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005296 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005297 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005298 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5299 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005300 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005301 case Type::STK_Pointer:
5302 llvm_unreachable("valid float->pointer cast?");
5303 case Type::STK_MemberPointer:
5304 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005305 }
5306 break;
5307
John McCalldaa8e4e2010-11-15 09:13:47 +00005308 case Type::STK_FloatingComplex:
5309 switch (DestTy->getScalarTypeKind()) {
5310 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005311 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005312 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005313 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005314 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005315 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005316 if (S.Context.hasSameType(ET, DestTy))
5317 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005318 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005319 return CK_FloatingCast;
5320 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005321 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005322 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005323 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005324 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5325 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005326 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005327 case Type::STK_Pointer:
5328 llvm_unreachable("valid complex float->pointer cast?");
5329 case Type::STK_MemberPointer:
5330 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005331 }
5332 break;
5333
John McCalldaa8e4e2010-11-15 09:13:47 +00005334 case Type::STK_IntegralComplex:
5335 switch (DestTy->getScalarTypeKind()) {
5336 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005337 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005338 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005339 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005340 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005341 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005342 if (S.Context.hasSameType(ET, DestTy))
5343 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005344 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005345 return CK_IntegralCast;
5346 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005347 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005348 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005349 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005350 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5351 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005352 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005353 case Type::STK_Pointer:
5354 llvm_unreachable("valid complex int->pointer cast?");
5355 case Type::STK_MemberPointer:
5356 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005357 }
5358 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005359 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005360
John McCallf3ea8cf2010-11-14 08:17:51 +00005361 llvm_unreachable("Unhandled scalar cast");
5362 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005363}
5364
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005365/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley429bb272011-04-08 18:41:53 +00005366ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5367 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5368 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005369 if (castExpr->getType() == Context.UnknownAnyTy)
5370 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5371
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005372 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005373 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5374 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005375 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005376 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005377
John McCallfb8721c2011-04-10 19:13:55 +00005378 assert(!castExpr->getType()->isPlaceholderType());
5379
John McCallf89e55a2010-11-18 06:31:45 +00005380 // We only support r-value casts in C.
5381 VK = VK_RValue;
5382
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005383 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5384 // type needs to be scalar.
5385 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005386 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005387 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5388 if (castExprRes.isInvalid())
5389 return ExprError();
5390 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005391
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005392 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005393 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005394 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005395 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005396
John Wiegley429bb272011-04-08 18:41:53 +00005397 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5398 if (castExprRes.isInvalid())
5399 return ExprError();
5400 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005401
Eli Friedman8d438082010-07-17 20:43:49 +00005402 if (RequireCompleteType(TyR.getBegin(), castType,
5403 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005404 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005405
Anders Carlssonebeaf202009-10-16 02:35:04 +00005406 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005407 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005408 (castType->isStructureType() || castType->isUnionType())) {
5409 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005410 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005411 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5412 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005413 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005414 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005415 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005416
Anders Carlssonc3516322009-10-16 02:48:28 +00005417 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005418 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005419 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005420 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005421 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005422 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005423 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005424 castExpr->getType()) &&
5425 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005426 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5427 << castExpr->getSourceRange();
5428 break;
5429 }
5430 }
John Wiegley429bb272011-04-08 18:41:53 +00005431 if (Field == FieldEnd) {
5432 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005433 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005434 return ExprError();
5435 }
John McCall2de56d12010-08-25 11:45:40 +00005436 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005437 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005438 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005439
Anders Carlssonc3516322009-10-16 02:48:28 +00005440 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005441 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005442 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005443 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005444 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005445
John McCallf3ea8cf2010-11-14 08:17:51 +00005446 // The type we're casting to is known to be a scalar or vector.
5447
5448 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005449 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005450 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005451 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005452 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005453 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005454 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005455 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005456
5457 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005458 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005459
Anton Yartsevd06fea82011-03-27 09:32:40 +00005460 if (castType->isVectorType()) {
5461 if (castType->getAs<VectorType>()->getVectorKind() ==
5462 VectorType::AltiVecVector &&
5463 (castExpr->getType()->isIntegerType() ||
5464 castExpr->getType()->isFloatingType())) {
5465 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005466 return Owned(castExpr);
5467 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5468 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005469 } else
John Wiegley429bb272011-04-08 18:41:53 +00005470 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005471 }
John Wiegley429bb272011-04-08 18:41:53 +00005472 if (castExpr->getType()->isVectorType()) {
5473 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5474 return ExprError();
5475 else
5476 return Owned(castExpr);
5477 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005478
John McCallf3ea8cf2010-11-14 08:17:51 +00005479 // The source and target types are both scalars, i.e.
5480 // - arithmetic types (fundamental, enum, and complex)
5481 // - all kinds of pointers
5482 // Note that member pointers were filtered out with C++, above.
5483
John Wiegley429bb272011-04-08 18:41:53 +00005484 if (isa<ObjCSelectorExpr>(castExpr)) {
5485 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5486 return ExprError();
5487 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005488
John McCallf3ea8cf2010-11-14 08:17:51 +00005489 // If either type is a pointer, the other type has to be either an
5490 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005491 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005492 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005493 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005494 castExprType->isArithmeticType()) {
5495 Diag(castExpr->getLocStart(),
5496 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005497 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005498 return ExprError();
5499 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005500 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005501 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5502 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005503 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005504 return ExprError();
5505 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005506 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005507
John Wiegley429bb272011-04-08 18:41:53 +00005508 castExprRes = Owned(castExpr);
5509 Kind = PrepareScalarCast(*this, castExprRes, castType);
5510 if (castExprRes.isInvalid())
5511 return ExprError();
5512 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005513
John McCallf3ea8cf2010-11-14 08:17:51 +00005514 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005515 CheckCastAlign(castExpr, castType, TyR);
5516
John Wiegley429bb272011-04-08 18:41:53 +00005517 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005518}
5519
Anders Carlssonc3516322009-10-16 02:48:28 +00005520bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005521 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005522 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005523
Anders Carlssona64db8f2007-11-27 05:51:55 +00005524 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005525 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005526 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005527 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005528 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005529 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005530 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005531 } else
5532 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005533 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005534 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005535
John McCall2de56d12010-08-25 11:45:40 +00005536 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005537 return false;
5538}
5539
John Wiegley429bb272011-04-08 18:41:53 +00005540ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5541 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005542 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005543
Anders Carlsson16a89042009-10-16 05:23:41 +00005544 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005545
Nate Begeman9b10da62009-06-27 22:05:55 +00005546 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5547 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005548 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005549 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5550 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005551 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005552 return ExprError();
5553 }
John McCall2de56d12010-08-25 11:45:40 +00005554 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005555 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005556 }
5557
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005558 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005559 // conversion will take place first from scalar to elt type, and then
5560 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005561 if (SrcTy->isPointerType())
5562 return Diag(R.getBegin(),
5563 diag::err_invalid_conversion_between_vector_and_scalar)
5564 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005565
5566 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005567 ExprResult CastExprRes = Owned(CastExpr);
5568 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5569 if (CastExprRes.isInvalid())
5570 return ExprError();
5571 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005572
John McCall2de56d12010-08-25 11:45:40 +00005573 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005574 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005575}
5576
John McCall60d7b3a2010-08-24 06:29:42 +00005577ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005578Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005579 SourceLocation RParenLoc, Expr *castExpr) {
5580 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005581 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005582
John McCall9d125032010-01-15 18:39:57 +00005583 TypeSourceInfo *castTInfo;
5584 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5585 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005586 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005587
Nate Begeman2ef13e52009-08-10 23:49:36 +00005588 // If the Expr being casted is a ParenListExpr, handle it specially.
5589 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005590 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005591 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005592
John McCall9ae2f072010-08-23 23:25:46 +00005593 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005594}
5595
John McCall60d7b3a2010-08-24 06:29:42 +00005596ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005597Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005598 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005599 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005600 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005601 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005602 ExprResult CastResult =
5603 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5604 Kind, VK, BasePath);
5605 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005606 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005607 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005608
John McCallf871d0c2010-08-07 06:22:56 +00005609 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005610 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005611 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005612 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005613}
5614
Nate Begeman2ef13e52009-08-10 23:49:36 +00005615/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5616/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005617ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005618Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005619 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5620 if (!E)
5621 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005622
John McCall60d7b3a2010-08-24 06:29:42 +00005623 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005624
Nate Begeman2ef13e52009-08-10 23:49:36 +00005625 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005626 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5627 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005628
John McCall9ae2f072010-08-23 23:25:46 +00005629 if (Result.isInvalid()) return ExprError();
5630
5631 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005632}
5633
John McCall60d7b3a2010-08-24 06:29:42 +00005634ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005635Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005636 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005637 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005638 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005639 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005640 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005641
Anton Yartsevd06fea82011-03-27 09:32:40 +00005642 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005643 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005644 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5645 if (PE->getNumExprs() == 0) {
5646 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5647 return ExprError();
5648 }
John Thompson8bb59a82010-06-30 22:55:51 +00005649 if (PE->getNumExprs() == 1) {
5650 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005651 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005652 }
5653 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005654 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005655 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005656
Anton Yartsevd06fea82011-03-27 09:32:40 +00005657 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005658 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005659 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005660 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005661 // '(...)' form of vector initialization in AltiVec: the number of
5662 // initializers must be one or must match the size of the vector.
5663 // If a single value is specified in the initializer then it will be
5664 // replicated to all the components of the vector
5665 if (Ty->getAs<VectorType>()->getVectorKind() ==
5666 VectorType::AltiVecVector) {
5667 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5668 // The number of initializers must be one or must match the size of the
5669 // vector. If a single value is specified in the initializer then it will
5670 // be replicated to all the components of the vector
5671 if (PE->getNumExprs() == 1) {
5672 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005673 ExprResult Literal = Owned(PE->getExpr(0));
5674 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5675 PrepareScalarCast(*this, Literal, ElemTy));
5676 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005677 }
5678 else if (PE->getNumExprs() < numElems) {
5679 Diag(PE->getExprLoc(),
5680 diag::err_incorrect_number_of_vector_initializers);
5681 return ExprError();
5682 }
5683 else
5684 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5685 initExprs.push_back(PE->getExpr(i));
5686 }
5687 else
5688 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5689 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005690
5691 // FIXME: This means that pretty-printing the final AST will produce curly
5692 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005693 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5694 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005695 initExprs.size(), RParenLoc);
5696 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005697 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005698 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005699 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005700 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005701 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005702 if (Result.isInvalid()) return ExprError();
5703 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005704 }
5705}
5706
John McCall60d7b3a2010-08-24 06:29:42 +00005707ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005708 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005709 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005710 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005711 unsigned nexprs = Val.size();
5712 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005713 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5714 Expr *expr;
5715 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5716 expr = new (Context) ParenExpr(L, R, exprs[0]);
5717 else
5718 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005719 return Owned(expr);
5720}
5721
Chandler Carruth82214a82011-02-18 23:54:50 +00005722/// \brief Emit a specialized diagnostic when one expression is a null pointer
5723/// constant and the other is not a pointer.
5724bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5725 SourceLocation QuestionLoc) {
5726 Expr *NullExpr = LHS;
5727 Expr *NonPointerExpr = RHS;
5728 Expr::NullPointerConstantKind NullKind =
5729 NullExpr->isNullPointerConstant(Context,
5730 Expr::NPC_ValueDependentIsNotNull);
5731
5732 if (NullKind == Expr::NPCK_NotNull) {
5733 NullExpr = RHS;
5734 NonPointerExpr = LHS;
5735 NullKind =
5736 NullExpr->isNullPointerConstant(Context,
5737 Expr::NPC_ValueDependentIsNotNull);
5738 }
5739
5740 if (NullKind == Expr::NPCK_NotNull)
5741 return false;
5742
5743 if (NullKind == Expr::NPCK_ZeroInteger) {
5744 // In this case, check to make sure that we got here from a "NULL"
5745 // string in the source code.
5746 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005747 SourceLocation loc = NullExpr->getExprLoc();
5748 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005749 return false;
5750 }
5751
5752 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5753 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5754 << NonPointerExpr->getType() << DiagType
5755 << NonPointerExpr->getSourceRange();
5756 return true;
5757}
5758
Sebastian Redl28507842009-02-26 14:39:58 +00005759/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5760/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005761/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005762QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005763 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005764 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005765
John McCallfb8721c2011-04-10 19:13:55 +00005766 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005767 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005768 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005769
John McCallfb8721c2011-04-10 19:13:55 +00005770 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005771 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005772 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005773
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005774 // C++ is sufficiently different to merit its own checker.
5775 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005776 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005777
5778 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005779 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005780
John Wiegley429bb272011-04-08 18:41:53 +00005781 Cond = UsualUnaryConversions(Cond.take());
5782 if (Cond.isInvalid())
5783 return QualType();
5784 LHS = UsualUnaryConversions(LHS.take());
5785 if (LHS.isInvalid())
5786 return QualType();
5787 RHS = UsualUnaryConversions(RHS.take());
5788 if (RHS.isInvalid())
5789 return QualType();
5790
5791 QualType CondTy = Cond.get()->getType();
5792 QualType LHSTy = LHS.get()->getType();
5793 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005794
Reid Spencer5f016e22007-07-11 17:01:13 +00005795 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005796 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005797 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5798 // Throw an error if its not either.
5799 if (getLangOptions().OpenCL) {
5800 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005801 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005802 diag::err_typecheck_cond_expect_scalar_or_vector)
5803 << CondTy;
5804 return QualType();
5805 }
5806 }
5807 else {
John Wiegley429bb272011-04-08 18:41:53 +00005808 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005809 << CondTy;
5810 return QualType();
5811 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005812 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005813
Chris Lattner70d67a92008-01-06 22:42:25 +00005814 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005815 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5816 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005817
Nate Begeman6155d732010-09-20 22:41:17 +00005818 // OpenCL: If the condition is a vector, and both operands are scalar,
5819 // attempt to implicity convert them to the vector type to act like the
5820 // built in select.
5821 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5822 // Both operands should be of scalar type.
5823 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005824 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005825 << CondTy;
5826 return QualType();
5827 }
5828 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005829 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005830 << CondTy;
5831 return QualType();
5832 }
5833 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005834 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5835 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005836 }
5837
Chris Lattner70d67a92008-01-06 22:42:25 +00005838 // If both operands have arithmetic type, do the usual arithmetic conversions
5839 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005840 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5841 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005842 if (LHS.isInvalid() || RHS.isInvalid())
5843 return QualType();
5844 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005845 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005846
Chris Lattner70d67a92008-01-06 22:42:25 +00005847 // If both operands are the same structure or union type, the result is that
5848 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005849 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5850 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005851 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005852 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005853 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005854 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005855 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005857
Chris Lattner70d67a92008-01-06 22:42:25 +00005858 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005859 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005860 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5861 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005862 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5863 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005864 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005865 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5866 << LHS.get()->getSourceRange();
5867 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5868 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005869 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005870 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005871 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5872 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005873 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005874 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005875 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00005876 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005877 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005878 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005879 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005880 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5881 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005882 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005883 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005884
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005885 // All objective-c pointer type analysis is done here.
5886 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5887 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005888 if (LHS.isInvalid() || RHS.isInvalid())
5889 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005890 if (!compositeType.isNull())
5891 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005892
5893
Steve Naroff7154a772009-07-01 14:36:47 +00005894 // Handle block pointer types.
5895 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5896 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5897 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5898 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005899 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5900 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005901 return destType;
5902 }
5903 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005904 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005905 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005906 }
Steve Naroff7154a772009-07-01 14:36:47 +00005907 // We have 2 block pointer types.
5908 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5909 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005910 return LHSTy;
5911 }
Steve Naroff7154a772009-07-01 14:36:47 +00005912 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005913 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5914 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005915
Steve Naroff7154a772009-07-01 14:36:47 +00005916 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5917 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005918 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005919 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005920 // In this situation, we assume void* type. No especially good
5921 // reason, but this is what gcc does, and we do have to pick
5922 // to get a consistent AST.
5923 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005924 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5925 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005926 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005927 }
Steve Naroff7154a772009-07-01 14:36:47 +00005928 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005929 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5930 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005931 return LHSTy;
5932 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005933
Steve Naroff7154a772009-07-01 14:36:47 +00005934 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5935 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5936 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005937 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5938 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005939
5940 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5941 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5942 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005943 QualType destPointee
5944 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005945 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005946 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005947 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005948 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005949 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005950 return destType;
5951 }
5952 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005953 QualType destPointee
5954 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005955 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005956 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005957 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005958 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005959 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005960 return destType;
5961 }
5962
5963 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5964 // Two identical pointer types are always compatible.
5965 return LHSTy;
5966 }
5967 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5968 rhptee.getUnqualifiedType())) {
5969 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005970 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005971 // In this situation, we assume void* type. No especially good
5972 // reason, but this is what gcc does, and we do have to pick
5973 // to get a consistent AST.
5974 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005975 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5976 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005977 return incompatTy;
5978 }
5979 // The pointer types are compatible.
5980 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5981 // differently qualified versions of compatible types, the result type is
5982 // a pointer to an appropriately qualified version of the *composite*
5983 // type.
5984 // FIXME: Need to calculate the composite type.
5985 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00005986 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5987 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005988 return LHSTy;
5989 }
Mike Stump1eb44332009-09-09 15:08:12 +00005990
John McCall404cd162010-11-13 01:35:44 +00005991 // GCC compatibility: soften pointer/integer mismatch. Note that
5992 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005993 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5994 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005995 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5996 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005997 return RHSTy;
5998 }
5999 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6000 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00006001 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6002 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00006003 return LHSTy;
6004 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00006005
Chandler Carruth82214a82011-02-18 23:54:50 +00006006 // Emit a better diagnostic if one of the expressions is a null pointer
6007 // constant and the other is not a pointer type. In this case, the user most
6008 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00006009 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00006010 return QualType();
6011
Chris Lattner70d67a92008-01-06 22:42:25 +00006012 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006013 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006014 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006015 return QualType();
6016}
6017
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006018/// FindCompositeObjCPointerType - Helper method to find composite type of
6019/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00006020QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006021 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00006022 QualType LHSTy = LHS.get()->getType();
6023 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006024
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006025 // Handle things like Class and struct objc_class*. Here we case the result
6026 // to the pseudo-builtin, because that will be implicitly cast back to the
6027 // redefinition type if an attempt is made to access its fields.
6028 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006029 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006030 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006031 return LHSTy;
6032 }
6033 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006034 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006035 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006036 return RHSTy;
6037 }
6038 // And the same for struct objc_object* / id
6039 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006040 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006041 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006042 return LHSTy;
6043 }
6044 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006045 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006046 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006047 return RHSTy;
6048 }
6049 // And the same for struct objc_selector* / SEL
6050 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006051 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006052 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006053 return LHSTy;
6054 }
6055 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006056 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006057 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006058 return RHSTy;
6059 }
6060 // Check constraints for Objective-C object pointers types.
6061 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006062
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006063 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6064 // Two identical object pointer types are always compatible.
6065 return LHSTy;
6066 }
6067 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6068 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6069 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006070
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006071 // If both operands are interfaces and either operand can be
6072 // assigned to the other, use that type as the composite
6073 // type. This allows
6074 // xxx ? (A*) a : (B*) b
6075 // where B is a subclass of A.
6076 //
6077 // Additionally, as for assignment, if either type is 'id'
6078 // allow silent coercion. Finally, if the types are
6079 // incompatible then make sure to use 'id' as the composite
6080 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006081
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006082 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6083 // It could return the composite type.
6084 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6085 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6086 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6087 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6088 } else if ((LHSTy->isObjCQualifiedIdType() ||
6089 RHSTy->isObjCQualifiedIdType()) &&
6090 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6091 // Need to handle "id<xx>" explicitly.
6092 // GCC allows qualified id and any Objective-C type to devolve to
6093 // id. Currently localizing to here until clear this should be
6094 // part of ObjCQualifiedIdTypesAreCompatible.
6095 compositeType = Context.getObjCIdType();
6096 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6097 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006098 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006099 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6100 ;
6101 else {
6102 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6103 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006104 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006105 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006106 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6107 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006108 return incompatTy;
6109 }
6110 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006111 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6112 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006113 return compositeType;
6114 }
6115 // Check Objective-C object pointer types and 'void *'
6116 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6117 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6118 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6119 QualType destPointee
6120 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6121 QualType destType = Context.getPointerType(destPointee);
6122 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006123 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006124 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006125 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006126 return destType;
6127 }
6128 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6129 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6130 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6131 QualType destPointee
6132 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6133 QualType destType = Context.getPointerType(destPointee);
6134 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006135 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006136 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006137 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006138 return destType;
6139 }
6140 return QualType();
6141}
6142
Steve Narofff69936d2007-09-16 03:34:24 +00006143/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006144/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006145ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006146 SourceLocation ColonLoc,
6147 Expr *CondExpr, Expr *LHSExpr,
6148 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006149 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6150 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006151 OpaqueValueExpr *opaqueValue = 0;
6152 Expr *commonExpr = 0;
6153 if (LHSExpr == 0) {
6154 commonExpr = CondExpr;
6155
6156 // We usually want to apply unary conversions *before* saving, except
6157 // in the special case of a C++ l-value conditional.
6158 if (!(getLangOptions().CPlusPlus
6159 && !commonExpr->isTypeDependent()
6160 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6161 && commonExpr->isGLValue()
6162 && commonExpr->isOrdinaryOrBitFieldObject()
6163 && RHSExpr->isOrdinaryOrBitFieldObject()
6164 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006165 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6166 if (commonRes.isInvalid())
6167 return ExprError();
6168 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006169 }
6170
6171 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6172 commonExpr->getType(),
6173 commonExpr->getValueKind(),
6174 commonExpr->getObjectKind());
6175 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006176 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006177
John McCallf89e55a2010-11-18 06:31:45 +00006178 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006179 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006180 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6181 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006182 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006183 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6184 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006185 return ExprError();
6186
John McCall56ca35d2011-02-17 10:25:35 +00006187 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006188 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6189 LHS.take(), ColonLoc,
6190 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006191
6192 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006193 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6194 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006195}
6196
John McCalle4be87e2011-01-31 23:13:11 +00006197// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006198// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006199// routine is it effectively iqnores the qualifiers on the top level pointee.
6200// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6201// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006202static Sema::AssignConvertType
6203checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6204 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6205 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006206
Reid Spencer5f016e22007-07-11 17:01:13 +00006207 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006208 const Type *lhptee, *rhptee;
6209 Qualifiers lhq, rhq;
6210 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6211 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006212
John McCalle4be87e2011-01-31 23:13:11 +00006213 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006214
6215 // C99 6.5.16.1p1: This following citation is common to constraints
6216 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6217 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006218 Qualifiers lq;
6219
6220 if (!lhq.compatiblyIncludes(rhq)) {
6221 // Treat address-space mismatches as fatal. TODO: address subspaces
6222 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6223 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6224
John McCall22348732011-03-26 02:56:45 +00006225 // It's okay to add or remove GC qualifiers when converting to
6226 // and from void*.
6227 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6228 && (lhptee->isVoidType() || rhptee->isVoidType()))
6229 ; // keep old
6230
John McCall86c05f32011-02-01 00:10:29 +00006231 // For GCC compatibility, other qualifier mismatches are treated
6232 // as still compatible in C.
6233 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6234 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006235
Mike Stumpeed9cac2009-02-19 03:04:26 +00006236 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6237 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006238 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006239 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006240 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006241 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006242
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006243 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006244 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006245 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006246 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006247
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006248 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006249 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006250 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006251
6252 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006253 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006254 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006255 }
John McCall86c05f32011-02-01 00:10:29 +00006256
Mike Stumpeed9cac2009-02-19 03:04:26 +00006257 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006258 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006259 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6260 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006261 // Check if the pointee types are compatible ignoring the sign.
6262 // We explicitly check for char so that we catch "char" vs
6263 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006264 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006265 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006266 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006267 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006268
Chris Lattner6a2b9262009-10-17 20:33:28 +00006269 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006270 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006271 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006272 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006273
John McCall86c05f32011-02-01 00:10:29 +00006274 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006275 // Types are compatible ignoring the sign. Qualifier incompatibility
6276 // takes priority over sign incompatibility because the sign
6277 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006278 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006279 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006280
John McCalle4be87e2011-01-31 23:13:11 +00006281 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006282 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006283
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006284 // If we are a multi-level pointer, it's possible that our issue is simply
6285 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6286 // the eventual target type is the same and the pointers have the same
6287 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006288 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006289 do {
John McCall86c05f32011-02-01 00:10:29 +00006290 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6291 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006292 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006293
John McCall86c05f32011-02-01 00:10:29 +00006294 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006295 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006296 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006297
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006298 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006299 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006300 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006301 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006302}
6303
John McCalle4be87e2011-01-31 23:13:11 +00006304/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006305/// block pointer types are compatible or whether a block and normal pointer
6306/// are compatible. It is more restrict than comparing two function pointer
6307// types.
John McCalle4be87e2011-01-31 23:13:11 +00006308static Sema::AssignConvertType
6309checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6310 QualType rhsType) {
6311 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6312 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6313
Steve Naroff1c7d0672008-09-04 15:10:53 +00006314 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006315
Steve Naroff1c7d0672008-09-04 15:10:53 +00006316 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006317 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6318 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006319
John McCalle4be87e2011-01-31 23:13:11 +00006320 // In C++, the types have to match exactly.
6321 if (S.getLangOptions().CPlusPlus)
6322 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006323
John McCalle4be87e2011-01-31 23:13:11 +00006324 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006325
Steve Naroff1c7d0672008-09-04 15:10:53 +00006326 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006327 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6328 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006329
John McCalle4be87e2011-01-31 23:13:11 +00006330 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6331 return Sema::IncompatibleBlockPointer;
6332
Steve Naroff1c7d0672008-09-04 15:10:53 +00006333 return ConvTy;
6334}
6335
John McCalle4be87e2011-01-31 23:13:11 +00006336/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006337/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006338static Sema::AssignConvertType
6339checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6340 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6341 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6342
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006343 if (lhsType->isObjCBuiltinType()) {
6344 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006345 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6346 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006347 return Sema::IncompatiblePointer;
6348 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006349 }
6350 if (rhsType->isObjCBuiltinType()) {
6351 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006352 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6353 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006354 return Sema::IncompatiblePointer;
6355 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006356 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006357 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006358 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006359 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006360 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006361
John McCalle4be87e2011-01-31 23:13:11 +00006362 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6363 return Sema::CompatiblePointerDiscardsQualifiers;
6364
6365 if (S.Context.typesAreCompatible(lhsType, rhsType))
6366 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006367 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006368 return Sema::IncompatibleObjCQualifiedId;
6369 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006370}
6371
John McCall1c23e912010-11-16 02:32:08 +00006372Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006373Sema::CheckAssignmentConstraints(SourceLocation Loc,
6374 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006375 // Fake up an opaque expression. We don't actually care about what
6376 // cast operations are required, so if CheckAssignmentConstraints
6377 // adds casts to this they'll be wasted, but fortunately that doesn't
6378 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006379 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006380 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006381 CastKind K = CK_Invalid;
6382
6383 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6384}
6385
Mike Stumpeed9cac2009-02-19 03:04:26 +00006386/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6387/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006388/// pointers. Here are some objectionable examples that GCC considers warnings:
6389///
6390/// int a, *pint;
6391/// short *pshort;
6392/// struct foo *pfoo;
6393///
6394/// pint = pshort; // warning: assignment from incompatible pointer type
6395/// a = pint; // warning: assignment makes integer from pointer without a cast
6396/// pint = a; // warning: assignment makes pointer from integer without a cast
6397/// pint = pfoo; // warning: assignment from incompatible pointer type
6398///
6399/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006400/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006401///
John McCalldaa8e4e2010-11-15 09:13:47 +00006402/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006403Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006404Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006405 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006406 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006407
Chris Lattnerfc144e22008-01-04 23:18:45 +00006408 // Get canonical types. We're not formatting these types, just comparing
6409 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006410 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6411 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006412
John McCallb6cfa242011-01-31 22:28:28 +00006413 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006414 if (lhsType == rhsType) {
6415 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006416 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006417 }
6418
Douglas Gregor9d293df2008-10-28 00:22:11 +00006419 // If the left-hand side is a reference type, then we are in a
6420 // (rare!) case where we've allowed the use of references in C,
6421 // e.g., as a parameter type in a built-in function. In this case,
6422 // just make sure that the type referenced is compatible with the
6423 // right-hand side type. The caller is responsible for adjusting
6424 // lhsType so that the resulting expression does not have reference
6425 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006426 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006427 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6428 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006429 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006430 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006431 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006432 }
John McCallb6cfa242011-01-31 22:28:28 +00006433
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006434 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6435 // to the same ExtVector type.
6436 if (lhsType->isExtVectorType()) {
6437 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006438 return Incompatible;
6439 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006440 // CK_VectorSplat does T -> vector T, so first cast to the
6441 // element type.
6442 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6443 if (elType != rhsType) {
6444 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006445 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006446 }
6447 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006448 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006449 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006450 }
Mike Stump1eb44332009-09-09 15:08:12 +00006451
John McCallb6cfa242011-01-31 22:28:28 +00006452 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006453 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006454 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006455 // Allow assignments of an AltiVec vector type to an equivalent GCC
6456 // vector type and vice versa
6457 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6458 Kind = CK_BitCast;
6459 return Compatible;
6460 }
6461
Douglas Gregor255210e2010-08-06 10:14:59 +00006462 // If we are allowing lax vector conversions, and LHS and RHS are both
6463 // vectors, the total size only needs to be the same. This is a bitcast;
6464 // no bits are changed but the result type is different.
6465 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006466 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006467 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006468 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006469 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006470 }
6471 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006472 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006473
John McCallb6cfa242011-01-31 22:28:28 +00006474 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006475 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006476 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006477 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006478 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006479 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006480
John McCallb6cfa242011-01-31 22:28:28 +00006481 // Conversions to normal pointers.
6482 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6483 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006484 if (isa<PointerType>(rhsType)) {
6485 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006486 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006487 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006488
John McCallb6cfa242011-01-31 22:28:28 +00006489 // int -> T*
6490 if (rhsType->isIntegerType()) {
6491 Kind = CK_IntegralToPointer; // FIXME: null?
6492 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006493 }
John McCallb6cfa242011-01-31 22:28:28 +00006494
6495 // C pointers are not compatible with ObjC object pointers,
6496 // with two exceptions:
6497 if (isa<ObjCObjectPointerType>(rhsType)) {
6498 // - conversions to void*
6499 if (lhsPointer->getPointeeType()->isVoidType()) {
6500 Kind = CK_AnyPointerToObjCPointerCast;
6501 return Compatible;
6502 }
6503
6504 // - conversions from 'Class' to the redefinition type
6505 if (rhsType->isObjCClassType() &&
6506 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006507 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006508 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006509 }
Steve Naroffb4406862008-09-29 18:10:17 +00006510
John McCallb6cfa242011-01-31 22:28:28 +00006511 Kind = CK_BitCast;
6512 return IncompatiblePointer;
6513 }
6514
6515 // U^ -> void*
6516 if (rhsType->getAs<BlockPointerType>()) {
6517 if (lhsPointer->getPointeeType()->isVoidType()) {
6518 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006519 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006520 }
Steve Naroffb4406862008-09-29 18:10:17 +00006521 }
John McCallb6cfa242011-01-31 22:28:28 +00006522
Steve Naroff1c7d0672008-09-04 15:10:53 +00006523 return Incompatible;
6524 }
6525
John McCallb6cfa242011-01-31 22:28:28 +00006526 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006527 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006528 // U^ -> T^
6529 if (rhsType->isBlockPointerType()) {
6530 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006531 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006532 }
6533
6534 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006535 if (rhsType->isIntegerType()) {
6536 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006537 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006538 }
6539
John McCallb6cfa242011-01-31 22:28:28 +00006540 // id -> T^
6541 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6542 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006543 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006544 }
Steve Naroffb4406862008-09-29 18:10:17 +00006545
John McCallb6cfa242011-01-31 22:28:28 +00006546 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006547 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006548 if (RHSPT->getPointeeType()->isVoidType()) {
6549 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006550 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006551 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006552
Chris Lattnerfc144e22008-01-04 23:18:45 +00006553 return Incompatible;
6554 }
6555
John McCallb6cfa242011-01-31 22:28:28 +00006556 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006557 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006558 // A* -> B*
6559 if (rhsType->isObjCObjectPointerType()) {
6560 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006561 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006562 }
6563
6564 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006565 if (rhsType->isIntegerType()) {
6566 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006567 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006568 }
6569
John McCallb6cfa242011-01-31 22:28:28 +00006570 // In general, C pointers are not compatible with ObjC object pointers,
6571 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006572 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006573 // - conversions from 'void*'
6574 if (rhsType->isVoidPointerType()) {
6575 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006576 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006577 }
6578
6579 // - conversions to 'Class' from its redefinition type
6580 if (lhsType->isObjCClassType() &&
6581 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6582 Kind = CK_BitCast;
6583 return Compatible;
6584 }
6585
6586 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006587 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006588 }
John McCallb6cfa242011-01-31 22:28:28 +00006589
6590 // T^ -> A*
6591 if (rhsType->isBlockPointerType()) {
6592 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006593 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006594 }
6595
Steve Naroff14108da2009-07-10 23:34:53 +00006596 return Incompatible;
6597 }
John McCallb6cfa242011-01-31 22:28:28 +00006598
6599 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006600 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006601 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006602 if (lhsType == Context.BoolTy) {
6603 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006604 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006605 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006606
John McCallb6cfa242011-01-31 22:28:28 +00006607 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006608 if (lhsType->isIntegerType()) {
6609 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006610 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006611 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006612
Chris Lattnerfc144e22008-01-04 23:18:45 +00006613 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006614 }
John McCallb6cfa242011-01-31 22:28:28 +00006615
6616 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006617 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006618 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006619 if (lhsType == Context.BoolTy) {
6620 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006621 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006622 }
Steve Naroff14108da2009-07-10 23:34:53 +00006623
John McCallb6cfa242011-01-31 22:28:28 +00006624 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006625 if (lhsType->isIntegerType()) {
6626 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006627 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006628 }
6629
Steve Naroff14108da2009-07-10 23:34:53 +00006630 return Incompatible;
6631 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006632
John McCallb6cfa242011-01-31 22:28:28 +00006633 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006634 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006635 if (Context.typesAreCompatible(lhsType, rhsType)) {
6636 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006637 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006638 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006639 }
John McCallb6cfa242011-01-31 22:28:28 +00006640
Reid Spencer5f016e22007-07-11 17:01:13 +00006641 return Incompatible;
6642}
6643
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006644/// \brief Constructs a transparent union from an expression that is
6645/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006646static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006647 QualType UnionType, FieldDecl *Field) {
6648 // Build an initializer list that designates the appropriate member
6649 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006650 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006651 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006652 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006653 SourceLocation());
6654 Initializer->setType(UnionType);
6655 Initializer->setInitializedFieldInUnion(Field);
6656
6657 // Build a compound literal constructing a value of the transparent
6658 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006659 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006660 EResult = S.Owned(
6661 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6662 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006663}
6664
6665Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006666Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6667 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006668
Mike Stump1eb44332009-09-09 15:08:12 +00006669 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006670 // transparent_union GCC extension.
6671 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006672 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006673 return Incompatible;
6674
6675 // The field to initialize within the transparent union.
6676 RecordDecl *UD = UT->getDecl();
6677 FieldDecl *InitField = 0;
6678 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006679 for (RecordDecl::field_iterator it = UD->field_begin(),
6680 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006681 it != itend; ++it) {
6682 if (it->getType()->isPointerType()) {
6683 // If the transparent union contains a pointer type, we allow:
6684 // 1) void pointer
6685 // 2) null pointer constant
6686 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006687 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006688 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006689 InitField = *it;
6690 break;
6691 }
Mike Stump1eb44332009-09-09 15:08:12 +00006692
John Wiegley429bb272011-04-08 18:41:53 +00006693 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006694 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006695 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006696 InitField = *it;
6697 break;
6698 }
6699 }
6700
John McCalldaa8e4e2010-11-15 09:13:47 +00006701 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006702 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006703 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006704 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006705 InitField = *it;
6706 break;
6707 }
6708 }
6709
6710 if (!InitField)
6711 return Incompatible;
6712
John Wiegley429bb272011-04-08 18:41:53 +00006713 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006714 return Compatible;
6715}
6716
Chris Lattner5cf216b2008-01-04 18:04:52 +00006717Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006718Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006719 if (getLangOptions().CPlusPlus) {
6720 if (!lhsType->isRecordType()) {
6721 // C++ 5.17p3: If the left operand is not of class type, the
6722 // expression is implicitly converted (C++ 4) to the
6723 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006724 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6725 lhsType.getUnqualifiedType(),
6726 AA_Assigning);
6727 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006728 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006729 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006730 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006731 }
6732
6733 // FIXME: Currently, we fall through and treat C++ classes like C
6734 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006735 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006736
Steve Naroff529a4ad2007-11-27 17:58:44 +00006737 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6738 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006739 if ((lhsType->isPointerType() ||
6740 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006741 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00006742 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006743 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006744 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006745 return Compatible;
6746 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747
Chris Lattner943140e2007-10-16 02:55:40 +00006748 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006749 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006750 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006751 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006752 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006753 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00006754 if (!lhsType->isReferenceType()) {
6755 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6756 if (rExpr.isInvalid())
6757 return Incompatible;
6758 }
Steve Narofff1120de2007-08-24 22:33:52 +00006759
John McCalldaa8e4e2010-11-15 09:13:47 +00006760 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006761 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006762 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006763
Steve Narofff1120de2007-08-24 22:33:52 +00006764 // C99 6.5.16.1p2: The value of the right operand is converted to the
6765 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006766 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6767 // so that we can use references in built-in functions even in C.
6768 // The getNonReferenceType() call makes sure that the resulting expression
6769 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00006770 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6771 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006772 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006773}
6774
John Wiegley429bb272011-04-08 18:41:53 +00006775QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006776 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006777 << lex.get()->getType() << rex.get()->getType()
6778 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006779 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006780}
6781
John Wiegley429bb272011-04-08 18:41:53 +00006782QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006783 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006784 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006785 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006786 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00006787 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006788 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006789
Nate Begemanbe2341d2008-07-14 18:02:46 +00006790 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006791 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006792 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006793
Nate Begemanbe2341d2008-07-14 18:02:46 +00006794 // Handle the case of a vector & extvector type of the same size and element
6795 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006796 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006797 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006798 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006799 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006800 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006801 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006802 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006803 return lhsType;
6804 }
6805
John Wiegley429bb272011-04-08 18:41:53 +00006806 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006807 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006808 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6809 // If we are allowing lax vector conversions, and LHS and RHS are both
6810 // vectors, the total size only needs to be the same. This is a
6811 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00006812 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00006813 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006814 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006815 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006816 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006817 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006818
Douglas Gregor255210e2010-08-06 10:14:59 +00006819 // Handle the case of equivalent AltiVec and GCC vector types
6820 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6821 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00006822 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006823 return rhsType;
6824 }
6825
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006826 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6827 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6828 bool swapped = false;
6829 if (rhsType->isExtVectorType()) {
6830 swapped = true;
6831 std::swap(rex, lex);
6832 std::swap(rhsType, lhsType);
6833 }
Mike Stump1eb44332009-09-09 15:08:12 +00006834
Nate Begemandde25982009-06-28 19:12:57 +00006835 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006836 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006837 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006838 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006839 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6840 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006841 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006842 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006843 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006844 if (swapped) std::swap(rex, lex);
6845 return lhsType;
6846 }
6847 }
6848 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6849 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006850 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6851 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006852 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006853 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006854 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006855 if (swapped) std::swap(rex, lex);
6856 return lhsType;
6857 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006858 }
6859 }
Mike Stump1eb44332009-09-09 15:08:12 +00006860
Nate Begemandde25982009-06-28 19:12:57 +00006861 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006862 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00006863 << lex.get()->getType() << rex.get()->getType()
6864 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006865 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006866}
6867
Chris Lattner7ef655a2010-01-12 21:23:57 +00006868QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006869 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6870 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006871 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006872
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006873 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006874 if (lex.isInvalid() || rex.isInvalid())
6875 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006876
John Wiegley429bb272011-04-08 18:41:53 +00006877 if (!lex.get()->getType()->isArithmeticType() ||
6878 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006879 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006880
Chris Lattner7ef655a2010-01-12 21:23:57 +00006881 // Check for division by zero.
6882 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00006883 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6884 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6885 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006886
Chris Lattner7ef655a2010-01-12 21:23:57 +00006887 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006888}
6889
Chris Lattner7ef655a2010-01-12 21:23:57 +00006890QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006891 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6892 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6893 if (lex.get()->getType()->hasIntegerRepresentation() &&
6894 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006895 return CheckVectorOperands(Loc, lex, rex);
6896 return InvalidOperands(Loc, lex, rex);
6897 }
Steve Naroff90045e82007-07-13 23:32:42 +00006898
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006899 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006900 if (lex.isInvalid() || rex.isInvalid())
6901 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902
John Wiegley429bb272011-04-08 18:41:53 +00006903 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006904 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006905
Chris Lattner7ef655a2010-01-12 21:23:57 +00006906 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00006907 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6908 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6909 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006910
Chris Lattner7ef655a2010-01-12 21:23:57 +00006911 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006912}
6913
Chris Lattner7ef655a2010-01-12 21:23:57 +00006914QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006915 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6916 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006917 QualType compType = CheckVectorOperands(Loc, lex, rex);
6918 if (CompLHSTy) *CompLHSTy = compType;
6919 return compType;
6920 }
Steve Naroff49b45262007-07-13 16:58:59 +00006921
Eli Friedmanab3a8522009-03-28 01:22:36 +00006922 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006923 if (lex.isInvalid() || rex.isInvalid())
6924 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006925
Reid Spencer5f016e22007-07-11 17:01:13 +00006926 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006927 if (lex.get()->getType()->isArithmeticType() &&
6928 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006929 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006930 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006931 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006932
Eli Friedmand72d16e2008-05-18 18:08:51 +00006933 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00006934 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006935 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006936 std::swap(PExp, IExp);
6937
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006938 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006939
Eli Friedmand72d16e2008-05-18 18:08:51 +00006940 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006941 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006942
Chris Lattnerb5f15622009-04-24 23:50:08 +00006943 // Check for arithmetic on pointers to incomplete types.
6944 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006945 if (getLangOptions().CPlusPlus) {
6946 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006947 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006948 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006949 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006950
6951 // GNU extension: arithmetic on pointer to void
6952 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006953 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006954 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006955 if (getLangOptions().CPlusPlus) {
6956 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006957 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006958 return QualType();
6959 }
6960
6961 // GNU extension: arithmetic on pointer to function
6962 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00006963 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006964 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006965 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006966 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006967 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006968 PExp->getType()->isObjCObjectPointerType()) &&
6969 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006970 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6971 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006972 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006973 return QualType();
6974 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006975 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006976 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006977 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6978 << PointeeTy << PExp->getSourceRange();
6979 return QualType();
6980 }
Mike Stump1eb44332009-09-09 15:08:12 +00006981
Eli Friedmanab3a8522009-03-28 01:22:36 +00006982 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006983 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006984 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00006985 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006986 if (LHSTy->isPromotableIntegerType())
6987 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006988 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006989 *CompLHSTy = LHSTy;
6990 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006991 return PExp->getType();
6992 }
6993 }
6994
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006995 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006996}
6997
Chris Lattnereca7be62008-04-07 05:30:13 +00006998// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006999QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00007000 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007001 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007002 QualType compType = CheckVectorOperands(Loc, lex, rex);
7003 if (CompLHSTy) *CompLHSTy = compType;
7004 return compType;
7005 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007006
Eli Friedmanab3a8522009-03-28 01:22:36 +00007007 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007008 if (lex.isInvalid() || rex.isInvalid())
7009 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007010
Chris Lattner6e4ab612007-12-09 21:53:25 +00007011 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007012
Chris Lattner6e4ab612007-12-09 21:53:25 +00007013 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00007014 if (lex.get()->getType()->isArithmeticType() &&
7015 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007016 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007017 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007018 }
Mike Stump1eb44332009-09-09 15:08:12 +00007019
Chris Lattner6e4ab612007-12-09 21:53:25 +00007020 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00007021 if (lex.get()->getType()->isAnyPointerType()) {
7022 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007023
Douglas Gregore7450f52009-03-24 19:52:54 +00007024 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00007025
Douglas Gregore7450f52009-03-24 19:52:54 +00007026 bool ComplainAboutVoid = false;
7027 Expr *ComplainAboutFunc = 0;
7028 if (lpointee->isVoidType()) {
7029 if (getLangOptions().CPlusPlus) {
7030 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007031 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007032 return QualType();
7033 }
7034
7035 // GNU C extension: arithmetic on pointer to void
7036 ComplainAboutVoid = true;
7037 } else if (lpointee->isFunctionType()) {
7038 if (getLangOptions().CPlusPlus) {
7039 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007040 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007041 return QualType();
7042 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007043
7044 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007045 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007046 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007047 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007048 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007049 << lex.get()->getSourceRange()
7050 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007051 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007052
Chris Lattnerb5f15622009-04-24 23:50:08 +00007053 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007054 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007055 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007056 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007057 return QualType();
7058 }
Mike Stump1eb44332009-09-09 15:08:12 +00007059
Chris Lattner6e4ab612007-12-09 21:53:25 +00007060 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007061 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007062 if (ComplainAboutVoid)
7063 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007064 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007065 if (ComplainAboutFunc)
7066 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007067 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007068 << ComplainAboutFunc->getSourceRange();
7069
John Wiegley429bb272011-04-08 18:41:53 +00007070 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7071 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007072 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007073
Chris Lattner6e4ab612007-12-09 21:53:25 +00007074 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007075 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007076 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077
Douglas Gregore7450f52009-03-24 19:52:54 +00007078 // RHS must be a completely-type object type.
7079 // Handle the GNU void* extension.
7080 if (rpointee->isVoidType()) {
7081 if (getLangOptions().CPlusPlus) {
7082 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007083 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007084 return QualType();
7085 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007086
Douglas Gregore7450f52009-03-24 19:52:54 +00007087 ComplainAboutVoid = true;
7088 } else if (rpointee->isFunctionType()) {
7089 if (getLangOptions().CPlusPlus) {
7090 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007091 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007092 return QualType();
7093 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007094
7095 // GNU extension: arithmetic on pointer to function
7096 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007097 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007098 } else if (!rpointee->isDependentType() &&
7099 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007100 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007101 << rex.get()->getSourceRange()
7102 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007103 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007104
Eli Friedman88d936b2009-05-16 13:54:38 +00007105 if (getLangOptions().CPlusPlus) {
7106 // Pointee types must be the same: C++ [expr.add]
7107 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7108 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007109 << lex.get()->getType() << rex.get()->getType()
7110 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007111 return QualType();
7112 }
7113 } else {
7114 // Pointee types must be compatible C99 6.5.6p3
7115 if (!Context.typesAreCompatible(
7116 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7117 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7118 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007119 << lex.get()->getType() << rex.get()->getType()
7120 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007121 return QualType();
7122 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007123 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007124
Douglas Gregore7450f52009-03-24 19:52:54 +00007125 if (ComplainAboutVoid)
7126 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007127 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007128 if (ComplainAboutFunc)
7129 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007130 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007131 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007132
John Wiegley429bb272011-04-08 18:41:53 +00007133 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007134 return Context.getPointerDiffType();
7135 }
7136 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007137
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007138 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007139}
7140
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007141static bool isScopedEnumerationType(QualType T) {
7142 if (const EnumType *ET = dyn_cast<EnumType>(T))
7143 return ET->getDecl()->isScoped();
7144 return false;
7145}
7146
John Wiegley429bb272011-04-08 18:41:53 +00007147static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007148 SourceLocation Loc, unsigned Opc,
7149 QualType LHSTy) {
7150 llvm::APSInt Right;
7151 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007152 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007153 return;
7154
7155 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007156 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007157 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007158 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007159 return;
7160 }
7161 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007162 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007163 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007164 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007165 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007166 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007167 return;
7168 }
7169 if (Opc != BO_Shl)
7170 return;
7171
7172 // When left shifting an ICE which is signed, we can check for overflow which
7173 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7174 // integers have defined behavior modulo one more than the maximum value
7175 // representable in the result type, so never warn for those.
7176 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007177 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007178 LHSTy->hasUnsignedIntegerRepresentation())
7179 return;
7180 llvm::APInt ResultBits =
7181 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7182 if (LeftBits.uge(ResultBits))
7183 return;
7184 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7185 Result = Result.shl(Right);
7186
7187 // If we are only missing a sign bit, this is less likely to result in actual
7188 // bugs -- if the result is cast back to an unsigned type, it will have the
7189 // expected value. Thus we place this behind a different warning that can be
7190 // turned off separately if needed.
7191 if (LeftBits == ResultBits - 1) {
7192 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7193 << Result.toString(10) << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007194 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007195 return;
7196 }
7197
7198 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7199 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007200 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007201}
7202
Chris Lattnereca7be62008-04-07 05:30:13 +00007203// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007204QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007205 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007206 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007207 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7208 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007209 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007210
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007211 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7212 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007213 if (isScopedEnumerationType(lex.get()->getType()) ||
7214 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007215 return InvalidOperands(Loc, lex, rex);
7216 }
7217
Nate Begeman2207d792009-10-25 02:26:48 +00007218 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007219 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007220 return CheckVectorOperands(Loc, lex, rex);
7221
Chris Lattnerca5eede2007-12-12 05:47:28 +00007222 // Shifts don't perform usual arithmetic conversions, they just do integer
7223 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007224
John McCall1bc80af2010-12-16 19:28:59 +00007225 // For the LHS, do usual unary conversions, but then reset them away
7226 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007227 ExprResult old_lex = lex;
7228 lex = UsualUnaryConversions(lex.take());
7229 if (lex.isInvalid())
7230 return QualType();
7231 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007232 if (isCompAssign) lex = old_lex;
7233
7234 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007235 rex = UsualUnaryConversions(rex.take());
7236 if (rex.isInvalid())
7237 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007238
Ryan Flynnd0439682009-08-07 16:20:20 +00007239 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007240 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007241
Chris Lattnerca5eede2007-12-12 05:47:28 +00007242 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007243 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007244}
7245
Chandler Carruth99919472010-07-10 12:30:03 +00007246static bool IsWithinTemplateSpecialization(Decl *D) {
7247 if (DeclContext *DC = D->getDeclContext()) {
7248 if (isa<ClassTemplateSpecializationDecl>(DC))
7249 return true;
7250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7251 return FD->isFunctionTemplateSpecialization();
7252 }
7253 return false;
7254}
7255
Douglas Gregor0c6db942009-05-04 06:07:12 +00007256// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007257QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007258 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007259 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007260
Chris Lattner02dd4b12009-12-05 05:40:13 +00007261 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007262 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007263 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007264
John Wiegley429bb272011-04-08 18:41:53 +00007265 QualType lType = lex.get()->getType();
7266 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007267
John Wiegley429bb272011-04-08 18:41:53 +00007268 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7269 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007270 QualType LHSStrippedType = LHSStripped->getType();
7271 QualType RHSStrippedType = RHSStripped->getType();
7272
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007273
7274
Chandler Carruth543cb652011-02-17 08:37:06 +00007275 // Two different enums will raise a warning when compared.
7276 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7277 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7278 if (LHSEnumType->getDecl()->getIdentifier() &&
7279 RHSEnumType->getDecl()->getIdentifier() &&
7280 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7281 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7282 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007283 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007284 }
7285 }
7286 }
7287
Douglas Gregor8eee1192010-06-22 22:12:46 +00007288 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007289 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007290 !lex.get()->getLocStart().isMacroID() &&
7291 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007292 // For non-floating point types, check for self-comparisons of the form
7293 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7294 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007295 //
7296 // NOTE: Don't warn about comparison expressions resulting from macro
7297 // expansion. Also don't warn about comparisons which are only self
7298 // comparisons within a template specialization. The warnings should catch
7299 // obvious cases in the definition of the template anyways. The idea is to
7300 // warn when the typed comparison operator will always evaluate to the same
7301 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007302 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007303 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007304 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007305 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007306 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007307 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007308 << (Opc == BO_EQ
7309 || Opc == BO_LE
7310 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007311 } else if (lType->isArrayType() && rType->isArrayType() &&
7312 !DRL->getDecl()->getType()->isReferenceType() &&
7313 !DRR->getDecl()->getType()->isReferenceType()) {
7314 // what is it always going to eval to?
7315 char always_evals_to;
7316 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007317 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007318 always_evals_to = 0; // false
7319 break;
John McCall2de56d12010-08-25 11:45:40 +00007320 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007321 always_evals_to = 1; // true
7322 break;
7323 default:
7324 // best we can say is 'a constant'
7325 always_evals_to = 2; // e.g. array1 <= array2
7326 break;
7327 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007328 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007329 << 1 // array
7330 << always_evals_to);
7331 }
7332 }
Chandler Carruth99919472010-07-10 12:30:03 +00007333 }
Mike Stump1eb44332009-09-09 15:08:12 +00007334
Chris Lattner55660a72009-03-08 19:39:53 +00007335 if (isa<CastExpr>(LHSStripped))
7336 LHSStripped = LHSStripped->IgnoreParenCasts();
7337 if (isa<CastExpr>(RHSStripped))
7338 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007339
Chris Lattner55660a72009-03-08 19:39:53 +00007340 // Warn about comparisons against a string constant (unless the other
7341 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007342 Expr *literalString = 0;
7343 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007344 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007345 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007346 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007347 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007348 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007349 } else if ((isa<StringLiteral>(RHSStripped) ||
7350 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007351 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007352 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007353 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007354 literalStringStripped = RHSStripped;
7355 }
7356
7357 if (literalString) {
7358 std::string resultComparison;
7359 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007360 case BO_LT: resultComparison = ") < 0"; break;
7361 case BO_GT: resultComparison = ") > 0"; break;
7362 case BO_LE: resultComparison = ") <= 0"; break;
7363 case BO_GE: resultComparison = ") >= 0"; break;
7364 case BO_EQ: resultComparison = ") == 0"; break;
7365 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007366 default: assert(false && "Invalid comparison operator");
7367 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007368
Ted Kremenek351ba912011-02-23 01:52:04 +00007369 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007370 PDiag(diag::warn_stringcompare)
7371 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007372 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007373 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007374 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007375
Douglas Gregord64fdd02010-06-08 19:50:34 +00007376 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007377 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007378 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007379 if (lex.isInvalid() || rex.isInvalid())
7380 return QualType();
7381 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007382 else {
John Wiegley429bb272011-04-08 18:41:53 +00007383 lex = UsualUnaryConversions(lex.take());
7384 if (lex.isInvalid())
7385 return QualType();
7386
7387 rex = UsualUnaryConversions(rex.take());
7388 if (rex.isInvalid())
7389 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007390 }
7391
John Wiegley429bb272011-04-08 18:41:53 +00007392 lType = lex.get()->getType();
7393 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007394
Douglas Gregor447b69e2008-11-19 03:25:36 +00007395 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007396 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007397
Chris Lattnera5937dd2007-08-26 01:18:55 +00007398 if (isRelational) {
7399 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007400 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007401 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007402 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007403 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007404 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007405
Chris Lattnera5937dd2007-08-26 01:18:55 +00007406 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007407 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007409
John Wiegley429bb272011-04-08 18:41:53 +00007410 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007411 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007412 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007413 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007414
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007415 // All of the following pointer-related warnings are GCC extensions, except
7416 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007417 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007418 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007419 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007420 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007421 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007422
Douglas Gregor0c6db942009-05-04 06:07:12 +00007423 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007424 if (LCanPointeeTy == RCanPointeeTy)
7425 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007426 if (!isRelational &&
7427 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7428 // Valid unless comparison between non-null pointer and function pointer
7429 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007430 // In a SFINAE context, we treat this as a hard error to maintain
7431 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007432 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7433 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007434 Diag(Loc,
7435 isSFINAEContext()?
7436 diag::err_typecheck_comparison_of_fptr_to_void
7437 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007438 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007439
7440 if (isSFINAEContext())
7441 return QualType();
7442
John Wiegley429bb272011-04-08 18:41:53 +00007443 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007444 return ResultTy;
7445 }
7446 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007447
Douglas Gregor0c6db942009-05-04 06:07:12 +00007448 // C++ [expr.rel]p2:
7449 // [...] Pointer conversions (4.10) and qualification
7450 // conversions (4.4) are performed on pointer operands (or on
7451 // a pointer operand and a null pointer constant) to bring
7452 // them to their composite pointer type. [...]
7453 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007454 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007455 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007456 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007457 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007458 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007459 if (T.isNull()) {
7460 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007461 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007462 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007463 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007464 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007465 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007466 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007467 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007468 }
7469
John Wiegley429bb272011-04-08 18:41:53 +00007470 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7471 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007472 return ResultTy;
7473 }
Eli Friedman3075e762009-08-23 00:27:47 +00007474 // C99 6.5.9p2 and C99 6.5.8p2
7475 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7476 RCanPointeeTy.getUnqualifiedType())) {
7477 // Valid unless a relational comparison of function pointers
7478 if (isRelational && LCanPointeeTy->isFunctionType()) {
7479 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007480 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007481 }
7482 } else if (!isRelational &&
7483 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7484 // Valid unless comparison between non-null pointer and function pointer
7485 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7486 && !LHSIsNull && !RHSIsNull) {
7487 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007488 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007489 }
7490 } else {
7491 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007492 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007493 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007494 }
John McCall34d6f932011-03-11 04:25:25 +00007495 if (LCanPointeeTy != RCanPointeeTy) {
7496 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007497 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007498 else
John Wiegley429bb272011-04-08 18:41:53 +00007499 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007500 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007501 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007502 }
Mike Stump1eb44332009-09-09 15:08:12 +00007503
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007504 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007505 // Comparison of nullptr_t with itself.
7506 if (lType->isNullPtrType() && rType->isNullPtrType())
7507 return ResultTy;
7508
Mike Stump1eb44332009-09-09 15:08:12 +00007509 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007510 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007511 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007512 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007513 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007514 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007515 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007516 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007517 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007518 return ResultTy;
7519 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007520 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007521 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007522 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007523 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007524 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007525 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007526 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007527 return ResultTy;
7528 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007529
7530 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007531 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007532 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7533 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007534 // In addition, pointers to members can be compared, or a pointer to
7535 // member and a null pointer constant. Pointer to member conversions
7536 // (4.11) and qualification conversions (4.4) are performed to bring
7537 // them to a common type. If one operand is a null pointer constant,
7538 // the common type is the type of the other operand. Otherwise, the
7539 // common type is a pointer to member type similar (4.4) to the type
7540 // of one of the operands, with a cv-qualification signature (4.4)
7541 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007542 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007543 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007544 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007545 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007546 if (T.isNull()) {
7547 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007548 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007549 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007550 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007551 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007552 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007553 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007554 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007555 }
Mike Stump1eb44332009-09-09 15:08:12 +00007556
John Wiegley429bb272011-04-08 18:41:53 +00007557 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7558 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007559 return ResultTy;
7560 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007561
7562 // Handle scoped enumeration types specifically, since they don't promote
7563 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007564 if (lex.get()->getType()->isEnumeralType() &&
7565 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007566 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007567 }
Mike Stump1eb44332009-09-09 15:08:12 +00007568
Steve Naroff1c7d0672008-09-04 15:10:53 +00007569 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007570 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007571 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7572 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007573
Steve Naroff1c7d0672008-09-04 15:10:53 +00007574 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007575 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007576 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007577 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007578 }
John Wiegley429bb272011-04-08 18:41:53 +00007579 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007580 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007581 }
John Wiegley429bb272011-04-08 18:41:53 +00007582
Steve Naroff59f53942008-09-28 01:11:11 +00007583 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007584 if (!isRelational
7585 && ((lType->isBlockPointerType() && rType->isPointerType())
7586 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007587 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007588 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007589 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007590 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007591 ->getPointeeType()->isVoidType())))
7592 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007593 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007594 }
John McCall34d6f932011-03-11 04:25:25 +00007595 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007596 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007597 else
John Wiegley429bb272011-04-08 18:41:53 +00007598 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007599 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007600 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007601
John McCall34d6f932011-03-11 04:25:25 +00007602 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7603 const PointerType *LPT = lType->getAs<PointerType>();
7604 const PointerType *RPT = rType->getAs<PointerType>();
7605 if (LPT || RPT) {
7606 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7607 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007608
Steve Naroffa8069f12008-11-17 19:49:16 +00007609 if (!LPtrToVoid && !RPtrToVoid &&
7610 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007611 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007612 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007613 }
John McCall34d6f932011-03-11 04:25:25 +00007614 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007615 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007616 else
John Wiegley429bb272011-04-08 18:41:53 +00007617 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007618 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007619 }
Steve Naroff14108da2009-07-10 23:34:53 +00007620 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007621 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007622 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007623 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007624 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007625 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007626 else
John Wiegley429bb272011-04-08 18:41:53 +00007627 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007628 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007629 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007630 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007631 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7632 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007633 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007634 bool isError = false;
7635 if ((LHSIsNull && lType->isIntegerType()) ||
7636 (RHSIsNull && rType->isIntegerType())) {
7637 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007638 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007639 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007640 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007641 else if (getLangOptions().CPlusPlus) {
7642 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7643 isError = true;
7644 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007645 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007646
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007647 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007648 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007649 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007650 if (isError)
7651 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007652 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007653
7654 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007655 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007656 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007657 else
John Wiegley429bb272011-04-08 18:41:53 +00007658 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007659 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007660 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007661 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007662
Steve Naroff39218df2008-09-04 16:56:14 +00007663 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007664 if (!isRelational && RHSIsNull
7665 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007666 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007667 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007668 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007669 if (!isRelational && LHSIsNull
7670 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007671 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007672 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007673 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007674
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007675 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007676}
7677
Nate Begemanbe2341d2008-07-14 18:02:46 +00007678/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007679/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007680/// like a scalar comparison, a vector comparison produces a vector of integer
7681/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007682QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007683 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007684 bool isRelational) {
7685 // Check to make sure we're operating on vectors of the same type and width,
7686 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007687 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007688 if (vType.isNull())
7689 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007690
John Wiegley429bb272011-04-08 18:41:53 +00007691 QualType lType = lex.get()->getType();
7692 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007693
Anton Yartsev7870b132011-03-27 15:36:07 +00007694 // If AltiVec, the comparison results in a numeric type, i.e.
7695 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007696 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007697 return Context.getLogicalOperationType();
7698
Nate Begemanbe2341d2008-07-14 18:02:46 +00007699 // For non-floating point types, check for self-comparisons of the form
7700 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7701 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007702 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007703 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7704 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007705 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007706 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007707 PDiag(diag::warn_comparison_always)
7708 << 0 // self-
7709 << 2 // "a constant"
7710 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007711 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007712
Nate Begemanbe2341d2008-07-14 18:02:46 +00007713 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007714 if (!isRelational && lType->hasFloatingRepresentation()) {
7715 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007716 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007717 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007718
Nate Begemanbe2341d2008-07-14 18:02:46 +00007719 // Return the type for the comparison, which is the same as vector type for
7720 // integer vectors, or an integer type of identical size and number of
7721 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007722 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007723 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007724
John McCall183700f2009-09-21 23:43:11 +00007725 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007726 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007727 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007728 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007729 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007730 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7731
Mike Stumpeed9cac2009-02-19 03:04:26 +00007732 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007733 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007734 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7735}
7736
Reid Spencer5f016e22007-07-11 17:01:13 +00007737inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007738 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7739 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7740 if (lex.get()->getType()->hasIntegerRepresentation() &&
7741 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00007742 return CheckVectorOperands(Loc, lex, rex);
7743
7744 return InvalidOperands(Loc, lex, rex);
7745 }
Steve Naroff90045e82007-07-13 23:32:42 +00007746
John Wiegley429bb272011-04-08 18:41:53 +00007747 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7748 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7749 if (lexResult.isInvalid() || rexResult.isInvalid())
7750 return QualType();
7751 lex = lexResult.take();
7752 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007753
John Wiegley429bb272011-04-08 18:41:53 +00007754 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7755 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007756 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007757 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007758}
7759
7760inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00007761 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007762
7763 // Diagnose cases where the user write a logical and/or but probably meant a
7764 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7765 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00007766 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7767 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007768 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007769 !Loc.isMacroID()) {
7770 // If the RHS can be constant folded, and if it constant folds to something
7771 // that isn't 0 or 1 (which indicate a potential logical operation that
7772 // happened to fold to true/false) then warn.
7773 Expr::EvalResult Result;
John Wiegley429bb272011-04-08 18:41:53 +00007774 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattnerb7690b42010-07-24 01:10:11 +00007775 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7776 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley429bb272011-04-08 18:41:53 +00007777 << rex.get()->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007778 << (Opc == BO_LAnd ? "&&" : "||")
7779 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007780 }
7781 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007782
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007783 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007784 lex = UsualUnaryConversions(lex.take());
7785 if (lex.isInvalid())
7786 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007787
John Wiegley429bb272011-04-08 18:41:53 +00007788 rex = UsualUnaryConversions(rex.take());
7789 if (rex.isInvalid())
7790 return QualType();
7791
7792 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007793 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007794
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007795 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007796 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007797
John McCall75f7c0f2010-06-04 00:29:51 +00007798 // The following is safe because we only use this method for
7799 // non-overloadable operands.
7800
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007801 // C++ [expr.log.and]p1
7802 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007803 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00007804 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7805 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007806 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007807 lex = move(lexRes);
7808
7809 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7810 if (rexRes.isInvalid())
7811 return InvalidOperands(Loc, lex, rex);
7812 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007813
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007814 // C++ [expr.log.and]p2
7815 // C++ [expr.log.or]p2
7816 // The result is a bool.
7817 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007818}
7819
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007820/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7821/// is a read-only property; return true if so. A readonly property expression
7822/// depends on various declarations and thus must be treated specially.
7823///
Mike Stump1eb44332009-09-09 15:08:12 +00007824static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007825 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7826 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007827 if (PropExpr->isImplicitProperty()) return false;
7828
7829 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7830 QualType BaseType = PropExpr->isSuperReceiver() ?
7831 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007832 PropExpr->getBase()->getType();
7833
John McCall12f78a62010-12-02 01:19:52 +00007834 if (const ObjCObjectPointerType *OPT =
7835 BaseType->getAsObjCInterfacePointerType())
7836 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7837 if (S.isPropertyReadonly(PDecl, IFace))
7838 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007839 }
7840 return false;
7841}
7842
Fariborz Jahanian14086762011-03-28 23:47:18 +00007843static bool IsConstProperty(Expr *E, Sema &S) {
7844 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7845 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7846 if (PropExpr->isImplicitProperty()) return false;
7847
7848 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7849 QualType T = PDecl->getType();
7850 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007851 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007852 CanQualType CT = S.Context.getCanonicalType(T);
7853 return CT.isConstQualified();
7854 }
7855 return false;
7856}
7857
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007858static bool IsReadonlyMessage(Expr *E, Sema &S) {
7859 if (E->getStmtClass() != Expr::MemberExprClass)
7860 return false;
7861 const MemberExpr *ME = cast<MemberExpr>(E);
7862 NamedDecl *Member = ME->getMemberDecl();
7863 if (isa<FieldDecl>(Member)) {
7864 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7865 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7866 return false;
7867 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7868 }
7869 return false;
7870}
7871
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007872/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7873/// emit an error and return true. If so, return false.
7874static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007875 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007876 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007877 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007878 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7879 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007880 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7881 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007882 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7883 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007884 if (IsLV == Expr::MLV_Valid)
7885 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007886
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007887 unsigned Diag = 0;
7888 bool NeedType = false;
7889 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007890 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007891 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007892 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7893 NeedType = true;
7894 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007895 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007896 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7897 NeedType = true;
7898 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007899 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007900 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7901 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007902 case Expr::MLV_Valid:
7903 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007904 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007905 case Expr::MLV_MemberFunction:
7906 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007907 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7908 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007909 case Expr::MLV_IncompleteType:
7910 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007911 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007912 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007913 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007914 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007915 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7916 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007917 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007918 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7919 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007920 case Expr::MLV_ReadonlyProperty:
7921 Diag = diag::error_readonly_property_assignment;
7922 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007923 case Expr::MLV_NoSetterProperty:
7924 Diag = diag::error_nosetter_property_assignment;
7925 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007926 case Expr::MLV_InvalidMessageExpression:
7927 Diag = diag::error_readonly_message_assignment;
7928 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007929 case Expr::MLV_SubObjCPropertySetting:
7930 Diag = diag::error_no_subobject_property_setting;
7931 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007932 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007933
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007934 SourceRange Assign;
7935 if (Loc != OrigLoc)
7936 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007937 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007938 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007939 else
Mike Stump1eb44332009-09-09 15:08:12 +00007940 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007941 return true;
7942}
7943
7944
7945
7946// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00007947QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007948 SourceLocation Loc,
7949 QualType CompoundType) {
7950 // Verify that LHS is a modifiable lvalue, and emit error if not.
7951 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007952 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007953
7954 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00007955 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007956 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007957 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007958 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007959 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007960 if (LHS->getObjectKind() == OK_ObjCProperty) {
7961 ExprResult LHSResult = Owned(LHS);
7962 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7963 if (LHSResult.isInvalid())
7964 return QualType();
7965 LHS = LHSResult.take();
7966 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007967 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007968 if (RHS.isInvalid())
7969 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007970 // Special case of NSObject attributes on c-style pointer types.
7971 if (ConvTy == IncompatiblePointer &&
7972 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007973 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007974 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007975 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007976 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007977
John McCallf89e55a2010-11-18 06:31:45 +00007978 if (ConvTy == Compatible &&
7979 getLangOptions().ObjCNonFragileABI &&
7980 LHSType->isObjCObjectType())
7981 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7982 << LHSType;
7983
Chris Lattner2c156472008-08-21 18:04:13 +00007984 // If the RHS is a unary plus or minus, check to see if they = and + are
7985 // right next to each other. If so, the user may have typo'd "x =+ 4"
7986 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007987 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7989 RHSCheck = ICE->getSubExpr();
7990 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007991 if ((UO->getOpcode() == UO_Plus ||
7992 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007993 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007994 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007995 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7996 // And there is a space or other character before the subexpr of the
7997 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007998 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7999 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008000 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00008001 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008002 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00008003 }
Chris Lattner2c156472008-08-21 18:04:13 +00008004 }
8005 } else {
8006 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00008007 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008008 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008009
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008010 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00008011 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00008012 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008013
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00008014 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00008015 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008016 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008017
Reid Spencer5f016e22007-07-11 17:01:13 +00008018 // C99 6.5.16p3: The type of an assignment expression is the type of the
8019 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00008020 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00008021 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8022 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008023 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008024 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00008025 return (getLangOptions().CPlusPlus
8026 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008027}
8028
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008029// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008030static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008031 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00008032 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008033
John McCallfb8721c2011-04-10 19:13:55 +00008034 LHS = S.CheckPlaceholderExpr(LHS.take());
8035 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008036 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008037 return QualType();
8038
John McCallcf2e5062010-10-12 07:14:40 +00008039 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8040 // operands, but not unary promotions.
8041 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008042
John McCallf6a16482010-12-04 03:47:34 +00008043 // So we treat the LHS as a ignored value, and in C++ we allow the
8044 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008045 LHS = S.IgnoredValueConversions(LHS.take());
8046 if (LHS.isInvalid())
8047 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008048
8049 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008050 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8051 if (RHS.isInvalid())
8052 return QualType();
8053 if (!RHS.get()->getType()->isVoidType())
8054 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008055 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008056
John Wiegley429bb272011-04-08 18:41:53 +00008057 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008058}
8059
Steve Naroff49b45262007-07-13 16:58:59 +00008060/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8061/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008062static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8063 ExprValueKind &VK,
8064 SourceLocation OpLoc,
8065 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008066 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008067 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008068
Chris Lattner3528d352008-11-21 07:05:48 +00008069 QualType ResType = Op->getType();
8070 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008071
John McCall09431682010-11-18 19:01:18 +00008072 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008073 // Decrement of bool is not allowed.
8074 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008075 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008076 return QualType();
8077 }
8078 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008079 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008080 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008081 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008082 } else if (ResType->isAnyPointerType()) {
8083 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008084
Chris Lattner3528d352008-11-21 07:05:48 +00008085 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008086 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008087 if (S.getLangOptions().CPlusPlus) {
8088 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008089 << Op->getSourceRange();
8090 return QualType();
8091 }
8092
8093 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008094 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008095 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008096 if (S.getLangOptions().CPlusPlus) {
8097 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008098 << Op->getType() << Op->getSourceRange();
8099 return QualType();
8100 }
8101
John McCall09431682010-11-18 19:01:18 +00008102 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008103 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008104 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8105 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008106 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008107 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008108 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008109 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008110 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8111 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008112 << PointeeTy << Op->getSourceRange();
8113 return QualType();
8114 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008115 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008116 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008117 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008118 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008119 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008120 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008121 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008122 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8123 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008124 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8125 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008126 } else {
John McCall09431682010-11-18 19:01:18 +00008127 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008128 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008129 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008130 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008131 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008132 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008133 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008134 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008135 // In C++, a prefix increment is the same type as the operand. Otherwise
8136 // (in C or with postfix), the increment is the unqualified type of the
8137 // operand.
John McCall09431682010-11-18 19:01:18 +00008138 if (isPrefix && S.getLangOptions().CPlusPlus) {
8139 VK = VK_LValue;
8140 return ResType;
8141 } else {
8142 VK = VK_RValue;
8143 return ResType.getUnqualifiedType();
8144 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008145}
8146
John Wiegley429bb272011-04-08 18:41:53 +00008147ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008148 assert(E->getValueKind() == VK_LValue &&
8149 E->getObjectKind() == OK_ObjCProperty);
8150 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8151
8152 ExprValueKind VK = VK_RValue;
8153 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008154 if (const ObjCMethodDecl *GetterMethod =
8155 PRE->getImplicitPropertyGetter()) {
8156 QualType Result = GetterMethod->getResultType();
8157 VK = Expr::getValueKindForType(Result);
8158 }
8159 else {
8160 Diag(PRE->getLocation(), diag::err_getter_not_found)
8161 << PRE->getBase()->getType();
8162 }
John McCallf6a16482010-12-04 03:47:34 +00008163 }
8164
8165 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8166 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008167
8168 ExprResult Result = MaybeBindToTemporary(E);
8169 if (!Result.isInvalid())
8170 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008171
8172 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008173}
8174
John Wiegley429bb272011-04-08 18:41:53 +00008175void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8176 assert(LHS.get()->getValueKind() == VK_LValue &&
8177 LHS.get()->getObjectKind() == OK_ObjCProperty);
8178 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008179
John Wiegley429bb272011-04-08 18:41:53 +00008180 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008181 // If using property-dot syntax notation for assignment, and there is a
8182 // setter, RHS expression is being passed to the setter argument. So,
8183 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008184 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008185 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8186 LHSTy = (*P)->getType();
8187
8188 // Otherwise, if the getter returns an l-value, just call that.
8189 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008190 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008191 ExprValueKind VK = Expr::getValueKindForType(Result);
8192 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008193 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8194 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008195 return;
John McCall12f78a62010-12-02 01:19:52 +00008196 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008197 }
John McCallf6a16482010-12-04 03:47:34 +00008198 }
8199
8200 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008201 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008202 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008203 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008204 if (!ArgE.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008205 RHS = ArgE;
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008206 }
8207}
8208
8209
Anders Carlsson369dee42008-02-01 07:15:58 +00008210/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008211/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008212/// where the declaration is needed for type checking. We only need to
8213/// handle cases when the expression references a function designator
8214/// or is an lvalue. Here are some examples:
8215/// - &(x) => x
8216/// - &*****f => f for f a function designator.
8217/// - &s.xx => s
8218/// - &s.zz[1].yy -> s, if zz is an array
8219/// - *(x + 1) -> x, if x is an array
8220/// - &"123"[2] -> 0
8221/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008222static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008223 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008224 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008225 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008226 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008227 // If this is an arrow operator, the address is an offset from
8228 // the base's value, so the object the base refers to is
8229 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008230 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008231 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008232 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008233 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008234 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008235 // FIXME: This code shouldn't be necessary! We should catch the implicit
8236 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008237 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8238 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8239 if (ICE->getSubExpr()->getType()->isArrayType())
8240 return getPrimaryDecl(ICE->getSubExpr());
8241 }
8242 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008243 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008244 case Stmt::UnaryOperatorClass: {
8245 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008246
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008247 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008248 case UO_Real:
8249 case UO_Imag:
8250 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008251 return getPrimaryDecl(UO->getSubExpr());
8252 default:
8253 return 0;
8254 }
8255 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008256 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008257 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008258 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008259 // If the result of an implicit cast is an l-value, we care about
8260 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008261 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008262 default:
8263 return 0;
8264 }
8265}
8266
8267/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008268/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008269/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008270/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008271/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008272/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008273/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008274static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8275 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008276 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008277 return S.Context.DependentTy;
8278 if (OrigOp->getType() == S.Context.OverloadTy)
8279 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008280 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8281 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00008282 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8283 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8284 << OrigOp->getSourceRange();
8285 return QualType();
8286 }
John McCall9c72c602010-08-27 09:08:28 +00008287
John McCall755d8492011-04-12 00:42:48 +00008288 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008289
John McCall9c72c602010-08-27 09:08:28 +00008290 // Make sure to ignore parentheses in subsequent checks
8291 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008292
John McCall09431682010-11-18 19:01:18 +00008293 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008294 // Implement C99-only parts of addressof rules.
8295 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008296 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008297 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8298 // (assuming the deref expression is valid).
8299 return uOp->getSubExpr()->getType();
8300 }
8301 // Technically, there should be a check for array subscript
8302 // expressions here, but the result of one is always an lvalue anyway.
8303 }
John McCall5808ce42011-02-03 08:15:49 +00008304 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008305 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008306
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008307 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008308 bool sfinae = S.isSFINAEContext();
8309 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8310 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008311 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008312 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008313 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008314 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008315 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008316 } else if (lval == Expr::LV_MemberFunction) {
8317 // If it's an instance method, make a member pointer.
8318 // The expression must have exactly the form &A::foo.
8319
8320 // If the underlying expression isn't a decl ref, give up.
8321 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008322 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008323 << OrigOp->getSourceRange();
8324 return QualType();
8325 }
8326 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8327 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8328
8329 // The id-expression was parenthesized.
8330 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008331 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008332 << OrigOp->getSourceRange();
8333
8334 // The method was named without a qualifier.
8335 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008336 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008337 << op->getSourceRange();
8338 }
8339
John McCall09431682010-11-18 19:01:18 +00008340 return S.Context.getMemberPointerType(op->getType(),
8341 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008342 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008343 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008344 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008345 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008346 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008347 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008348 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008349 return QualType();
8350 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008351 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008352 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008353 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008354 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008355 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008356 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008357 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008358 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008359 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008360 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008361 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008362 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008363 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008364 << "property expression" << op->getSourceRange();
8365 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008366 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008367 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008368 // with the register storage-class specifier.
8369 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008370 // in C++ it is not error to take address of a register
8371 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008372 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008373 !S.getLangOptions().CPlusPlus) {
8374 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008375 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008376 return QualType();
8377 }
John McCallba135432009-11-21 08:51:07 +00008378 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008379 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008380 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008381 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008382 // Could be a pointer to member, though, if there is an explicit
8383 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008384 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008385 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008386 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008387 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008388 S.Diag(OpLoc,
8389 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008390 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008391 return QualType();
8392 }
Mike Stump1eb44332009-09-09 15:08:12 +00008393
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008394 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8395 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008396 return S.Context.getMemberPointerType(op->getType(),
8397 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008398 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008399 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008400 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008401 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008402 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008403
Eli Friedman441cf102009-05-16 23:27:50 +00008404 if (lval == Expr::LV_IncompleteVoidType) {
8405 // Taking the address of a void variable is technically illegal, but we
8406 // allow it in cases which are otherwise valid.
8407 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008408 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008409 }
8410
Reid Spencer5f016e22007-07-11 17:01:13 +00008411 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008412 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008413 return S.Context.getObjCObjectPointerType(op->getType());
8414 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008415}
8416
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008417/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008418static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8419 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008420 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008421 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008422
John Wiegley429bb272011-04-08 18:41:53 +00008423 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8424 if (ConvResult.isInvalid())
8425 return QualType();
8426 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008427 QualType OpTy = Op->getType();
8428 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008429
8430 if (isa<CXXReinterpretCastExpr>(Op)) {
8431 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8432 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8433 Op->getSourceRange());
8434 }
8435
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008436 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8437 // is an incomplete type or void. It would be possible to warn about
8438 // dereferencing a void pointer, but it's completely well-defined, and such a
8439 // warning is unlikely to catch any mistakes.
8440 if (const PointerType *PT = OpTy->getAs<PointerType>())
8441 Result = PT->getPointeeType();
8442 else if (const ObjCObjectPointerType *OPT =
8443 OpTy->getAs<ObjCObjectPointerType>())
8444 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008445 else {
John McCallfb8721c2011-04-10 19:13:55 +00008446 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008447 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008448 if (PR.take() != Op)
8449 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008450 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008451
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008452 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008453 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008454 << OpTy << Op->getSourceRange();
8455 return QualType();
8456 }
John McCall09431682010-11-18 19:01:18 +00008457
8458 // Dereferences are usually l-values...
8459 VK = VK_LValue;
8460
8461 // ...except that certain expressions are never l-values in C.
8462 if (!S.getLangOptions().CPlusPlus &&
8463 IsCForbiddenLValueType(S.Context, Result))
8464 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008465
8466 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008467}
8468
John McCall2de56d12010-08-25 11:45:40 +00008469static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008470 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008471 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008472 switch (Kind) {
8473 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008474 case tok::periodstar: Opc = BO_PtrMemD; break;
8475 case tok::arrowstar: Opc = BO_PtrMemI; break;
8476 case tok::star: Opc = BO_Mul; break;
8477 case tok::slash: Opc = BO_Div; break;
8478 case tok::percent: Opc = BO_Rem; break;
8479 case tok::plus: Opc = BO_Add; break;
8480 case tok::minus: Opc = BO_Sub; break;
8481 case tok::lessless: Opc = BO_Shl; break;
8482 case tok::greatergreater: Opc = BO_Shr; break;
8483 case tok::lessequal: Opc = BO_LE; break;
8484 case tok::less: Opc = BO_LT; break;
8485 case tok::greaterequal: Opc = BO_GE; break;
8486 case tok::greater: Opc = BO_GT; break;
8487 case tok::exclaimequal: Opc = BO_NE; break;
8488 case tok::equalequal: Opc = BO_EQ; break;
8489 case tok::amp: Opc = BO_And; break;
8490 case tok::caret: Opc = BO_Xor; break;
8491 case tok::pipe: Opc = BO_Or; break;
8492 case tok::ampamp: Opc = BO_LAnd; break;
8493 case tok::pipepipe: Opc = BO_LOr; break;
8494 case tok::equal: Opc = BO_Assign; break;
8495 case tok::starequal: Opc = BO_MulAssign; break;
8496 case tok::slashequal: Opc = BO_DivAssign; break;
8497 case tok::percentequal: Opc = BO_RemAssign; break;
8498 case tok::plusequal: Opc = BO_AddAssign; break;
8499 case tok::minusequal: Opc = BO_SubAssign; break;
8500 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8501 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8502 case tok::ampequal: Opc = BO_AndAssign; break;
8503 case tok::caretequal: Opc = BO_XorAssign; break;
8504 case tok::pipeequal: Opc = BO_OrAssign; break;
8505 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008506 }
8507 return Opc;
8508}
8509
John McCall2de56d12010-08-25 11:45:40 +00008510static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008511 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008512 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008513 switch (Kind) {
8514 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008515 case tok::plusplus: Opc = UO_PreInc; break;
8516 case tok::minusminus: Opc = UO_PreDec; break;
8517 case tok::amp: Opc = UO_AddrOf; break;
8518 case tok::star: Opc = UO_Deref; break;
8519 case tok::plus: Opc = UO_Plus; break;
8520 case tok::minus: Opc = UO_Minus; break;
8521 case tok::tilde: Opc = UO_Not; break;
8522 case tok::exclaim: Opc = UO_LNot; break;
8523 case tok::kw___real: Opc = UO_Real; break;
8524 case tok::kw___imag: Opc = UO_Imag; break;
8525 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008526 }
8527 return Opc;
8528}
8529
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008530/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8531/// This warning is only emitted for builtin assignment operations. It is also
8532/// suppressed in the event of macro expansions.
8533static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8534 SourceLocation OpLoc) {
8535 if (!S.ActiveTemplateInstantiations.empty())
8536 return;
8537 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8538 return;
8539 lhs = lhs->IgnoreParenImpCasts();
8540 rhs = rhs->IgnoreParenImpCasts();
8541 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8542 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8543 if (!LeftDeclRef || !RightDeclRef ||
8544 LeftDeclRef->getLocation().isMacroID() ||
8545 RightDeclRef->getLocation().isMacroID())
8546 return;
8547 const ValueDecl *LeftDecl =
8548 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8549 const ValueDecl *RightDecl =
8550 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8551 if (LeftDecl != RightDecl)
8552 return;
8553 if (LeftDecl->getType().isVolatileQualified())
8554 return;
8555 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8556 if (RefTy->getPointeeType().isVolatileQualified())
8557 return;
8558
8559 S.Diag(OpLoc, diag::warn_self_assignment)
8560 << LeftDeclRef->getType()
8561 << lhs->getSourceRange() << rhs->getSourceRange();
8562}
8563
Douglas Gregoreaebc752008-11-06 23:29:22 +00008564/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8565/// operator @p Opc at location @c TokLoc. This routine only supports
8566/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008567ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008568 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008569 Expr *lhsExpr, Expr *rhsExpr) {
8570 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008571 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008572 // The following two variables are used for compound assignment operators
8573 QualType CompLHSTy; // Type of LHS after promotions for computation
8574 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008575 ExprValueKind VK = VK_RValue;
8576 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008577
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008578 // Check if a 'foo<int>' involved in a binary op, identifies a single
8579 // function unambiguously (i.e. an lvalue ala 13.4)
8580 // But since an assignment can trigger target based overload, exclude it in
8581 // our blind search. i.e:
8582 // template<class T> void f(); template<class T, class U> void f(U);
8583 // f<int> == 0; // resolve f<int> blindly
8584 // void (*p)(int); p = f<int>; // resolve f<int> using target
8585 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008586 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008587 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008588 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008589
John McCallfb8721c2011-04-10 19:13:55 +00008590 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008591 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008592 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008593 }
8594
Douglas Gregoreaebc752008-11-06 23:29:22 +00008595 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008596 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008597 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008598 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008599 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8600 VK = lhs.get()->getValueKind();
8601 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008602 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008603 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008604 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008605 break;
John McCall2de56d12010-08-25 11:45:40 +00008606 case BO_PtrMemD:
8607 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008608 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008609 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008610 break;
John McCall2de56d12010-08-25 11:45:40 +00008611 case BO_Mul:
8612 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008613 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008614 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008615 break;
John McCall2de56d12010-08-25 11:45:40 +00008616 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008617 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8618 break;
John McCall2de56d12010-08-25 11:45:40 +00008619 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008620 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8621 break;
John McCall2de56d12010-08-25 11:45:40 +00008622 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008623 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8624 break;
John McCall2de56d12010-08-25 11:45:40 +00008625 case BO_Shl:
8626 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008627 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008628 break;
John McCall2de56d12010-08-25 11:45:40 +00008629 case BO_LE:
8630 case BO_LT:
8631 case BO_GE:
8632 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008633 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008634 break;
John McCall2de56d12010-08-25 11:45:40 +00008635 case BO_EQ:
8636 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008637 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008638 break;
John McCall2de56d12010-08-25 11:45:40 +00008639 case BO_And:
8640 case BO_Xor:
8641 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008642 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8643 break;
John McCall2de56d12010-08-25 11:45:40 +00008644 case BO_LAnd:
8645 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008646 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008647 break;
John McCall2de56d12010-08-25 11:45:40 +00008648 case BO_MulAssign:
8649 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008650 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008651 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008652 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008653 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8654 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008655 break;
John McCall2de56d12010-08-25 11:45:40 +00008656 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008657 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8658 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008659 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8660 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008661 break;
John McCall2de56d12010-08-25 11:45:40 +00008662 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008663 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008664 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8665 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008666 break;
John McCall2de56d12010-08-25 11:45:40 +00008667 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008668 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008669 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8670 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008671 break;
John McCall2de56d12010-08-25 11:45:40 +00008672 case BO_ShlAssign:
8673 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008674 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008675 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008676 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8677 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008678 break;
John McCall2de56d12010-08-25 11:45:40 +00008679 case BO_AndAssign:
8680 case BO_XorAssign:
8681 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008682 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8683 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008684 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8685 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008686 break;
John McCall2de56d12010-08-25 11:45:40 +00008687 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008688 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008689 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8690 VK = rhs.get()->getValueKind();
8691 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008692 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008693 break;
8694 }
John Wiegley429bb272011-04-08 18:41:53 +00008695 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008696 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008697 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008698 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8699 ResultTy, VK, OK, OpLoc));
8700 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008701 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00008702 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008703 }
John Wiegley429bb272011-04-08 18:41:53 +00008704 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8705 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008706 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008707}
8708
Sebastian Redlaee3c932009-10-27 12:10:02 +00008709/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8710/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008711static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8712 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008713 const PartialDiagnostic &FirstNote,
8714 SourceRange FirstParenRange,
8715 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008716 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008717 Self.Diag(Loc, PD);
8718
8719 if (!FirstNote.getDiagID())
8720 return;
8721
8722 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8723 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8724 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008725 return;
8726 }
8727
Douglas Gregor55b38842010-04-14 16:09:52 +00008728 Self.Diag(Loc, FirstNote)
8729 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008730 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008731
Douglas Gregor55b38842010-04-14 16:09:52 +00008732 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008733 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008734
Douglas Gregor827feec2010-01-08 00:20:23 +00008735 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8736 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8737 // We can't display the parentheses, so just dig the
8738 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008739 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008740 return;
8741 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008742
Douglas Gregor55b38842010-04-14 16:09:52 +00008743 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008744 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8745 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008746}
8747
Sebastian Redlaee3c932009-10-27 12:10:02 +00008748/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8749/// operators are mixed in a way that suggests that the programmer forgot that
8750/// comparison operators have higher precedence. The most typical example of
8751/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008752static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008753 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008754 typedef BinaryOperator BinOp;
8755 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8756 rhsopc = static_cast<BinOp::Opcode>(-1);
8757 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008758 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008759 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008760 rhsopc = BO->getOpcode();
8761
8762 // Subs are not binary operators.
8763 if (lhsopc == -1 && rhsopc == -1)
8764 return;
8765
8766 // Bitwise operations are sometimes used as eager logical ops.
8767 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008768 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8769 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008770 return;
8771
Sebastian Redlaee3c932009-10-27 12:10:02 +00008772 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008773 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008774 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008775 << SourceRange(lhs->getLocStart(), OpLoc)
8776 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008777 Self.PDiag(diag::note_precedence_bitwise_silence)
8778 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008779 lhs->getSourceRange(),
8780 Self.PDiag(diag::note_precedence_bitwise_first)
8781 << BinOp::getOpcodeStr(Opc),
8782 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redlaee3c932009-10-27 12:10:02 +00008783 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008784 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008785 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008786 << SourceRange(OpLoc, rhs->getLocEnd())
8787 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008788 Self.PDiag(diag::note_precedence_bitwise_silence)
8789 << BinOp::getOpcodeStr(rhsopc),
8790 rhs->getSourceRange(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008791 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008792 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008793 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008794}
8795
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008796/// \brief It accepts a '&&' expr that is inside a '||' one.
8797/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8798/// in parentheses.
8799static void
8800EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008801 BinaryOperator *Bop) {
8802 assert(Bop->getOpcode() == BO_LAnd);
8803 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008804 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008805 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008806 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008807 Bop->getSourceRange(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008808 Self.PDiag(0), SourceRange());
8809}
8810
8811/// \brief Returns true if the given expression can be evaluated as a constant
8812/// 'true'.
8813static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8814 bool Res;
8815 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8816}
8817
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008818/// \brief Returns true if the given expression can be evaluated as a constant
8819/// 'false'.
8820static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8821 bool Res;
8822 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8823}
8824
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008825/// \brief Look for '&&' in the left hand of a '||' expr.
8826static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008827 Expr *OrLHS, Expr *OrRHS) {
8828 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008829 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008830 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8831 if (EvaluatesAsFalse(S, OrRHS))
8832 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008833 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8834 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8835 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8836 } else if (Bop->getOpcode() == BO_LOr) {
8837 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8838 // If it's "a || b && 1 || c" we didn't warn earlier for
8839 // "a || b && 1", but warn now.
8840 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8841 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8842 }
8843 }
8844 }
8845}
8846
8847/// \brief Look for '&&' in the right hand of a '||' expr.
8848static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008849 Expr *OrLHS, Expr *OrRHS) {
8850 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008851 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008852 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8853 if (EvaluatesAsFalse(S, OrLHS))
8854 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008855 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8856 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8857 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008858 }
8859 }
8860}
8861
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008862/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008863/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008864static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008865 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008866 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008867 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008868 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8869
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008870 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8871 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008872 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008873 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8874 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008875 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008876}
8877
Reid Spencer5f016e22007-07-11 17:01:13 +00008878// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008879ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008880 tok::TokenKind Kind,
8881 Expr *lhs, Expr *rhs) {
8882 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008883 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8884 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008885
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008886 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8887 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8888
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008889 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8890}
8891
John McCall60d7b3a2010-08-24 06:29:42 +00008892ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008893 BinaryOperatorKind Opc,
8894 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008895 if (getLangOptions().CPlusPlus) {
8896 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008897
John McCall01b2e4e2010-12-06 05:26:58 +00008898 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8899 UseBuiltinOperator = false;
8900 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8901 UseBuiltinOperator = true;
8902 } else {
8903 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8904 !rhs->getType()->isOverloadableType();
8905 }
8906
8907 if (!UseBuiltinOperator) {
8908 // Find all of the overloaded operators visible from this
8909 // point. We perform both an operator-name lookup from the local
8910 // scope and an argument-dependent lookup based on the types of
8911 // the arguments.
8912 UnresolvedSet<16> Functions;
8913 OverloadedOperatorKind OverOp
8914 = BinaryOperator::getOverloadedOperator(Opc);
8915 if (S && OverOp != OO_None)
8916 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8917 Functions);
8918
8919 // Build the (potentially-overloaded, potentially-dependent)
8920 // binary operation.
8921 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8922 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008923 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008924
Douglas Gregoreaebc752008-11-06 23:29:22 +00008925 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008926 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008927}
8928
John McCall60d7b3a2010-08-24 06:29:42 +00008929ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008930 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008931 Expr *InputExpr) {
8932 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008933 ExprValueKind VK = VK_RValue;
8934 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008935 QualType resultType;
8936 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008937 case UO_PreInc:
8938 case UO_PreDec:
8939 case UO_PostInc:
8940 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008941 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008942 Opc == UO_PreInc ||
8943 Opc == UO_PostInc,
8944 Opc == UO_PreInc ||
8945 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008946 break;
John McCall2de56d12010-08-25 11:45:40 +00008947 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008948 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008949 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008950 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008951 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008952 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008953 Input = move(resolved);
8954 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8955 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008956 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008957 }
John McCall2de56d12010-08-25 11:45:40 +00008958 case UO_Plus:
8959 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008960 Input = UsualUnaryConversions(Input.take());
8961 if (Input.isInvalid()) return ExprError();
8962 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008963 if (resultType->isDependentType())
8964 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008965 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8966 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008967 break;
8968 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8969 resultType->isEnumeralType())
8970 break;
8971 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008972 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008973 resultType->isPointerType())
8974 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008975 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008976 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008977 if (Input.isInvalid()) return ExprError();
8978 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008979 }
Douglas Gregor74253732008-11-19 15:42:04 +00008980
Sebastian Redl0eb23302009-01-19 00:08:26 +00008981 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008982 << resultType << Input.get()->getSourceRange());
8983
John McCall2de56d12010-08-25 11:45:40 +00008984 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008985 Input = UsualUnaryConversions(Input.take());
8986 if (Input.isInvalid()) return ExprError();
8987 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008988 if (resultType->isDependentType())
8989 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008990 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8991 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8992 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008993 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008994 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008995 else if (resultType->hasIntegerRepresentation())
8996 break;
8997 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008998 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008999 if (Input.isInvalid()) return ExprError();
9000 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009001 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009002 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009003 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009004 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009005 break;
John Wiegley429bb272011-04-08 18:41:53 +00009006
John McCall2de56d12010-08-25 11:45:40 +00009007 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00009008 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00009009 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9010 if (Input.isInvalid()) return ExprError();
9011 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009012 if (resultType->isDependentType())
9013 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00009014 if (resultType->isScalarType()) {
9015 // C99 6.5.3.3p1: ok, fallthrough;
9016 if (Context.getLangOptions().CPlusPlus) {
9017 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9018 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00009019 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9020 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00009021 }
John McCall2cd11fe2010-10-12 02:09:17 +00009022 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009023 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009024 if (Input.isInvalid()) return ExprError();
9025 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009026 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009027 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009028 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009029 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009030
Reid Spencer5f016e22007-07-11 17:01:13 +00009031 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009032 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009033 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009034 break;
John McCall2de56d12010-08-25 11:45:40 +00009035 case UO_Real:
9036 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009037 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00009038 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009039 if (Input.isInvalid()) return ExprError();
9040 if (Input.get()->getValueKind() != VK_RValue &&
9041 Input.get()->getObjectKind() == OK_Ordinary)
9042 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009043 break;
John McCall2de56d12010-08-25 11:45:40 +00009044 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009045 resultType = Input.get()->getType();
9046 VK = Input.get()->getValueKind();
9047 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009048 break;
9049 }
John Wiegley429bb272011-04-08 18:41:53 +00009050 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009051 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009052
John Wiegley429bb272011-04-08 18:41:53 +00009053 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009054 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009055}
9056
John McCall60d7b3a2010-08-24 06:29:42 +00009057ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009058 UnaryOperatorKind Opc,
9059 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009060 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009061 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009062 // Find all of the overloaded operators visible from this
9063 // point. We perform both an operator-name lookup from the local
9064 // scope and an argument-dependent lookup based on the types of
9065 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009066 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009067 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009068 if (S && OverOp != OO_None)
9069 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9070 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009071
John McCall9ae2f072010-08-23 23:25:46 +00009072 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009073 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009074
John McCall9ae2f072010-08-23 23:25:46 +00009075 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009076}
9077
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009078// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009079ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009080 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009081 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009082}
9083
Steve Naroff1b273c42007-09-16 14:56:35 +00009084/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009085ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009086 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009087 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009088 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009089 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009090 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009091}
9092
John McCall60d7b3a2010-08-24 06:29:42 +00009093ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009094Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009095 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009096 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9097 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9098
Douglas Gregordd8f5692010-03-10 04:54:39 +00009099 bool isFileScope
9100 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009101 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009102 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009103
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009104 // FIXME: there are a variety of strange constraints to enforce here, for
9105 // example, it is not possible to goto into a stmt expression apparently.
9106 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009107
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009108 // If there are sub stmts in the compound stmt, take the type of the last one
9109 // as the type of the stmtexpr.
9110 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009111 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009112 if (!Compound->body_empty()) {
9113 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009114 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009115 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009116 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9117 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009118 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009119 }
John Wiegley429bb272011-04-08 18:41:53 +00009120 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009121 // Do function/array conversion on the last expression, but not
9122 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009123 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9124 if (LastExpr.isInvalid())
9125 return ExprError();
9126 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009127
John Wiegley429bb272011-04-08 18:41:53 +00009128 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9129 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009130 InitializedEntity::InitializeResult(LPLoc,
9131 Ty,
9132 false),
9133 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00009134 LastExpr);
9135 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009136 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009137 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009138 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009139 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009140 else
John Wiegley429bb272011-04-08 18:41:53 +00009141 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009142 StmtExprMayBindToTemp = true;
9143 }
9144 }
9145 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009146 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009147
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009148 // FIXME: Check that expression type is complete/non-abstract; statement
9149 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009150 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9151 if (StmtExprMayBindToTemp)
9152 return MaybeBindToTemporary(ResStmtExpr);
9153 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009154}
Steve Naroffd34e9152007-08-01 22:05:33 +00009155
John McCall60d7b3a2010-08-24 06:29:42 +00009156ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009157 TypeSourceInfo *TInfo,
9158 OffsetOfComponent *CompPtr,
9159 unsigned NumComponents,
9160 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009161 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009162 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009163 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009164
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009165 // We must have at least one component that refers to the type, and the first
9166 // one is known to be a field designator. Verify that the ArgTy represents
9167 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009168 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009169 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9170 << ArgTy << TypeRange);
9171
9172 // Type must be complete per C99 7.17p3 because a declaring a variable
9173 // with an incomplete type would be ill-formed.
9174 if (!Dependent
9175 && RequireCompleteType(BuiltinLoc, ArgTy,
9176 PDiag(diag::err_offsetof_incomplete_type)
9177 << TypeRange))
9178 return ExprError();
9179
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009180 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9181 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009182 // FIXME: This diagnostic isn't actually visible because the location is in
9183 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009184 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009185 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9186 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009187
9188 bool DidWarnAboutNonPOD = false;
9189 QualType CurrentType = ArgTy;
9190 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9191 llvm::SmallVector<OffsetOfNode, 4> Comps;
9192 llvm::SmallVector<Expr*, 4> Exprs;
9193 for (unsigned i = 0; i != NumComponents; ++i) {
9194 const OffsetOfComponent &OC = CompPtr[i];
9195 if (OC.isBrackets) {
9196 // Offset of an array sub-field. TODO: Should we allow vector elements?
9197 if (!CurrentType->isDependentType()) {
9198 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9199 if(!AT)
9200 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9201 << CurrentType);
9202 CurrentType = AT->getElementType();
9203 } else
9204 CurrentType = Context.DependentTy;
9205
9206 // The expression must be an integral expression.
9207 // FIXME: An integral constant expression?
9208 Expr *Idx = static_cast<Expr*>(OC.U.E);
9209 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9210 !Idx->getType()->isIntegerType())
9211 return ExprError(Diag(Idx->getLocStart(),
9212 diag::err_typecheck_subscript_not_integer)
9213 << Idx->getSourceRange());
9214
9215 // Record this array index.
9216 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9217 Exprs.push_back(Idx);
9218 continue;
9219 }
9220
9221 // Offset of a field.
9222 if (CurrentType->isDependentType()) {
9223 // We have the offset of a field, but we can't look into the dependent
9224 // type. Just record the identifier of the field.
9225 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9226 CurrentType = Context.DependentTy;
9227 continue;
9228 }
9229
9230 // We need to have a complete type to look into.
9231 if (RequireCompleteType(OC.LocStart, CurrentType,
9232 diag::err_offsetof_incomplete_type))
9233 return ExprError();
9234
9235 // Look for the designated field.
9236 const RecordType *RC = CurrentType->getAs<RecordType>();
9237 if (!RC)
9238 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9239 << CurrentType);
9240 RecordDecl *RD = RC->getDecl();
9241
9242 // C++ [lib.support.types]p5:
9243 // The macro offsetof accepts a restricted set of type arguments in this
9244 // International Standard. type shall be a POD structure or a POD union
9245 // (clause 9).
9246 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9247 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009248 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009249 PDiag(diag::warn_offsetof_non_pod_type)
9250 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9251 << CurrentType))
9252 DidWarnAboutNonPOD = true;
9253 }
9254
9255 // Look for the field.
9256 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9257 LookupQualifiedName(R, RD);
9258 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009259 IndirectFieldDecl *IndirectMemberDecl = 0;
9260 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009261 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009262 MemberDecl = IndirectMemberDecl->getAnonField();
9263 }
9264
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009265 if (!MemberDecl)
9266 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9267 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9268 OC.LocEnd));
9269
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009270 // C99 7.17p3:
9271 // (If the specified member is a bit-field, the behavior is undefined.)
9272 //
9273 // We diagnose this as an error.
9274 if (MemberDecl->getBitWidth()) {
9275 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9276 << MemberDecl->getDeclName()
9277 << SourceRange(BuiltinLoc, RParenLoc);
9278 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9279 return ExprError();
9280 }
Eli Friedman19410a72010-08-05 10:11:36 +00009281
9282 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009283 if (IndirectMemberDecl)
9284 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009285
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009286 // If the member was found in a base class, introduce OffsetOfNodes for
9287 // the base class indirections.
9288 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9289 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009290 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009291 CXXBasePath &Path = Paths.front();
9292 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9293 B != BEnd; ++B)
9294 Comps.push_back(OffsetOfNode(B->Base));
9295 }
Eli Friedman19410a72010-08-05 10:11:36 +00009296
Francois Pichet87c2e122010-11-21 06:08:52 +00009297 if (IndirectMemberDecl) {
9298 for (IndirectFieldDecl::chain_iterator FI =
9299 IndirectMemberDecl->chain_begin(),
9300 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9301 assert(isa<FieldDecl>(*FI));
9302 Comps.push_back(OffsetOfNode(OC.LocStart,
9303 cast<FieldDecl>(*FI), OC.LocEnd));
9304 }
9305 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009306 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009307
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009308 CurrentType = MemberDecl->getType().getNonReferenceType();
9309 }
9310
9311 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9312 TInfo, Comps.data(), Comps.size(),
9313 Exprs.data(), Exprs.size(), RParenLoc));
9314}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009315
John McCall60d7b3a2010-08-24 06:29:42 +00009316ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009317 SourceLocation BuiltinLoc,
9318 SourceLocation TypeLoc,
9319 ParsedType argty,
9320 OffsetOfComponent *CompPtr,
9321 unsigned NumComponents,
9322 SourceLocation RPLoc) {
9323
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009324 TypeSourceInfo *ArgTInfo;
9325 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9326 if (ArgTy.isNull())
9327 return ExprError();
9328
Eli Friedman5a15dc12010-08-05 10:15:45 +00009329 if (!ArgTInfo)
9330 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9331
9332 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9333 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009334}
9335
9336
John McCall60d7b3a2010-08-24 06:29:42 +00009337ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009338 Expr *CondExpr,
9339 Expr *LHSExpr, Expr *RHSExpr,
9340 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009341 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9342
John McCallf89e55a2010-11-18 06:31:45 +00009343 ExprValueKind VK = VK_RValue;
9344 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009345 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009346 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009347 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009348 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009349 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009350 } else {
9351 // The conditional expression is required to be a constant expression.
9352 llvm::APSInt condEval(32);
9353 SourceLocation ExpLoc;
9354 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009355 return ExprError(Diag(ExpLoc,
9356 diag::err_typecheck_choose_expr_requires_constant)
9357 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009358
Sebastian Redl28507842009-02-26 14:39:58 +00009359 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009360 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9361
9362 resType = ActiveExpr->getType();
9363 ValueDependent = ActiveExpr->isValueDependent();
9364 VK = ActiveExpr->getValueKind();
9365 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009366 }
9367
Sebastian Redlf53597f2009-03-15 17:47:39 +00009368 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009369 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009370 resType->isDependentType(),
9371 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009372}
9373
Steve Naroff4eb206b2008-09-03 18:15:37 +00009374//===----------------------------------------------------------------------===//
9375// Clang Extensions.
9376//===----------------------------------------------------------------------===//
9377
9378/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009379void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009380 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9381 PushBlockScope(BlockScope, Block);
9382 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009383 if (BlockScope)
9384 PushDeclContext(BlockScope, Block);
9385 else
9386 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009387}
9388
Mike Stump98eb8a72009-02-04 22:31:32 +00009389void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009390 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009391 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009392 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009393
John McCallbf1a0282010-06-04 23:28:52 +00009394 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009395 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009396
John McCall711c52b2011-01-05 12:14:39 +00009397 // GetTypeForDeclarator always produces a function type for a block
9398 // literal signature. Furthermore, it is always a FunctionProtoType
9399 // unless the function was written with a typedef.
9400 assert(T->isFunctionType() &&
9401 "GetTypeForDeclarator made a non-function block signature");
9402
9403 // Look for an explicit signature in that function type.
9404 FunctionProtoTypeLoc ExplicitSignature;
9405
9406 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9407 if (isa<FunctionProtoTypeLoc>(tmp)) {
9408 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9409
9410 // Check whether that explicit signature was synthesized by
9411 // GetTypeForDeclarator. If so, don't save that as part of the
9412 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009413 if (ExplicitSignature.getLocalRangeBegin() ==
9414 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009415 // This would be much cheaper if we stored TypeLocs instead of
9416 // TypeSourceInfos.
9417 TypeLoc Result = ExplicitSignature.getResultLoc();
9418 unsigned Size = Result.getFullDataSize();
9419 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9420 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9421
9422 ExplicitSignature = FunctionProtoTypeLoc();
9423 }
John McCall82dc0092010-06-04 11:21:44 +00009424 }
Mike Stump1eb44332009-09-09 15:08:12 +00009425
John McCall711c52b2011-01-05 12:14:39 +00009426 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9427 CurBlock->FunctionType = T;
9428
9429 const FunctionType *Fn = T->getAs<FunctionType>();
9430 QualType RetTy = Fn->getResultType();
9431 bool isVariadic =
9432 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9433
John McCallc71a4912010-06-04 19:02:56 +00009434 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009435
John McCall82dc0092010-06-04 11:21:44 +00009436 // Don't allow returning a objc interface by value.
9437 if (RetTy->isObjCObjectType()) {
9438 Diag(ParamInfo.getSourceRange().getBegin(),
9439 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9440 return;
9441 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009442
John McCall82dc0092010-06-04 11:21:44 +00009443 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009444 // return type. TODO: what should we do with declarators like:
9445 // ^ * { ... }
9446 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009447 if (RetTy != Context.DependentTy)
9448 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009449
John McCall82dc0092010-06-04 11:21:44 +00009450 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009451 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009452 if (ExplicitSignature) {
9453 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9454 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009455 if (Param->getIdentifier() == 0 &&
9456 !Param->isImplicit() &&
9457 !Param->isInvalidDecl() &&
9458 !getLangOptions().CPlusPlus)
9459 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009460 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009461 }
John McCall82dc0092010-06-04 11:21:44 +00009462
9463 // Fake up parameter variables if we have a typedef, like
9464 // ^ fntype { ... }
9465 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9466 for (FunctionProtoType::arg_type_iterator
9467 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9468 ParmVarDecl *Param =
9469 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9470 ParamInfo.getSourceRange().getBegin(),
9471 *I);
John McCallc71a4912010-06-04 19:02:56 +00009472 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009473 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009474 }
John McCall82dc0092010-06-04 11:21:44 +00009475
John McCallc71a4912010-06-04 19:02:56 +00009476 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009477 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009478 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009479 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9480 CurBlock->TheDecl->param_end(),
9481 /*CheckParameterNames=*/false);
9482 }
9483
John McCall82dc0092010-06-04 11:21:44 +00009484 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009485 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009486
John McCallc71a4912010-06-04 19:02:56 +00009487 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009488 Diag(ParamInfo.getAttributes()->getLoc(),
9489 diag::warn_attribute_sentinel_not_variadic) << 1;
9490 // FIXME: remove the attribute.
9491 }
9492
9493 // Put the parameter variables in scope. We can bail out immediately
9494 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009495 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009496 return;
9497
Steve Naroff090276f2008-10-10 01:28:17 +00009498 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009499 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9500 (*AI)->setOwningFunction(CurBlock->TheDecl);
9501
Steve Naroff090276f2008-10-10 01:28:17 +00009502 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009503 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009504 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009505
Steve Naroff090276f2008-10-10 01:28:17 +00009506 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009507 }
John McCall7a9813c2010-01-22 00:28:27 +00009508 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009509}
9510
9511/// ActOnBlockError - If there is an error parsing a block, this callback
9512/// is invoked to pop the information about the block from the action impl.
9513void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009514 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009515 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009516 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009517}
9518
9519/// ActOnBlockStmtExpr - This is called when the body of a block statement
9520/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009521ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009522 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009523 // If blocks are disabled, emit an error.
9524 if (!LangOpts.Blocks)
9525 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009526
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009527 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009528
Steve Naroff090276f2008-10-10 01:28:17 +00009529 PopDeclContext();
9530
Steve Naroff4eb206b2008-09-03 18:15:37 +00009531 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009532 if (!BSI->ReturnType.isNull())
9533 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009534
Mike Stump56925862009-07-28 22:04:01 +00009535 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009536 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009537
John McCall469a1eb2011-02-02 13:00:07 +00009538 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009539 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9540 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009541
John McCallc71a4912010-06-04 19:02:56 +00009542 // If the user wrote a function type in some form, try to use that.
9543 if (!BSI->FunctionType.isNull()) {
9544 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9545
9546 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9547 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9548
9549 // Turn protoless block types into nullary block types.
9550 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009551 FunctionProtoType::ExtProtoInfo EPI;
9552 EPI.ExtInfo = Ext;
9553 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009554
9555 // Otherwise, if we don't need to change anything about the function type,
9556 // preserve its sugar structure.
9557 } else if (FTy->getResultType() == RetTy &&
9558 (!NoReturn || FTy->getNoReturnAttr())) {
9559 BlockTy = BSI->FunctionType;
9560
9561 // Otherwise, make the minimal modifications to the function type.
9562 } else {
9563 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009564 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9565 EPI.TypeQuals = 0; // FIXME: silently?
9566 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009567 BlockTy = Context.getFunctionType(RetTy,
9568 FPT->arg_type_begin(),
9569 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009570 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009571 }
9572
9573 // If we don't have a function type, just build one from nothing.
9574 } else {
John McCalle23cf432010-12-14 08:05:40 +00009575 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmana49218e2011-04-09 08:18:08 +00009576 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalle23cf432010-12-14 08:05:40 +00009577 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009578 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009579
John McCallc71a4912010-06-04 19:02:56 +00009580 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9581 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009582 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009583
Chris Lattner17a78302009-04-19 05:28:12 +00009584 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009585 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009586 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009587
Chris Lattnere476bdc2011-02-17 23:58:47 +00009588 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009589
John McCall469a1eb2011-02-02 13:00:07 +00009590 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009591
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009592 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9593 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009594 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009595}
9596
John McCall60d7b3a2010-08-24 06:29:42 +00009597ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009598 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009599 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009600 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009601 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009602 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009603}
9604
John McCall60d7b3a2010-08-24 06:29:42 +00009605ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009606 Expr *E, TypeSourceInfo *TInfo,
9607 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009608 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009609
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009610 // Get the va_list type
9611 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009612 if (VaListType->isArrayType()) {
9613 // Deal with implicit array decay; for example, on x86-64,
9614 // va_list is an array, but it's supposed to decay to
9615 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009616 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009617 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009618 ExprResult Result = UsualUnaryConversions(E);
9619 if (Result.isInvalid())
9620 return ExprError();
9621 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009622 } else {
9623 // Otherwise, the va_list argument must be an l-value because
9624 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009625 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009626 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009627 return ExprError();
9628 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009629
Douglas Gregordd027302009-05-19 23:10:31 +00009630 if (!E->isTypeDependent() &&
9631 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009632 return ExprError(Diag(E->getLocStart(),
9633 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009634 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009635 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009636
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009637 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009638 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009639
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009640 QualType T = TInfo->getType().getNonLValueExprType(Context);
9641 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009642}
9643
John McCall60d7b3a2010-08-24 06:29:42 +00009644ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009645 // The type of __null will be int or long, depending on the size of
9646 // pointers on the target.
9647 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009648 unsigned pw = Context.Target.getPointerWidth(0);
9649 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009650 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009651 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009652 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009653 else if (pw == Context.Target.getLongLongWidth())
9654 Ty = Context.LongLongTy;
9655 else {
9656 assert(!"I don't know size of pointer!");
9657 Ty = Context.IntTy;
9658 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009659
Sebastian Redlf53597f2009-03-15 17:47:39 +00009660 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009661}
9662
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009663static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009664 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009665 if (!SemaRef.getLangOptions().ObjC1)
9666 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009667
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009668 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9669 if (!PT)
9670 return;
9671
9672 // Check if the destination is of type 'id'.
9673 if (!PT->isObjCIdType()) {
9674 // Check if the destination is the 'NSString' interface.
9675 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9676 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9677 return;
9678 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009679
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009680 // Strip off any parens and casts.
9681 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9682 if (!SL || SL->isWide())
9683 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009684
Douglas Gregor849b2432010-03-31 17:46:05 +00009685 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009686}
9687
Chris Lattner5cf216b2008-01-04 18:04:52 +00009688bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9689 SourceLocation Loc,
9690 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009691 Expr *SrcExpr, AssignmentAction Action,
9692 bool *Complained) {
9693 if (Complained)
9694 *Complained = false;
9695
Chris Lattner5cf216b2008-01-04 18:04:52 +00009696 // Decode the result (notice that AST's are still created for extensions).
9697 bool isInvalid = false;
9698 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009699 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009700
Chris Lattner5cf216b2008-01-04 18:04:52 +00009701 switch (ConvTy) {
9702 default: assert(0 && "Unknown conversion type");
9703 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009704 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009705 DiagKind = diag::ext_typecheck_convert_pointer_int;
9706 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009707 case IntToPointer:
9708 DiagKind = diag::ext_typecheck_convert_int_pointer;
9709 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009710 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009711 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009712 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9713 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009714 case IncompatiblePointerSign:
9715 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9716 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009717 case FunctionVoidPointer:
9718 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9719 break;
John McCall86c05f32011-02-01 00:10:29 +00009720 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009721 // Perform array-to-pointer decay if necessary.
9722 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9723
John McCall86c05f32011-02-01 00:10:29 +00009724 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9725 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9726 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9727 DiagKind = diag::err_typecheck_incompatible_address_space;
9728 break;
9729 }
9730
9731 llvm_unreachable("unknown error case for discarding qualifiers!");
9732 // fallthrough
9733 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009734 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009735 // If the qualifiers lost were because we were applying the
9736 // (deprecated) C++ conversion from a string literal to a char*
9737 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9738 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009739 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009740 // bit of refactoring (so that the second argument is an
9741 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009742 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009743 // C++ semantics.
9744 if (getLangOptions().CPlusPlus &&
9745 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9746 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009747 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9748 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009749 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009750 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009751 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009752 case IntToBlockPointer:
9753 DiagKind = diag::err_int_to_block_pointer;
9754 break;
9755 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009756 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009757 break;
Steve Naroff39579072008-10-14 22:18:38 +00009758 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009759 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009760 // it can give a more specific diagnostic.
9761 DiagKind = diag::warn_incompatible_qualified_id;
9762 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009763 case IncompatibleVectors:
9764 DiagKind = diag::warn_incompatible_vectors;
9765 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009766 case Incompatible:
9767 DiagKind = diag::err_typecheck_convert_incompatible;
9768 isInvalid = true;
9769 break;
9770 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009771
Douglas Gregord4eea832010-04-09 00:35:39 +00009772 QualType FirstType, SecondType;
9773 switch (Action) {
9774 case AA_Assigning:
9775 case AA_Initializing:
9776 // The destination type comes first.
9777 FirstType = DstType;
9778 SecondType = SrcType;
9779 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009780
Douglas Gregord4eea832010-04-09 00:35:39 +00009781 case AA_Returning:
9782 case AA_Passing:
9783 case AA_Converting:
9784 case AA_Sending:
9785 case AA_Casting:
9786 // The source type comes first.
9787 FirstType = SrcType;
9788 SecondType = DstType;
9789 break;
9790 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009791
Douglas Gregord4eea832010-04-09 00:35:39 +00009792 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009793 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009794 if (Complained)
9795 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009796 return isInvalid;
9797}
Anders Carlssone21555e2008-11-30 19:50:32 +00009798
Chris Lattner3bf68932009-04-25 21:59:05 +00009799bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009800 llvm::APSInt ICEResult;
9801 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9802 if (Result)
9803 *Result = ICEResult;
9804 return false;
9805 }
9806
Anders Carlssone21555e2008-11-30 19:50:32 +00009807 Expr::EvalResult EvalResult;
9808
Mike Stumpeed9cac2009-02-19 03:04:26 +00009809 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009810 EvalResult.HasSideEffects) {
9811 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9812
9813 if (EvalResult.Diag) {
9814 // We only show the note if it's not the usual "invalid subexpression"
9815 // or if it's actually in a subexpression.
9816 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9817 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9818 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9819 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009820
Anders Carlssone21555e2008-11-30 19:50:32 +00009821 return true;
9822 }
9823
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009824 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9825 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009826
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009827 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009828 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9829 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009830 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009831
Anders Carlssone21555e2008-11-30 19:50:32 +00009832 if (Result)
9833 *Result = EvalResult.Val.getInt();
9834 return false;
9835}
Douglas Gregore0762c92009-06-19 23:52:42 +00009836
Douglas Gregor2afce722009-11-26 00:44:06 +00009837void
Mike Stump1eb44332009-09-09 15:08:12 +00009838Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009839 ExprEvalContexts.push_back(
9840 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009841}
9842
Mike Stump1eb44332009-09-09 15:08:12 +00009843void
Douglas Gregor2afce722009-11-26 00:44:06 +00009844Sema::PopExpressionEvaluationContext() {
9845 // Pop the current expression evaluation context off the stack.
9846 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9847 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009848
Douglas Gregor06d33692009-12-12 07:57:52 +00009849 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9850 if (Rec.PotentiallyReferenced) {
9851 // Mark any remaining declarations in the current position of the stack
9852 // as "referenced". If they were not meant to be referenced, semantic
9853 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009854 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009855 I = Rec.PotentiallyReferenced->begin(),
9856 IEnd = Rec.PotentiallyReferenced->end();
9857 I != IEnd; ++I)
9858 MarkDeclarationReferenced(I->first, I->second);
9859 }
9860
9861 if (Rec.PotentiallyDiagnosed) {
9862 // Emit any pending diagnostics.
9863 for (PotentiallyEmittedDiagnostics::iterator
9864 I = Rec.PotentiallyDiagnosed->begin(),
9865 IEnd = Rec.PotentiallyDiagnosed->end();
9866 I != IEnd; ++I)
9867 Diag(I->first, I->second);
9868 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009869 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009870
9871 // When are coming out of an unevaluated context, clear out any
9872 // temporaries that we may have created as part of the evaluation of
9873 // the expression in that context: they aren't relevant because they
9874 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009875 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009876 ExprTemporaries.size() > Rec.NumTemporaries)
9877 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9878 ExprTemporaries.end());
9879
9880 // Destroy the popped expression evaluation record.
9881 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009882}
Douglas Gregore0762c92009-06-19 23:52:42 +00009883
9884/// \brief Note that the given declaration was referenced in the source code.
9885///
9886/// This routine should be invoke whenever a given declaration is referenced
9887/// in the source code, and where that reference occurred. If this declaration
9888/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9889/// C99 6.9p3), then the declaration will be marked as used.
9890///
9891/// \param Loc the location where the declaration was referenced.
9892///
9893/// \param D the declaration that has been referenced by the source code.
9894void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9895 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009896
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009897 D->setReferenced();
9898
Douglas Gregorc070cc62010-06-17 23:14:26 +00009899 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009901
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009902 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9903 // template or not. The reason for this is that unevaluated expressions
9904 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9905 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009906 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009907 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009908 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009909 return;
9910 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009911
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009912 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9913 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009914
Douglas Gregore0762c92009-06-19 23:52:42 +00009915 // Do not mark anything as "used" within a dependent context; wait for
9916 // an instantiation.
9917 if (CurContext->isDependentContext())
9918 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009919
Douglas Gregor2afce722009-11-26 00:44:06 +00009920 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009921 case Unevaluated:
9922 // We are in an expression that is not potentially evaluated; do nothing.
9923 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009924
Douglas Gregorac7610d2009-06-22 20:57:11 +00009925 case PotentiallyEvaluated:
9926 // We are in a potentially-evaluated expression, so this declaration is
9927 // "used"; handle this below.
9928 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009929
Douglas Gregorac7610d2009-06-22 20:57:11 +00009930 case PotentiallyPotentiallyEvaluated:
9931 // We are in an expression that may be potentially evaluated; queue this
9932 // declaration reference until we know whether the expression is
9933 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009934 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009935 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009936
9937 case PotentiallyEvaluatedIfUsed:
9938 // Referenced declarations will only be used if the construct in the
9939 // containing expression is used.
9940 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009941 }
Mike Stump1eb44332009-09-09 15:08:12 +00009942
Douglas Gregore0762c92009-06-19 23:52:42 +00009943 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009944 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +00009945 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9946 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009947 return;
9948 if (!Constructor->isUsed(false))
9949 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +00009950 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +00009951 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009952 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +00009953 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009954 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009955
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009956 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009957 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009958 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009959 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009960 if (Destructor->isVirtual())
9961 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009962 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009963 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009964 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009965 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009966 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009967 } else if (MethodDecl->isVirtual())
9968 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009969 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009970 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009971 // Recursive functions should be marked when used from another function.
9972 if (CurContext == Function) return;
9973
Mike Stump1eb44332009-09-09 15:08:12 +00009974 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009975 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009976 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009977 bool AlreadyInstantiated = false;
9978 if (FunctionTemplateSpecializationInfo *SpecInfo
9979 = Function->getTemplateSpecializationInfo()) {
9980 if (SpecInfo->getPointOfInstantiation().isInvalid())
9981 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009982 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009983 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009984 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009985 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009986 = Function->getMemberSpecializationInfo()) {
9987 if (MSInfo->getPointOfInstantiation().isInvalid())
9988 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009989 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009990 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009991 AlreadyInstantiated = true;
9992 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009993
Douglas Gregor60406be2010-01-16 22:29:39 +00009994 if (!AlreadyInstantiated) {
9995 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9996 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9997 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9998 Loc));
9999 else
Chandler Carruth62c78d52010-08-25 08:44:16 +000010000 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +000010001 }
John McCall15e310a2011-02-19 02:53:41 +000010002 } else {
10003 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +000010004 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10005 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +000010006 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +000010007 MarkDeclarationReferenced(Loc, *i);
10008 }
John McCall15e310a2011-02-19 02:53:41 +000010009 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010010
John McCall15e310a2011-02-19 02:53:41 +000010011 // Keep track of used but undefined functions.
10012 if (!Function->isPure() && !Function->hasBody() &&
10013 Function->getLinkage() != ExternalLinkage) {
10014 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10015 if (old.isInvalid()) old = Loc;
10016 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +000010017
John McCall15e310a2011-02-19 02:53:41 +000010018 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +000010019 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010020 }
Mike Stump1eb44332009-09-09 15:08:12 +000010021
Douglas Gregore0762c92009-06-19 23:52:42 +000010022 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +000010023 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +000010024 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010025 Var->getInstantiatedFromStaticDataMember()) {
10026 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10027 assert(MSInfo && "Missing member specialization information?");
10028 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10029 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10030 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +000010031 // This is a modification of an existing AST node. Notify listeners.
10032 if (ASTMutationListener *L = getASTMutationListener())
10033 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +000010034 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010035 }
10036 }
Mike Stump1eb44332009-09-09 15:08:12 +000010037
John McCall77efc682011-02-21 19:25:48 +000010038 // Keep track of used but undefined variables. We make a hole in
10039 // the warning for static const data members with in-line
10040 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010041 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010042 && Var->getLinkage() != ExternalLinkage
10043 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010044 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10045 if (old.isInvalid()) old = Loc;
10046 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010047
Douglas Gregore0762c92009-06-19 23:52:42 +000010048 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010049 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010050 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010051}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010052
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010053namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010054 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010055 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010056 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010057 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10058 Sema &S;
10059 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010060
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010061 public:
10062 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010063
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010064 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010065
10066 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10067 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010068 };
10069}
10070
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010071bool MarkReferencedDecls::TraverseTemplateArgument(
10072 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010073 if (Arg.getKind() == TemplateArgument::Declaration) {
10074 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10075 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010076
10077 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010078}
10079
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010080bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010081 if (ClassTemplateSpecializationDecl *Spec
10082 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10083 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010084 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010085 }
10086
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010087 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010088}
10089
10090void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10091 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010092 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010093}
10094
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010095namespace {
10096 /// \brief Helper class that marks all of the declarations referenced by
10097 /// potentially-evaluated subexpressions as "referenced".
10098 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10099 Sema &S;
10100
10101 public:
10102 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10103
10104 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10105
10106 void VisitDeclRefExpr(DeclRefExpr *E) {
10107 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10108 }
10109
10110 void VisitMemberExpr(MemberExpr *E) {
10111 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010112 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010113 }
10114
10115 void VisitCXXNewExpr(CXXNewExpr *E) {
10116 if (E->getConstructor())
10117 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10118 if (E->getOperatorNew())
10119 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10120 if (E->getOperatorDelete())
10121 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010122 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010123 }
10124
10125 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10126 if (E->getOperatorDelete())
10127 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010128 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10129 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10130 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10131 S.MarkDeclarationReferenced(E->getLocStart(),
10132 S.LookupDestructor(Record));
10133 }
10134
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010135 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010136 }
10137
10138 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10139 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010140 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010141 }
10142
10143 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10144 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10145 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010146
10147 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10148 Visit(E->getExpr());
10149 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010150 };
10151}
10152
10153/// \brief Mark any declarations that appear within this expression or any
10154/// potentially-evaluated subexpressions as "referenced".
10155void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10156 EvaluatedExprMarker(*this).Visit(E);
10157}
10158
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010159/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10160/// of the program being compiled.
10161///
10162/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010163/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010164/// possibility that the code will actually be executable. Code in sizeof()
10165/// expressions, code used only during overload resolution, etc., are not
10166/// potentially evaluated. This routine will suppress such diagnostics or,
10167/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010168/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010169/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010170///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010171/// This routine should be used for all diagnostics that describe the run-time
10172/// behavior of a program, such as passing a non-POD value through an ellipsis.
10173/// Failure to do so will likely result in spurious diagnostics or failures
10174/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010175bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010176 const PartialDiagnostic &PD) {
10177 switch (ExprEvalContexts.back().Context ) {
10178 case Unevaluated:
10179 // The argument will never be evaluated, so don't complain.
10180 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010181
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010182 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010183 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010184 if (stmt && getCurFunctionOrMethodDecl()) {
10185 FunctionScopes.back()->PossiblyUnreachableDiags.
10186 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10187 }
10188 else
10189 Diag(Loc, PD);
10190
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010191 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010192
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010193 case PotentiallyPotentiallyEvaluated:
10194 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10195 break;
10196 }
10197
10198 return false;
10199}
10200
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010201bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10202 CallExpr *CE, FunctionDecl *FD) {
10203 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10204 return false;
10205
10206 PartialDiagnostic Note =
10207 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10208 << FD->getDeclName() : PDiag();
10209 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010210
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010211 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010212 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010213 PDiag(diag::err_call_function_incomplete_return)
10214 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010215 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010216 << CE->getSourceRange(),
10217 std::make_pair(NoteLoc, Note)))
10218 return true;
10219
10220 return false;
10221}
10222
Douglas Gregor92c3a042011-01-19 16:50:08 +000010223// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010224// will prevent this condition from triggering, which is what we want.
10225void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10226 SourceLocation Loc;
10227
John McCalla52ef082009-11-11 02:41:58 +000010228 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010229 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010230
John McCall5a881bb2009-10-12 21:59:07 +000010231 if (isa<BinaryOperator>(E)) {
10232 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010233 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010234 return;
10235
Douglas Gregor92c3a042011-01-19 16:50:08 +000010236 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10237
John McCallc8d8ac52009-11-12 00:06:05 +000010238 // Greylist some idioms by putting them into a warning subcategory.
10239 if (ObjCMessageExpr *ME
10240 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10241 Selector Sel = ME->getSelector();
10242
John McCallc8d8ac52009-11-12 00:06:05 +000010243 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010244 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010245 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10246
10247 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010248 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010249 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10250 }
John McCalla52ef082009-11-11 02:41:58 +000010251
John McCall5a881bb2009-10-12 21:59:07 +000010252 Loc = Op->getOperatorLoc();
10253 } else if (isa<CXXOperatorCallExpr>(E)) {
10254 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010255 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010256 return;
10257
Douglas Gregor92c3a042011-01-19 16:50:08 +000010258 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010259 Loc = Op->getOperatorLoc();
10260 } else {
10261 // Not an assignment.
10262 return;
10263 }
10264
Douglas Gregor55b38842010-04-14 16:09:52 +000010265 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010266
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010267 SourceLocation Open = E->getSourceRange().getBegin();
10268 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10269 Diag(Loc, diag::note_condition_assign_silence)
10270 << FixItHint::CreateInsertion(Open, "(")
10271 << FixItHint::CreateInsertion(Close, ")");
10272
Douglas Gregor92c3a042011-01-19 16:50:08 +000010273 if (IsOrAssign)
10274 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10275 << FixItHint::CreateReplacement(Loc, "!=");
10276 else
10277 Diag(Loc, diag::note_condition_assign_to_comparison)
10278 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000010279}
10280
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010281/// \brief Redundant parentheses over an equality comparison can indicate
10282/// that the user intended an assignment used as condition.
10283void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010284 // Don't warn if the parens came from a macro.
10285 SourceLocation parenLoc = parenE->getLocStart();
10286 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10287 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010288 // Don't warn for dependent expressions.
10289 if (parenE->isTypeDependent())
10290 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010291
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010292 Expr *E = parenE->IgnoreParens();
10293
10294 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010295 if (opE->getOpcode() == BO_EQ &&
10296 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10297 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010298 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010299
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010300 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010301 Diag(Loc, diag::note_equality_comparison_silence)
10302 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10303 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010304 Diag(Loc, diag::note_equality_comparison_to_assign)
10305 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010306 }
10307}
10308
John Wiegley429bb272011-04-08 18:41:53 +000010309ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010310 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010311 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10312 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010313
John McCall864c0412011-04-26 20:42:42 +000010314 ExprResult result = CheckPlaceholderExpr(E);
10315 if (result.isInvalid()) return ExprError();
10316 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010317
John McCall864c0412011-04-26 20:42:42 +000010318 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +000010319 if (getLangOptions().CPlusPlus)
10320 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10321
John Wiegley429bb272011-04-08 18:41:53 +000010322 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10323 if (ERes.isInvalid())
10324 return ExprError();
10325 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010326
10327 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010328 if (!T->isScalarType()) { // C99 6.8.4.1p1
10329 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10330 << T << E->getSourceRange();
10331 return ExprError();
10332 }
John McCall5a881bb2009-10-12 21:59:07 +000010333 }
10334
John Wiegley429bb272011-04-08 18:41:53 +000010335 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010336}
Douglas Gregor586596f2010-05-06 17:25:47 +000010337
John McCall60d7b3a2010-08-24 06:29:42 +000010338ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10339 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010340 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010341 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010342
10343 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010344}
John McCall2a984ca2010-10-12 00:20:44 +000010345
John McCall1de4d4e2011-04-07 08:22:57 +000010346namespace {
John McCall755d8492011-04-12 00:42:48 +000010347 /// A visitor for rebuilding a call to an __unknown_any expression
10348 /// to have an appropriate type.
10349 struct RebuildUnknownAnyFunction
10350 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10351
10352 Sema &S;
10353
10354 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10355
10356 ExprResult VisitStmt(Stmt *S) {
10357 llvm_unreachable("unexpected statement!");
10358 return ExprError();
10359 }
10360
10361 ExprResult VisitExpr(Expr *expr) {
10362 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10363 << expr->getSourceRange();
10364 return ExprError();
10365 }
10366
10367 /// Rebuild an expression which simply semantically wraps another
10368 /// expression which it shares the type and value kind of.
10369 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10370 ExprResult subResult = Visit(expr->getSubExpr());
10371 if (subResult.isInvalid()) return ExprError();
10372
10373 Expr *subExpr = subResult.take();
10374 expr->setSubExpr(subExpr);
10375 expr->setType(subExpr->getType());
10376 expr->setValueKind(subExpr->getValueKind());
10377 assert(expr->getObjectKind() == OK_Ordinary);
10378 return expr;
10379 }
10380
10381 ExprResult VisitParenExpr(ParenExpr *paren) {
10382 return rebuildSugarExpr(paren);
10383 }
10384
10385 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10386 return rebuildSugarExpr(op);
10387 }
10388
10389 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10390 ExprResult subResult = Visit(op->getSubExpr());
10391 if (subResult.isInvalid()) return ExprError();
10392
10393 Expr *subExpr = subResult.take();
10394 op->setSubExpr(subExpr);
10395 op->setType(S.Context.getPointerType(subExpr->getType()));
10396 assert(op->getValueKind() == VK_RValue);
10397 assert(op->getObjectKind() == OK_Ordinary);
10398 return op;
10399 }
10400
10401 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10402 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10403
10404 expr->setType(decl->getType());
10405
10406 assert(expr->getValueKind() == VK_RValue);
10407 if (S.getLangOptions().CPlusPlus &&
10408 !(isa<CXXMethodDecl>(decl) &&
10409 cast<CXXMethodDecl>(decl)->isInstance()))
10410 expr->setValueKind(VK_LValue);
10411
10412 return expr;
10413 }
10414
10415 ExprResult VisitMemberExpr(MemberExpr *mem) {
10416 return resolveDecl(mem, mem->getMemberDecl());
10417 }
10418
10419 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10420 return resolveDecl(ref, ref->getDecl());
10421 }
10422 };
10423}
10424
10425/// Given a function expression of unknown-any type, try to rebuild it
10426/// to have a function type.
10427static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10428 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10429 if (result.isInvalid()) return ExprError();
10430 return S.DefaultFunctionArrayConversion(result.take());
10431}
10432
10433namespace {
John McCall379b5152011-04-11 07:02:50 +000010434 /// A visitor for rebuilding an expression of type __unknown_anytype
10435 /// into one which resolves the type directly on the referring
10436 /// expression. Strict preservation of the original source
10437 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010438 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010439 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010440
10441 Sema &S;
10442
10443 /// The current destination type.
10444 QualType DestType;
10445
10446 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10447 : S(S), DestType(castType) {}
10448
John McCalla5fc4722011-04-09 22:50:59 +000010449 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010450 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010451 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010452 }
10453
John McCall379b5152011-04-11 07:02:50 +000010454 ExprResult VisitExpr(Expr *expr) {
10455 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10456 << expr->getSourceRange();
10457 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010458 }
10459
John McCall379b5152011-04-11 07:02:50 +000010460 ExprResult VisitCallExpr(CallExpr *call);
10461 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10462
John McCalla5fc4722011-04-09 22:50:59 +000010463 /// Rebuild an expression which simply semantically wraps another
10464 /// expression which it shares the type and value kind of.
10465 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10466 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010467 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010468 Expr *subExpr = subResult.take();
10469 expr->setSubExpr(subExpr);
10470 expr->setType(subExpr->getType());
10471 expr->setValueKind(subExpr->getValueKind());
10472 assert(expr->getObjectKind() == OK_Ordinary);
10473 return expr;
10474 }
John McCall1de4d4e2011-04-07 08:22:57 +000010475
John McCalla5fc4722011-04-09 22:50:59 +000010476 ExprResult VisitParenExpr(ParenExpr *paren) {
10477 return rebuildSugarExpr(paren);
10478 }
10479
10480 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10481 return rebuildSugarExpr(op);
10482 }
10483
John McCall755d8492011-04-12 00:42:48 +000010484 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10485 const PointerType *ptr = DestType->getAs<PointerType>();
10486 if (!ptr) {
10487 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10488 << op->getSourceRange();
10489 return ExprError();
10490 }
10491 assert(op->getValueKind() == VK_RValue);
10492 assert(op->getObjectKind() == OK_Ordinary);
10493 op->setType(DestType);
10494
10495 // Build the sub-expression as if it were an object of the pointee type.
10496 DestType = ptr->getPointeeType();
10497 ExprResult subResult = Visit(op->getSubExpr());
10498 if (subResult.isInvalid()) return ExprError();
10499 op->setSubExpr(subResult.take());
10500 return op;
10501 }
10502
John McCall379b5152011-04-11 07:02:50 +000010503 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010504
John McCall755d8492011-04-12 00:42:48 +000010505 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010506
John McCall755d8492011-04-12 00:42:48 +000010507 ExprResult VisitMemberExpr(MemberExpr *mem) {
10508 return resolveDecl(mem, mem->getMemberDecl());
10509 }
John McCalla5fc4722011-04-09 22:50:59 +000010510
10511 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010512 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010513 }
10514 };
10515}
10516
John McCall379b5152011-04-11 07:02:50 +000010517/// Rebuilds a call expression which yielded __unknown_anytype.
10518ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10519 Expr *callee = call->getCallee();
10520
10521 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000010522 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000010523 FK_FunctionPointer,
10524 FK_BlockPointer
10525 };
10526
10527 FnKind kind;
10528 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +000010529 if (type == S.Context.BoundMemberTy) {
10530 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10531 kind = FK_MemberFunction;
10532 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +000010533 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10534 type = ptr->getPointeeType();
10535 kind = FK_FunctionPointer;
10536 } else {
10537 type = type->castAs<BlockPointerType>()->getPointeeType();
10538 kind = FK_BlockPointer;
10539 }
10540 const FunctionType *fnType = type->castAs<FunctionType>();
10541
10542 // Verify that this is a legal result type of a function.
10543 if (DestType->isArrayType() || DestType->isFunctionType()) {
10544 unsigned diagID = diag::err_func_returning_array_function;
10545 if (kind == FK_BlockPointer)
10546 diagID = diag::err_block_returning_array_function;
10547
10548 S.Diag(call->getExprLoc(), diagID)
10549 << DestType->isFunctionType() << DestType;
10550 return ExprError();
10551 }
10552
10553 // Otherwise, go ahead and set DestType as the call's result.
10554 call->setType(DestType.getNonLValueExprType(S.Context));
10555 call->setValueKind(Expr::getValueKindForType(DestType));
10556 assert(call->getObjectKind() == OK_Ordinary);
10557
10558 // Rebuild the function type, replacing the result type with DestType.
10559 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10560 DestType = S.Context.getFunctionType(DestType,
10561 proto->arg_type_begin(),
10562 proto->getNumArgs(),
10563 proto->getExtProtoInfo());
10564 else
10565 DestType = S.Context.getFunctionNoProtoType(DestType,
10566 fnType->getExtInfo());
10567
10568 // Rebuild the appropriate pointer-to-function type.
10569 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +000010570 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000010571 // Nothing to do.
10572 break;
10573
10574 case FK_FunctionPointer:
10575 DestType = S.Context.getPointerType(DestType);
10576 break;
10577
10578 case FK_BlockPointer:
10579 DestType = S.Context.getBlockPointerType(DestType);
10580 break;
10581 }
10582
10583 // Finally, we can recurse.
10584 ExprResult calleeResult = Visit(callee);
10585 if (!calleeResult.isUsable()) return ExprError();
10586 call->setCallee(calleeResult.take());
10587
10588 // Bind a temporary if necessary.
10589 return S.MaybeBindToTemporary(call);
10590}
10591
10592ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000010593 ObjCMethodDecl *method = msg->getMethodDecl();
10594 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000010595
John McCall755d8492011-04-12 00:42:48 +000010596 // Verify that this is a legal result type of a call.
10597 if (DestType->isArrayType() || DestType->isFunctionType()) {
10598 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10599 << DestType->isFunctionType() << DestType;
10600 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010601 }
10602
John McCall755d8492011-04-12 00:42:48 +000010603 assert(method->getResultType() == S.Context.UnknownAnyTy);
10604 method->setResultType(DestType);
10605
John McCall379b5152011-04-11 07:02:50 +000010606 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000010607 msg->setType(DestType.getNonReferenceType());
10608 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010609
John McCall755d8492011-04-12 00:42:48 +000010610 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000010611}
10612
10613ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000010614 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000010615 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000010616 assert(ice->getValueKind() == VK_RValue);
10617 assert(ice->getObjectKind() == OK_Ordinary);
10618
John McCall755d8492011-04-12 00:42:48 +000010619 ice->setType(DestType);
10620
John McCall379b5152011-04-11 07:02:50 +000010621 // Rebuild the sub-expression as the pointee (function) type.
10622 DestType = DestType->castAs<PointerType>()->getPointeeType();
10623
10624 ExprResult result = Visit(ice->getSubExpr());
10625 if (!result.isUsable()) return ExprError();
10626
10627 ice->setSubExpr(result.take());
10628 return S.Owned(ice);
10629}
10630
John McCall755d8492011-04-12 00:42:48 +000010631ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000010632 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000010633 QualType type = DestType;
10634
10635 // We know how to make this work for certain kinds of decls:
10636
10637 // - functions
John McCall755d8492011-04-12 00:42:48 +000010638 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +000010639 // This is true because FunctionDecls must always have function
10640 // type, so we can't be resolving the entire thing at once.
10641 assert(type->isFunctionType());
10642
John McCallf5307512011-04-27 00:36:17 +000010643 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10644 if (method->isInstance()) {
10645 valueKind = VK_RValue;
10646 type = S.Context.BoundMemberTy;
10647 }
10648
John McCall379b5152011-04-11 07:02:50 +000010649 // Function references aren't l-values in C.
10650 if (!S.getLangOptions().CPlusPlus)
10651 valueKind = VK_RValue;
10652
10653 // - variables
10654 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000010655 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10656 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000010657 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000010658 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10659 << decl << expr->getSourceRange();
10660 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010661 }
10662
10663 // - nothing else
10664 } else {
10665 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10666 << decl << expr->getSourceRange();
10667 return ExprError();
10668 }
10669
John McCall755d8492011-04-12 00:42:48 +000010670 decl->setType(DestType);
10671 expr->setType(type);
10672 expr->setValueKind(valueKind);
10673 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000010674}
10675
John McCall1de4d4e2011-04-07 08:22:57 +000010676/// Check a cast of an unknown-any type. We intentionally only
10677/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000010678ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10679 Expr *castExpr, CastKind &castKind,
10680 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010681 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000010682 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10683 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010684
John McCalla5fc4722011-04-09 22:50:59 +000010685 castExpr = result.take();
10686 VK = castExpr->getValueKind();
10687 castKind = CK_NoOp;
10688
10689 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010690}
10691
10692static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10693 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000010694 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010695 while (true) {
10696 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000010697 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000010698 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010699 diagID = diag::err_uncasted_call_of_unknown_any;
10700 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010701 break;
John McCall379b5152011-04-11 07:02:50 +000010702 }
John McCall1de4d4e2011-04-07 08:22:57 +000010703 }
10704
John McCall379b5152011-04-11 07:02:50 +000010705 SourceLocation loc;
10706 NamedDecl *d;
10707 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10708 loc = ref->getLocation();
10709 d = ref->getDecl();
10710 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10711 loc = mem->getMemberLoc();
10712 d = mem->getMemberDecl();
10713 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10714 diagID = diag::err_uncasted_call_of_unknown_any;
10715 loc = msg->getSelectorLoc();
10716 d = msg->getMethodDecl();
10717 assert(d && "unknown method returning __unknown_any?");
10718 } else {
10719 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10720 << e->getSourceRange();
10721 return ExprError();
10722 }
10723
10724 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010725
10726 // Never recoverable.
10727 return ExprError();
10728}
10729
John McCall2a984ca2010-10-12 00:20:44 +000010730/// Check for operands with placeholder types and complain if found.
10731/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010732ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010733 // Placeholder types are always *exactly* the appropriate builtin type.
10734 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010735
John McCall1de4d4e2011-04-07 08:22:57 +000010736 // Overloaded expressions.
10737 if (type == Context.OverloadTy)
10738 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010739 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010740 QualType(),
10741 diag::err_ovl_unresolvable);
10742
John McCall864c0412011-04-26 20:42:42 +000010743 // Bound member functions.
10744 if (type == Context.BoundMemberTy) {
10745 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10746 << E->getSourceRange();
10747 return ExprError();
10748 }
10749
John McCall1de4d4e2011-04-07 08:22:57 +000010750 // Expressions of unknown type.
10751 if (type == Context.UnknownAnyTy)
10752 return diagnoseUnknownAnyExpr(*this, E);
10753
10754 assert(!type->isPlaceholderType());
10755 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010756}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010757
10758bool Sema::CheckCaseExpression(Expr *expr) {
10759 if (expr->isTypeDependent())
10760 return true;
10761 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10762 return expr->getType()->isIntegralOrEnumerationType();
10763 return false;
10764}