blob: 9019e95747dfe15595d35d90888c1ad2211b1559 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
159 // FIXME: In C++0x, if any of the arguments are parameter pack
160 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 int sentinelPos = attr->getSentinel();
162 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000163
Mike Stump87c57ac2009-05-16 07:39:55 +0000164 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
165 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000166 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000167 bool warnNotEnoughArgs = false;
168 int isMethod = 0;
169 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
170 // skip over named parameters.
171 ObjCMethodDecl::param_iterator P, E = MD->param_end();
172 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
173 if (nullPos)
174 --nullPos;
175 else
176 ++i;
177 }
178 warnNotEnoughArgs = (P != E || i >= NumArgs);
179 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000180 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000181 // skip over named parameters.
182 ObjCMethodDecl::param_iterator P, E = FD->param_end();
183 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
184 if (nullPos)
185 --nullPos;
186 else
187 ++i;
188 }
189 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000190 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000191 // block or function pointer call.
192 QualType Ty = V->getType();
193 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000194 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000195 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
196 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000197 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
198 unsigned NumArgsInProto = Proto->getNumArgs();
199 unsigned k;
200 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
201 if (nullPos)
202 --nullPos;
203 else
204 ++i;
205 }
206 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
207 }
208 if (Ty->isBlockPointerType())
209 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000210 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000211 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000212 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 return;
214
215 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000216 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000217 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000218 return;
219 }
220 int sentinel = i;
221 while (sentinelPos > 0 && i < NumArgs-1) {
222 --sentinelPos;
223 ++i;
224 }
225 if (sentinelPos > 0) {
226 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000227 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000228 return;
229 }
230 while (i < NumArgs-1) {
231 ++i;
232 ++sentinel;
233 }
234 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000235 if (!sentinelExpr) return;
236 if (sentinelExpr->isTypeDependent()) return;
237 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000238
239 // nullptr_t is always treated as null.
240 if (sentinelExpr->getType()->isNullPtrType()) return;
241
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000242 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000243 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
244 Expr::NPC_ValueDependentIsNull))
245 return;
246
247 // Unfortunately, __null has type 'int'.
248 if (isa<GNUNullExpr>(sentinelExpr)) return;
249
250 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
251 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000252}
253
Douglas Gregor87f95b02009-02-26 21:00:50 +0000254SourceRange Sema::getExprRange(ExprTy *E) const {
255 Expr *Ex = (Expr *)E;
256 return Ex? Ex->getSourceRange() : SourceRange();
257}
258
Chris Lattner513165e2008-07-25 21:10:04 +0000259//===----------------------------------------------------------------------===//
260// Standard Promotions and Conversions
261//===----------------------------------------------------------------------===//
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000264ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000265 QualType Ty = E->getType();
266 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
267
Chris Lattner513165e2008-07-25 21:10:04 +0000268 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000269 E = ImpCastExprToType(E, Context.getPointerType(Ty),
270 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000271 else if (Ty->isArrayType()) {
272 // In C90 mode, arrays only promote to pointers if the array expression is
273 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
274 // type 'array of type' is converted to an expression that has type 'pointer
275 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
276 // that has type 'array of type' ...". The relevant change is "an lvalue"
277 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000278 //
279 // C++ 4.2p1:
280 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
281 // T" can be converted to an rvalue of type "pointer to T".
282 //
John McCall086a4642010-11-24 05:12:34 +0000283 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000284 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
285 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000286 }
John Wiegley01296292011-04-08 18:41:53 +0000287 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000288}
289
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000290static void CheckForNullPointerDereference(Sema &S, Expr *E) {
291 // Check to see if we are dereferencing a null pointer. If so,
292 // and if not volatile-qualified, this is undefined behavior that the
293 // optimizer will delete, so warn about it. People sometimes try to use this
294 // to get a deterministic trap and are surprised by clang's behavior. This
295 // only handles the pattern "*null", which is a very syntactic check.
296 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
297 if (UO->getOpcode() == UO_Deref &&
298 UO->getSubExpr()->IgnoreParenCasts()->
299 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
300 !UO->getType().isVolatileQualified()) {
301 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
302 S.PDiag(diag::warn_indirection_through_null)
303 << UO->getSubExpr()->getSourceRange());
304 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
305 S.PDiag(diag::note_indirection_through_null));
306 }
307}
308
John Wiegley01296292011-04-08 18:41:53 +0000309ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000310 // C++ [conv.lval]p1:
311 // A glvalue of a non-function, non-array type T can be
312 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000313 if (!E->isGLValue()) return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000314 QualType T = E->getType();
315 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000316
John McCall27584242010-12-06 20:48:59 +0000317 // Create a load out of an ObjCProperty l-value, if necessary.
318 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000319 ExprResult Res = ConvertPropertyForRValue(E);
320 if (Res.isInvalid())
321 return Owned(E);
322 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000323 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000324 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000325 }
John McCall27584242010-12-06 20:48:59 +0000326
327 // We don't want to throw lvalue-to-rvalue casts on top of
328 // expressions of certain types in C++.
329 if (getLangOptions().CPlusPlus &&
330 (E->getType() == Context.OverloadTy ||
331 T->isDependentType() ||
332 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000333 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000334
335 // The C standard is actually really unclear on this point, and
336 // DR106 tells us what the result should be but not why. It's
337 // generally best to say that void types just doesn't undergo
338 // lvalue-to-rvalue at all. Note that expressions of unqualified
339 // 'void' type are never l-values, but qualified void can be.
340 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000341 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000342
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000343 CheckForNullPointerDereference(*this, E);
344
John McCall27584242010-12-06 20:48:59 +0000345 // C++ [conv.lval]p1:
346 // [...] If T is a non-class type, the type of the prvalue is the
347 // cv-unqualified version of T. Otherwise, the type of the
348 // rvalue is T.
349 //
350 // C99 6.3.2.1p2:
351 // If the lvalue has qualified type, the value has the unqualified
352 // version of the type of the lvalue; otherwise, the value has the
353 // type of the lvalue.
354 if (T.hasQualifiers())
355 T = T.getUnqualifiedType();
356
Ted Kremenekdf26df72011-03-01 18:41:00 +0000357 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000358
John Wiegley01296292011-04-08 18:41:53 +0000359 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
360 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000361}
362
John Wiegley01296292011-04-08 18:41:53 +0000363ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
364 ExprResult Res = DefaultFunctionArrayConversion(E);
365 if (Res.isInvalid())
366 return ExprError();
367 Res = DefaultLvalueConversion(Res.take());
368 if (Res.isInvalid())
369 return ExprError();
370 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000371}
372
373
Chris Lattner513165e2008-07-25 21:10:04 +0000374/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000375/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000376/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000377/// apply if the array is an argument to the sizeof or address (&) operators.
378/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000379ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000380 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000381 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
382 if (Res.isInvalid())
383 return Owned(E);
384 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000385
386 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000387 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000388
389 // Try to perform integral promotions if the object has a theoretically
390 // promotable type.
391 if (Ty->isIntegralOrUnscopedEnumerationType()) {
392 // C99 6.3.1.1p2:
393 //
394 // The following may be used in an expression wherever an int or
395 // unsigned int may be used:
396 // - an object or expression with an integer type whose integer
397 // conversion rank is less than or equal to the rank of int
398 // and unsigned int.
399 // - A bit-field of type _Bool, int, signed int, or unsigned int.
400 //
401 // If an int can represent all values of the original type, the
402 // value is converted to an int; otherwise, it is converted to an
403 // unsigned int. These are called the integer promotions. All
404 // other types are unchanged by the integer promotions.
405
406 QualType PTy = Context.isPromotableBitField(E);
407 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
409 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000410 }
411 if (Ty->isPromotableIntegerType()) {
412 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
414 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000415 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000416 }
John Wiegley01296292011-04-08 18:41:53 +0000417 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000418}
419
Chris Lattner2ce500f2008-07-25 22:25:12 +0000420/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000421/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000422/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000423ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
424 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000425 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000426
John Wiegley01296292011-04-08 18:41:53 +0000427 ExprResult Res = UsualUnaryConversions(E);
428 if (Res.isInvalid())
429 return Owned(E);
430 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000431
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000433 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
435
436 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000437}
438
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000439/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
440/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000441/// interfaces passed by value.
442ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000443 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000444 ExprResult ExprRes = CheckPlaceholderExpr(E);
445 if (ExprRes.isInvalid())
446 return ExprError();
447
448 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000449 if (ExprRes.isInvalid())
450 return ExprError();
451 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000453 // __builtin_va_start takes the second argument as a "varargs" argument, but
454 // it doesn't actually do anything with it. It doesn't need to be non-pod
455 // etc.
456 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000457 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000458
Douglas Gregor347e0f22011-05-21 19:26:31 +0000459 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000460 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000461 DiagRuntimeBehavior(E->getLocStart(), 0,
462 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
463 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000464 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000465
John McCall31168b02011-06-15 23:02:42 +0000466 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000467 // C++0x [expr.call]p7:
468 // Passing a potentially-evaluated argument of class type (Clause 9)
469 // having a non-trivial copy constructor, a non-trivial move constructor,
470 // or a non-trivial destructor, with no corresponding parameter,
471 // is conditionally-supported with implementation-defined semantics.
472 bool TrivialEnough = false;
473 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
474 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
475 if (Record->hasTrivialCopyConstructor() &&
476 Record->hasTrivialMoveConstructor() &&
477 Record->hasTrivialDestructor())
478 TrivialEnough = true;
479 }
480 }
John McCall31168b02011-06-15 23:02:42 +0000481
482 if (!TrivialEnough &&
483 getLangOptions().ObjCAutoRefCount &&
484 E->getType()->isObjCLifetimeType())
485 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000486
487 if (TrivialEnough) {
488 // Nothing to diagnose. This is okay.
489 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000490 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000491 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000492 << CT)) {
493 // Turn this into a trap.
494 CXXScopeSpec SS;
495 UnqualifiedId Name;
496 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
497 E->getLocStart());
498 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
499 if (TrapFn.isInvalid())
500 return ExprError();
501
502 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
503 MultiExprArg(), E->getLocEnd());
504 if (Call.isInvalid())
505 return ExprError();
506
507 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
508 Call.get(), E);
509 if (Comma.isInvalid())
510 return ExprError();
511
512 E = Comma.get();
513 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000514 }
515
John Wiegley01296292011-04-08 18:41:53 +0000516 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000517}
518
Chris Lattner513165e2008-07-25 21:10:04 +0000519/// UsualArithmeticConversions - Performs various conversions that are common to
520/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000521/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000522/// responsible for emitting appropriate error diagnostics.
523/// FIXME: verify the conversion rules for "complex int" are consistent with
524/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000525QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000526 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000527 if (!isCompAssign) {
528 lhsExpr = UsualUnaryConversions(lhsExpr.take());
529 if (lhsExpr.isInvalid())
530 return QualType();
531 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000532
John Wiegley01296292011-04-08 18:41:53 +0000533 rhsExpr = UsualUnaryConversions(rhsExpr.take());
534 if (rhsExpr.isInvalid())
535 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000536
Mike Stump11289f42009-09-09 15:08:12 +0000537 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000538 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000539 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000540 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000541 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000542 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000543
544 // If both types are identical, no conversion is needed.
545 if (lhs == rhs)
546 return lhs;
547
548 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
549 // The caller can deal with this (e.g. pointer + int).
550 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
551 return lhs;
552
John McCalld005ac92010-11-13 08:17:45 +0000553 // Apply unary and bitfield promotions to the LHS's type.
554 QualType lhs_unpromoted = lhs;
555 if (lhs->isPromotableIntegerType())
556 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000557 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000558 if (!LHSBitfieldPromoteTy.isNull())
559 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000560 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000561 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000562
John McCalld005ac92010-11-13 08:17:45 +0000563 // If both types are identical, no conversion is needed.
564 if (lhs == rhs)
565 return lhs;
566
567 // At this point, we have two different arithmetic types.
568
569 // Handle complex types first (C99 6.3.1.8p1).
570 bool LHSComplexFloat = lhs->isComplexType();
571 bool RHSComplexFloat = rhs->isComplexType();
572 if (LHSComplexFloat || RHSComplexFloat) {
573 // if we have an integer operand, the result is the complex type.
574
John McCallc5e62b42010-11-13 09:02:35 +0000575 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
576 if (rhs->isIntegerType()) {
577 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000578 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
579 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000580 } else {
581 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000582 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000583 }
John McCalld005ac92010-11-13 08:17:45 +0000584 return lhs;
585 }
586
John McCallc5e62b42010-11-13 09:02:35 +0000587 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
588 if (!isCompAssign) {
589 // int -> float -> _Complex float
590 if (lhs->isIntegerType()) {
591 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000592 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
593 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000594 } else {
595 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000597 }
598 }
John McCalld005ac92010-11-13 08:17:45 +0000599 return rhs;
600 }
601
602 // This handles complex/complex, complex/float, or float/complex.
603 // When both operands are complex, the shorter operand is converted to the
604 // type of the longer, and that is the type of the result. This corresponds
605 // to what is done when combining two real floating-point operands.
606 // The fun begins when size promotion occur across type domains.
607 // From H&S 6.3.4: When one operand is complex and the other is a real
608 // floating-point type, the less precise type is converted, within it's
609 // real or complex domain, to the precision of the other type. For example,
610 // when combining a "long double" with a "double _Complex", the
611 // "double _Complex" is promoted to "long double _Complex".
612 int order = Context.getFloatingTypeOrder(lhs, rhs);
613
614 // If both are complex, just cast to the more precise type.
615 if (LHSComplexFloat && RHSComplexFloat) {
616 if (order > 0) {
617 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000618 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000619 return lhs;
620
621 } else if (order < 0) {
622 // _Complex float -> _Complex double
623 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000624 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000625 return rhs;
626 }
627 return lhs;
628 }
629
630 // If just the LHS is complex, the RHS needs to be converted,
631 // and the LHS might need to be promoted.
632 if (LHSComplexFloat) {
633 if (order > 0) { // LHS is wider
634 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000635 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000636 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
637 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000638 return lhs;
639 }
640
641 // RHS is at least as wide. Find its corresponding complex type.
642 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
643
644 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000646
647 // _Complex float -> _Complex double
648 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000649 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000650
651 return result;
652 }
653
654 // Just the RHS is complex, so the LHS needs to be converted
655 // and the RHS might need to be promoted.
656 assert(RHSComplexFloat);
657
658 if (order < 0) { // RHS is wider
659 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000660 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000661 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000662 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
663 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000664 }
John McCalld005ac92010-11-13 08:17:45 +0000665 return rhs;
666 }
667
668 // LHS is at least as wide. Find its corresponding complex type.
669 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
670
671 // double -> _Complex double
672 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000673 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000674
675 // _Complex float -> _Complex double
676 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000677 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000678
679 return result;
680 }
681
682 // Now handle "real" floating types (i.e. float, double, long double).
683 bool LHSFloat = lhs->isRealFloatingType();
684 bool RHSFloat = rhs->isRealFloatingType();
685 if (LHSFloat || RHSFloat) {
686 // If we have two real floating types, convert the smaller operand
687 // to the bigger result.
688 if (LHSFloat && RHSFloat) {
689 int order = Context.getFloatingTypeOrder(lhs, rhs);
690 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000692 return lhs;
693 }
694
695 assert(order < 0 && "illegal float comparison");
696 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000697 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000698 return rhs;
699 }
700
701 // If we have an integer operand, the result is the real floating type.
702 if (LHSFloat) {
703 if (rhs->isIntegerType()) {
704 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000705 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000706 return lhs;
707 }
708
709 // Convert both sides to the appropriate complex float.
710 assert(rhs->isComplexIntegerType());
711 QualType result = Context.getComplexType(lhs);
712
713 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000714 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000715
716 // float -> _Complex float
717 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000719
720 return result;
721 }
722
723 assert(RHSFloat);
724 if (lhs->isIntegerType()) {
725 // Convert lhs to the rhs floating point type.
726 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000727 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000728 return rhs;
729 }
730
731 // Convert both sides to the appropriate complex float.
732 assert(lhs->isComplexIntegerType());
733 QualType result = Context.getComplexType(rhs);
734
735 // _Complex int -> _Complex float
736 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000737 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000738
739 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000740 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000741
742 return result;
743 }
744
745 // Handle GCC complex int extension.
746 // FIXME: if the operands are (int, _Complex long), we currently
747 // don't promote the complex. Also, signedness?
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750 if (lhsComplexInt && rhsComplexInt) {
751 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
752 rhsComplexInt->getElementType());
753 assert(order && "inequal types with equal element ordering");
754 if (order > 0) {
755 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000756 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000757 return lhs;
758 }
759
760 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000761 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000762 return rhs;
763 } else if (lhsComplexInt) {
764 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000765 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000766 return lhs;
767 } else if (rhsComplexInt) {
768 // int -> _Complex int
769 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000770 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000771 return rhs;
772 }
773
774 // Finally, we have two differing integer types.
775 // The rules for this case are in C99 6.3.1.8
776 int compare = Context.getIntegerTypeOrder(lhs, rhs);
777 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
778 rhsSigned = rhs->hasSignedIntegerRepresentation();
779 if (lhsSigned == rhsSigned) {
780 // Same signedness; use the higher-ranked type
781 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000782 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000783 return lhs;
784 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000785 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000786 return rhs;
787 } else if (compare != (lhsSigned ? 1 : -1)) {
788 // The unsigned type has greater than or equal rank to the
789 // signed type, so use the unsigned type
790 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000791 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000792 return lhs;
793 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000795 return rhs;
796 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
797 // The two types are different widths; if we are here, that
798 // means the signed type is larger than the unsigned type, so
799 // use the signed type.
800 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000802 return lhs;
803 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000805 return rhs;
806 } else {
807 // The signed type is higher-ranked than the unsigned type,
808 // but isn't actually any bigger (like unsigned int and long
809 // on most 32-bit systems). Use the unsigned type corresponding
810 // to the signed type.
811 QualType result =
812 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000813 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000814 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000816 return result;
817 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000818}
819
Chris Lattner513165e2008-07-25 21:10:04 +0000820//===----------------------------------------------------------------------===//
821// Semantic Analysis for various Expression Types
822//===----------------------------------------------------------------------===//
823
824
Peter Collingbourne91147592011-04-15 00:35:48 +0000825ExprResult
826Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
827 SourceLocation DefaultLoc,
828 SourceLocation RParenLoc,
829 Expr *ControllingExpr,
830 MultiTypeArg types,
831 MultiExprArg exprs) {
832 unsigned NumAssocs = types.size();
833 assert(NumAssocs == exprs.size());
834
835 ParsedType *ParsedTypes = types.release();
836 Expr **Exprs = exprs.release();
837
838 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
839 for (unsigned i = 0; i < NumAssocs; ++i) {
840 if (ParsedTypes[i])
841 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
842 else
843 Types[i] = 0;
844 }
845
846 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
847 ControllingExpr, Types, Exprs,
848 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000849 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000850 return ER;
851}
852
853ExprResult
854Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
855 SourceLocation DefaultLoc,
856 SourceLocation RParenLoc,
857 Expr *ControllingExpr,
858 TypeSourceInfo **Types,
859 Expr **Exprs,
860 unsigned NumAssocs) {
861 bool TypeErrorFound = false,
862 IsResultDependent = ControllingExpr->isTypeDependent(),
863 ContainsUnexpandedParameterPack
864 = ControllingExpr->containsUnexpandedParameterPack();
865
866 for (unsigned i = 0; i < NumAssocs; ++i) {
867 if (Exprs[i]->containsUnexpandedParameterPack())
868 ContainsUnexpandedParameterPack = true;
869
870 if (Types[i]) {
871 if (Types[i]->getType()->containsUnexpandedParameterPack())
872 ContainsUnexpandedParameterPack = true;
873
874 if (Types[i]->getType()->isDependentType()) {
875 IsResultDependent = true;
876 } else {
877 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
878 // complete object type other than a variably modified type."
879 unsigned D = 0;
880 if (Types[i]->getType()->isIncompleteType())
881 D = diag::err_assoc_type_incomplete;
882 else if (!Types[i]->getType()->isObjectType())
883 D = diag::err_assoc_type_nonobject;
884 else if (Types[i]->getType()->isVariablyModifiedType())
885 D = diag::err_assoc_type_variably_modified;
886
887 if (D != 0) {
888 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
889 << Types[i]->getTypeLoc().getSourceRange()
890 << Types[i]->getType();
891 TypeErrorFound = true;
892 }
893
894 // C1X 6.5.1.1p2 "No two generic associations in the same generic
895 // selection shall specify compatible types."
896 for (unsigned j = i+1; j < NumAssocs; ++j)
897 if (Types[j] && !Types[j]->getType()->isDependentType() &&
898 Context.typesAreCompatible(Types[i]->getType(),
899 Types[j]->getType())) {
900 Diag(Types[j]->getTypeLoc().getBeginLoc(),
901 diag::err_assoc_compatible_types)
902 << Types[j]->getTypeLoc().getSourceRange()
903 << Types[j]->getType()
904 << Types[i]->getType();
905 Diag(Types[i]->getTypeLoc().getBeginLoc(),
906 diag::note_compat_assoc)
907 << Types[i]->getTypeLoc().getSourceRange()
908 << Types[i]->getType();
909 TypeErrorFound = true;
910 }
911 }
912 }
913 }
914 if (TypeErrorFound)
915 return ExprError();
916
917 // If we determined that the generic selection is result-dependent, don't
918 // try to compute the result expression.
919 if (IsResultDependent)
920 return Owned(new (Context) GenericSelectionExpr(
921 Context, KeyLoc, ControllingExpr,
922 Types, Exprs, NumAssocs, DefaultLoc,
923 RParenLoc, ContainsUnexpandedParameterPack));
924
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000925 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000926 unsigned DefaultIndex = -1U;
927 for (unsigned i = 0; i < NumAssocs; ++i) {
928 if (!Types[i])
929 DefaultIndex = i;
930 else if (Context.typesAreCompatible(ControllingExpr->getType(),
931 Types[i]->getType()))
932 CompatIndices.push_back(i);
933 }
934
935 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
936 // type compatible with at most one of the types named in its generic
937 // association list."
938 if (CompatIndices.size() > 1) {
939 // We strip parens here because the controlling expression is typically
940 // parenthesized in macro definitions.
941 ControllingExpr = ControllingExpr->IgnoreParens();
942 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
943 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
944 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000945 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000946 E = CompatIndices.end(); I != E; ++I) {
947 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
948 diag::note_compat_assoc)
949 << Types[*I]->getTypeLoc().getSourceRange()
950 << Types[*I]->getType();
951 }
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
956 // its controlling expression shall have type compatible with exactly one of
957 // the types named in its generic association list."
958 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
959 // We strip parens here because the controlling expression is typically
960 // parenthesized in macro definitions.
961 ControllingExpr = ControllingExpr->IgnoreParens();
962 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
963 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
964 return ExprError();
965 }
966
967 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
968 // type name that is compatible with the type of the controlling expression,
969 // then the result expression of the generic selection is the expression
970 // in that generic association. Otherwise, the result expression of the
971 // generic selection is the expression in the default generic association."
972 unsigned ResultIndex =
973 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
974
975 return Owned(new (Context) GenericSelectionExpr(
976 Context, KeyLoc, ControllingExpr,
977 Types, Exprs, NumAssocs, DefaultLoc,
978 RParenLoc, ContainsUnexpandedParameterPack,
979 ResultIndex));
980}
981
Steve Naroff83895f72007-09-16 03:34:24 +0000982/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000983/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
984/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
985/// multiple tokens. However, the common case is that StringToks points to one
986/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000987///
John McCalldadc5752010-08-24 06:29:42 +0000988ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000989Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000990 assert(NumStringToks && "Must have at least one string!");
991
Chris Lattner8a24e582009-01-16 18:51:42 +0000992 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000993 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000994 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000995
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000996 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000997 for (unsigned i = 0; i != NumStringToks; ++i)
998 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000999
Chris Lattner36fc8792008-02-11 00:02:17 +00001000 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001001 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001002 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001003 else if (Literal.isUTF16())
1004 StrTy = Context.Char16Ty;
1005 else if (Literal.isUTF32())
1006 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001007 else if (Literal.Pascal)
1008 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001009
Douglas Gregorfb65e592011-07-27 05:40:30 +00001010 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1011 if (Literal.isWide())
1012 Kind = StringLiteral::Wide;
1013 else if (Literal.isUTF8())
1014 Kind = StringLiteral::UTF8;
1015 else if (Literal.isUTF16())
1016 Kind = StringLiteral::UTF16;
1017 else if (Literal.isUTF32())
1018 Kind = StringLiteral::UTF32;
1019
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001020 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001021 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001022 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001023
Chris Lattner36fc8792008-02-11 00:02:17 +00001024 // Get an array type for the string, according to C99 6.4.5. This includes
1025 // the nul terminator character as well as the string length for pascal
1026 // strings.
1027 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001028 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001029 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001030
Chris Lattner5b183d82006-11-10 05:03:26 +00001031 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001032 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001033 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001034 &StringTokLocs[0],
1035 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001036}
1037
John McCallc63de662011-02-02 13:00:07 +00001038enum CaptureResult {
1039 /// No capture is required.
1040 CR_NoCapture,
1041
1042 /// A capture is required.
1043 CR_Capture,
1044
John McCall351762c2011-02-07 10:33:21 +00001045 /// A by-ref capture is required.
1046 CR_CaptureByRef,
1047
John McCallc63de662011-02-02 13:00:07 +00001048 /// An error occurred when trying to capture the given variable.
1049 CR_Error
1050};
1051
1052/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001053///
John McCallc63de662011-02-02 13:00:07 +00001054/// \param var - the variable referenced
1055/// \param DC - the context which we couldn't capture through
1056static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001057diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001058 VarDecl *var, DeclContext *DC) {
1059 switch (S.ExprEvalContexts.back().Context) {
1060 case Sema::Unevaluated:
1061 // The argument will never be evaluated, so don't complain.
1062 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001063
John McCallc63de662011-02-02 13:00:07 +00001064 case Sema::PotentiallyEvaluated:
1065 case Sema::PotentiallyEvaluatedIfUsed:
1066 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001067
John McCallc63de662011-02-02 13:00:07 +00001068 case Sema::PotentiallyPotentiallyEvaluated:
1069 // FIXME: delay these!
1070 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
John McCallc63de662011-02-02 13:00:07 +00001073 // Don't diagnose about capture if we're not actually in code right
1074 // now; in general, there are more appropriate places that will
1075 // diagnose this.
1076 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1077
John McCall92d627e2011-03-22 23:15:50 +00001078 // Certain madnesses can happen with parameter declarations, which
1079 // we want to ignore.
1080 if (isa<ParmVarDecl>(var)) {
1081 // - If the parameter still belongs to the translation unit, then
1082 // we're actually just using one parameter in the declaration of
1083 // the next. This is useful in e.g. VLAs.
1084 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1085 return CR_NoCapture;
1086
1087 // - This particular madness can happen in ill-formed default
1088 // arguments; claim it's okay and let downstream code handle it.
1089 if (S.CurContext == var->getDeclContext()->getParent())
1090 return CR_NoCapture;
1091 }
John McCallc63de662011-02-02 13:00:07 +00001092
1093 DeclarationName functionName;
1094 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1095 functionName = fn->getDeclName();
1096 // FIXME: variable from enclosing block that we couldn't capture from!
1097
1098 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1099 << var->getIdentifier() << functionName;
1100 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1101 << var->getIdentifier();
1102
1103 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001104}
1105
John McCall351762c2011-02-07 10:33:21 +00001106/// There is a well-formed capture at a particular scope level;
1107/// propagate it through all the nested blocks.
1108static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1109 const BlockDecl::Capture &capture) {
1110 VarDecl *var = capture.getVariable();
1111
1112 // Update all the inner blocks with the capture information.
1113 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1114 i != e; ++i) {
1115 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1116 innerBlock->Captures.push_back(
1117 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1118 /*nested*/ true, capture.getCopyExpr()));
1119 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1120 }
1121
1122 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1123}
1124
1125/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001126/// given value in the current context requires a variable capture.
1127///
1128/// This also keeps the captures set in the BlockScopeInfo records
1129/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001130static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001131 ValueDecl *value) {
1132 // Only variables ever require capture.
1133 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001134 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001135
1136 // Fast path: variables from the current context never require capture.
1137 DeclContext *DC = S.CurContext;
1138 if (var->getDeclContext() == DC) return CR_NoCapture;
1139
1140 // Only variables with local storage require capture.
1141 // FIXME: What about 'const' variables in C++?
1142 if (!var->hasLocalStorage()) return CR_NoCapture;
1143
1144 // Otherwise, we need to capture.
1145
1146 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001147 do {
1148 // Only blocks (and eventually C++0x closures) can capture; other
1149 // scopes don't work.
1150 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001151 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001152
1153 BlockScopeInfo *blockScope =
1154 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1155 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1156
John McCall351762c2011-02-07 10:33:21 +00001157 // Check whether we've already captured it in this block. If so,
1158 // we're done.
1159 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1160 return propagateCapture(S, functionScopesIndex,
1161 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001162
1163 functionScopesIndex--;
1164 DC = cast<BlockDecl>(DC)->getDeclContext();
1165 } while (var->getDeclContext() != DC);
1166
John McCall351762c2011-02-07 10:33:21 +00001167 // Okay, we descended all the way to the block that defines the variable.
1168 // Actually try to capture it.
1169 QualType type = var->getType();
1170
1171 // Prohibit variably-modified types.
1172 if (type->isVariablyModifiedType()) {
1173 S.Diag(loc, diag::err_ref_vm_type);
1174 S.Diag(var->getLocation(), diag::note_declared_at);
1175 return CR_Error;
1176 }
1177
1178 // Prohibit arrays, even in __block variables, but not references to
1179 // them.
1180 if (type->isArrayType()) {
1181 S.Diag(loc, diag::err_ref_array_type);
1182 S.Diag(var->getLocation(), diag::note_declared_at);
1183 return CR_Error;
1184 }
1185
1186 S.MarkDeclarationReferenced(loc, var);
1187
1188 // The BlocksAttr indicates the variable is bound by-reference.
1189 bool byRef = var->hasAttr<BlocksAttr>();
1190
1191 // Build a copy expression.
1192 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001193 const RecordType *rtype;
1194 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1195 (rtype = type->getAs<RecordType>())) {
1196
1197 // The capture logic needs the destructor, so make sure we mark it.
1198 // Usually this is unnecessary because most local variables have
1199 // their destructors marked at declaration time, but parameters are
1200 // an exception because it's technically only the call site that
1201 // actually requires the destructor.
1202 if (isa<ParmVarDecl>(var))
1203 S.FinalizeVarWithDestructor(var, rtype);
1204
John McCall351762c2011-02-07 10:33:21 +00001205 // According to the blocks spec, the capture of a variable from
1206 // the stack requires a const copy constructor. This is not true
1207 // of the copy/move done to move a __block variable to the heap.
1208 type.addConst();
1209
1210 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1211 ExprResult result =
1212 S.PerformCopyInitialization(
1213 InitializedEntity::InitializeBlock(var->getLocation(),
1214 type, false),
1215 loc, S.Owned(declRef));
1216
1217 // Build a full-expression copy expression if initialization
1218 // succeeded and used a non-trivial constructor. Recover from
1219 // errors by pretending that the copy isn't necessary.
1220 if (!result.isInvalid() &&
1221 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1222 result = S.MaybeCreateExprWithCleanups(result);
1223 copyExpr = result.take();
1224 }
1225 }
1226
1227 // We're currently at the declarer; go back to the closure.
1228 functionScopesIndex++;
1229 BlockScopeInfo *blockScope =
1230 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1231
1232 // Build a valid capture in this scope.
1233 blockScope->Captures.push_back(
1234 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1235 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1236
1237 // Propagate that to inner captures if necessary.
1238 return propagateCapture(S, functionScopesIndex,
1239 blockScope->Captures.back());
1240}
1241
1242static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1243 const DeclarationNameInfo &NameInfo,
1244 bool byRef) {
1245 assert(isa<VarDecl>(vd) && "capturing non-variable");
1246
1247 VarDecl *var = cast<VarDecl>(vd);
1248 assert(var->hasLocalStorage() && "capturing non-local");
1249 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1250
1251 QualType exprType = var->getType().getNonReferenceType();
1252
1253 BlockDeclRefExpr *BDRE;
1254 if (!byRef) {
1255 // The variable will be bound by copy; make it const within the
1256 // closure, but record that this was done in the expression.
1257 bool constAdded = !exprType.isConstQualified();
1258 exprType.addConst();
1259
1260 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1261 NameInfo.getLoc(), false,
1262 constAdded);
1263 } else {
1264 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1265 NameInfo.getLoc(), true);
1266 }
1267
1268 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001269}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001270
John McCalldadc5752010-08-24 06:29:42 +00001271ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001272Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001273 SourceLocation Loc,
1274 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001275 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001276 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001277}
1278
John McCallf4cd4f92011-02-09 01:13:10 +00001279/// BuildDeclRefExpr - Build an expression that references a
1280/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001281ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001282Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001283 const DeclarationNameInfo &NameInfo,
1284 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001285 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001286
John McCall086a4642010-11-24 05:12:34 +00001287 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001288 SS? SS->getWithLocInContext(Context)
1289 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001290 D, NameInfo, Ty, VK);
1291
1292 // Just in case we're building an illegal pointer-to-member.
1293 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1294 E->setObjectKind(OK_BitField);
1295
1296 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001297}
1298
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001299/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001300/// possibly a list of template arguments.
1301///
1302/// If this produces template arguments, it is permitted to call
1303/// DecomposeTemplateName.
1304///
1305/// This actually loses a lot of source location information for
1306/// non-standard name kinds; we should consider preserving that in
1307/// some way.
Douglas Gregor5476205b2011-06-23 00:49:38 +00001308void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1309 TemplateArgumentListInfo &Buffer,
1310 DeclarationNameInfo &NameInfo,
1311 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001312 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1313 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1314 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1315
Douglas Gregor5476205b2011-06-23 00:49:38 +00001316 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001317 Id.TemplateId->getTemplateArgs(),
1318 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001319 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001320 TemplateArgsPtr.release();
1321
John McCall3e56fd42010-08-23 07:28:44 +00001322 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001323 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001324 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001325 TemplateArgs = &Buffer;
1326 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001327 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001328 TemplateArgs = 0;
1329 }
1330}
1331
John McCalld681c392009-12-16 08:11:27 +00001332/// Diagnose an empty lookup.
1333///
1334/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001335bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1336 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001337 DeclarationName Name = R.getLookupName();
1338
John McCalld681c392009-12-16 08:11:27 +00001339 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001340 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001341 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1342 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001343 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001344 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001345 diagnostic_suggest = diag::err_undeclared_use_suggest;
1346 }
John McCalld681c392009-12-16 08:11:27 +00001347
Douglas Gregor598b08f2009-12-31 05:20:13 +00001348 // If the original lookup was an unqualified lookup, fake an
1349 // unqualified lookup. This is useful when (for example) the
1350 // original lookup would not have found something because it was a
1351 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001352 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001353 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001354 if (isa<CXXRecordDecl>(DC)) {
1355 LookupQualifiedName(R, DC);
1356
1357 if (!R.empty()) {
1358 // Don't give errors about ambiguities in this lookup.
1359 R.suppressDiagnostics();
1360
1361 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1362 bool isInstance = CurMethod &&
1363 CurMethod->isInstance() &&
1364 DC == CurMethod->getParent();
1365
1366 // Give a code modification hint to insert 'this->'.
1367 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1368 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001369 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001370 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1371 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001372 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001373 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001374 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001375 Diag(R.getNameLoc(), diagnostic) << Name
1376 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1377 QualType DepThisType = DepMethod->getThisType(Context);
1378 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1379 R.getNameLoc(), DepThisType, false);
1380 TemplateArgumentListInfo TList;
1381 if (ULE->hasExplicitTemplateArgs())
1382 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001383
Douglas Gregore16af532011-02-28 18:50:33 +00001384 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001385 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001386 CXXDependentScopeMemberExpr *DepExpr =
1387 CXXDependentScopeMemberExpr::Create(
1388 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001389 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001390 R.getLookupNameInfo(), &TList);
1391 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001392 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001393 // FIXME: we should be able to handle this case too. It is correct
1394 // to add this-> here. This is a workaround for PR7947.
1395 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001396 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001397 } else {
John McCalld681c392009-12-16 08:11:27 +00001398 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001399 }
John McCalld681c392009-12-16 08:11:27 +00001400
1401 // Do we really want to note all of these?
1402 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1403 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1404
1405 // Tell the callee to try to recover.
1406 return false;
1407 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001408
1409 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001410 }
1411 }
1412
Douglas Gregor598b08f2009-12-31 05:20:13 +00001413 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001414 TypoCorrection Corrected;
1415 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1416 S, &SS, NULL, false, CTC))) {
1417 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1418 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1419 R.setLookupName(Corrected.getCorrection());
1420
Hans Wennborg38198de2011-07-12 08:45:31 +00001421 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001422 R.addDecl(ND);
1423 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001424 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001425 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1426 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001427 else
1428 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001429 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001430 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001431 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1432 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001433 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001434 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001435
1436 // Tell the callee to try to recover.
1437 return false;
1438 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001439
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001440 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001441 // FIXME: If we ended up with a typo for a type name or
1442 // Objective-C class name, we're in trouble because the parser
1443 // is in the wrong place to recover. Suggest the typo
1444 // correction, but don't make it a fix-it since we're not going
1445 // to recover well anyway.
1446 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001447 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001448 else
1449 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001450 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001451 << SS.getRange();
1452
1453 // Don't try to recover; it won't work.
1454 return true;
1455 }
1456 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001457 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001458 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001459 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001460 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001461 else
Douglas Gregor25363982010-01-01 00:15:04 +00001462 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001463 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001464 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001465 return true;
1466 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001467 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001468 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001469
1470 // Emit a special diagnostic for failed member lookups.
1471 // FIXME: computing the declaration context might fail here (?)
1472 if (!SS.isEmpty()) {
1473 Diag(R.getNameLoc(), diag::err_no_member)
1474 << Name << computeDeclContext(SS, false)
1475 << SS.getRange();
1476 return true;
1477 }
1478
John McCalld681c392009-12-16 08:11:27 +00001479 // Give up, we can't recover.
1480 Diag(R.getNameLoc(), diagnostic) << Name;
1481 return true;
1482}
1483
Douglas Gregor05fcf842010-11-02 20:36:02 +00001484ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1485 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001486 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1487 if (!IDecl)
1488 return 0;
1489 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1490 if (!ClassImpDecl)
1491 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001492 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001493 if (!property)
1494 return 0;
1495 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001496 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1497 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001498 return 0;
1499 return property;
1500}
1501
Douglas Gregor05fcf842010-11-02 20:36:02 +00001502bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1503 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1504 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1505 if (!IDecl)
1506 return false;
1507 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1508 if (!ClassImpDecl)
1509 return false;
1510 if (ObjCPropertyImplDecl *PIDecl
1511 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1512 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1513 PIDecl->getPropertyIvarDecl())
1514 return false;
1515
1516 return true;
1517}
1518
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001519ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1520 IdentifierInfo *II,
1521 SourceLocation NameLoc) {
1522 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001523 bool LookForIvars;
1524 if (Lookup.empty())
1525 LookForIvars = true;
1526 else if (CurMeth->isClassMethod())
1527 LookForIvars = false;
1528 else
1529 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001530 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1531 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001532 if (!LookForIvars)
1533 return 0;
1534
Fariborz Jahanian18722982010-07-17 00:59:30 +00001535 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1536 if (!IDecl)
1537 return 0;
1538 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001539 if (!ClassImpDecl)
1540 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001541 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001542 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001543 if (!property)
1544 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001545 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001546 DynamicImplSeen =
1547 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001548 // property implementation has a designated ivar. No need to assume a new
1549 // one.
1550 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1551 return 0;
1552 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001553 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001554 QualType PropType = Context.getCanonicalType(property->getType());
1555 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001556 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001557 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001558 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001559 (Expr *)0, true);
1560 ClassImpDecl->addDecl(Ivar);
1561 IDecl->makeDeclVisibleInContext(Ivar, false);
1562 property->setPropertyIvarDecl(Ivar);
1563 return Ivar;
1564 }
1565 return 0;
1566}
1567
John McCalldadc5752010-08-24 06:29:42 +00001568ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001569 CXXScopeSpec &SS,
1570 UnqualifiedId &Id,
1571 bool HasTrailingLParen,
1572 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001573 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1574 "cannot be direct & operand and have a trailing lparen");
1575
1576 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001577 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001578
John McCall10eae182009-11-30 22:42:35 +00001579 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001580
1581 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001582 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001583 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001584 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001585
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001586 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001587 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001588 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001589
John McCalle66edc12009-11-24 19:00:30 +00001590 // C++ [temp.dep.expr]p3:
1591 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001592 // -- an identifier that was declared with a dependent type,
1593 // (note: handled after lookup)
1594 // -- a template-id that is dependent,
1595 // (note: handled in BuildTemplateIdExpr)
1596 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001597 // -- a nested-name-specifier that contains a class-name that
1598 // names a dependent type.
1599 // Determine whether this is a member of an unknown specialization;
1600 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001601 bool DependentID = false;
1602 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1603 Name.getCXXNameType()->isDependentType()) {
1604 DependentID = true;
1605 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001606 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001607 if (RequireCompleteDeclContext(SS, DC))
1608 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001609 } else {
1610 DependentID = true;
1611 }
1612 }
1613
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001614 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001615 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001616 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001617
Fariborz Jahanian86151342010-07-22 23:33:21 +00001618 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001619 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001620 LookupResult R(*this, NameInfo,
1621 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1622 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001623 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001624 // Lookup the template name again to correctly establish the context in
1625 // which it was found. This is really unfortunate as we already did the
1626 // lookup to determine that it was a template name in the first place. If
1627 // this becomes a performance hit, we can work harder to preserve those
1628 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001629 bool MemberOfUnknownSpecialization;
1630 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1631 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001632
1633 if (MemberOfUnknownSpecialization ||
1634 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1635 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1636 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001637 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001638 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001639 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Douglas Gregora5226932011-02-04 13:35:07 +00001641 // If the result might be in a dependent base class, this is a dependent
1642 // id-expression.
1643 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1644 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1645 TemplateArgs);
1646
John McCalle66edc12009-11-24 19:00:30 +00001647 // If this reference is in an Objective-C method, then we need to do
1648 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001649 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001650 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001651 if (E.isInvalid())
1652 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001653
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001654 if (Expr *Ex = E.takeAs<Expr>())
1655 return Owned(Ex);
1656
1657 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001658 if (getLangOptions().ObjCDefaultSynthProperties &&
1659 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001660 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001661 if (const ObjCPropertyDecl *Property =
1662 canSynthesizeProvisionalIvar(II)) {
1663 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1664 Diag(Property->getLocation(), diag::note_property_declare);
1665 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001666 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1667 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001668 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001669 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001670 // for further use, this must be set to false if in class method.
1671 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001672 }
Chris Lattner59a25942008-03-31 00:36:02 +00001673 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001674
John McCalle66edc12009-11-24 19:00:30 +00001675 if (R.isAmbiguous())
1676 return ExprError();
1677
Douglas Gregor171c45a2009-02-18 21:56:37 +00001678 // Determine whether this name might be a candidate for
1679 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001680 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001681
John McCalle66edc12009-11-24 19:00:30 +00001682 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001683 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001684 // in C90, extension in C99, forbidden in C++).
1685 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1686 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1687 if (D) R.addDecl(D);
1688 }
1689
1690 // If this name wasn't predeclared and if this is not a function
1691 // call, diagnose the problem.
1692 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001693 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001694 return ExprError();
1695
1696 assert(!R.empty() &&
1697 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001698
1699 // If we found an Objective-C instance variable, let
1700 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001701 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001702 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1703 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001704 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001705 assert(E.isInvalid() || E.get());
1706 return move(E);
1707 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001708 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
John McCalle66edc12009-11-24 19:00:30 +00001711 // This is guaranteed from this point on.
1712 assert(!R.empty() || ADL);
1713
John McCall2d74de92009-12-01 22:10:20 +00001714 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001715 // C++ [class.mfct.non-static]p3:
1716 // When an id-expression that is not part of a class member access
1717 // syntax and not used to form a pointer to member is used in the
1718 // body of a non-static member function of class X, if name lookup
1719 // resolves the name in the id-expression to a non-static non-type
1720 // member of some class C, the id-expression is transformed into a
1721 // class member access expression using (*this) as the
1722 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001723 //
1724 // But we don't actually need to do this for '&' operands if R
1725 // resolved to a function or overloaded function set, because the
1726 // expression is ill-formed if it actually works out to be a
1727 // non-static member function:
1728 //
1729 // C++ [expr.ref]p4:
1730 // Otherwise, if E1.E2 refers to a non-static member function. . .
1731 // [t]he expression can be used only as the left-hand operand of a
1732 // member function call.
1733 //
1734 // There are other safeguards against such uses, but it's important
1735 // to get this right here so that we don't end up making a
1736 // spuriously dependent expression if we're inside a dependent
1737 // instance method.
John McCall57500772009-12-16 12:17:52 +00001738 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001739 bool MightBeImplicitMember;
1740 if (!isAddressOfOperand)
1741 MightBeImplicitMember = true;
1742 else if (!SS.isEmpty())
1743 MightBeImplicitMember = false;
1744 else if (R.isOverloadedResult())
1745 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001746 else if (R.isUnresolvableResult())
1747 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001748 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001749 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1750 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001751
1752 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001753 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001754 }
1755
John McCalle66edc12009-11-24 19:00:30 +00001756 if (TemplateArgs)
1757 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001758
John McCalle66edc12009-11-24 19:00:30 +00001759 return BuildDeclarationNameExpr(SS, R, ADL);
1760}
1761
John McCall10eae182009-11-30 22:42:35 +00001762/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1763/// declaration name, generally during template instantiation.
1764/// There's a large number of things which don't need to be done along
1765/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001766ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001767Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001768 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001769 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001770 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001771 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001772
John McCall0b66eb32010-05-01 00:40:08 +00001773 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001774 return ExprError();
1775
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001776 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001777 LookupQualifiedName(R, DC);
1778
1779 if (R.isAmbiguous())
1780 return ExprError();
1781
1782 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001783 Diag(NameInfo.getLoc(), diag::err_no_member)
1784 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001785 return ExprError();
1786 }
1787
1788 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1789}
1790
1791/// LookupInObjCMethod - The parser has read a name in, and Sema has
1792/// detected that we're currently inside an ObjC method. Perform some
1793/// additional lookup.
1794///
1795/// Ideally, most of this would be done by lookup, but there's
1796/// actually quite a lot of extra work involved.
1797///
1798/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001799ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001800Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001801 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001802 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001803 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001804
John McCalle66edc12009-11-24 19:00:30 +00001805 // There are two cases to handle here. 1) scoped lookup could have failed,
1806 // in which case we should look for an ivar. 2) scoped lookup could have
1807 // found a decl, but that decl is outside the current instance method (i.e.
1808 // a global variable). In these two cases, we do a lookup for an ivar with
1809 // this name, if the lookup sucedes, we replace it our current decl.
1810
1811 // If we're in a class method, we don't normally want to look for
1812 // ivars. But if we don't find anything else, and there's an
1813 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001814 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001815
1816 bool LookForIvars;
1817 if (Lookup.empty())
1818 LookForIvars = true;
1819 else if (IsClassMethod)
1820 LookForIvars = false;
1821 else
1822 LookForIvars = (Lookup.isSingleResult() &&
1823 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001824 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001825 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001826 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001827 ObjCInterfaceDecl *ClassDeclared;
1828 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1829 // Diagnose using an ivar in a class method.
1830 if (IsClassMethod)
1831 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1832 << IV->getDeclName());
1833
1834 // If we're referencing an invalid decl, just return this as a silent
1835 // error node. The error diagnostic was already emitted on the decl.
1836 if (IV->isInvalidDecl())
1837 return ExprError();
1838
1839 // Check if referencing a field with __attribute__((deprecated)).
1840 if (DiagnoseUseOfDecl(IV, Loc))
1841 return ExprError();
1842
1843 // Diagnose the use of an ivar outside of the declaring class.
1844 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1845 ClassDeclared != IFace)
1846 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1847
1848 // FIXME: This should use a new expr for a direct reference, don't
1849 // turn this into Self->ivar, just return a BareIVarExpr or something.
1850 IdentifierInfo &II = Context.Idents.get("self");
1851 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001852 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001853 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001854 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001855 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001856 SelfName, false, false);
1857 if (SelfExpr.isInvalid())
1858 return ExprError();
1859
John Wiegley01296292011-04-08 18:41:53 +00001860 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1861 if (SelfExpr.isInvalid())
1862 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001863
John McCalle66edc12009-11-24 19:00:30 +00001864 MarkDeclarationReferenced(Loc, IV);
1865 return Owned(new (Context)
1866 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001867 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001868 }
Chris Lattner87313662010-04-12 05:10:17 +00001869 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001870 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001871 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001872 ObjCInterfaceDecl *ClassDeclared;
1873 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1874 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1875 IFace == ClassDeclared)
1876 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1877 }
1878 }
1879
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001880 if (Lookup.empty() && II && AllowBuiltinCreation) {
1881 // FIXME. Consolidate this with similar code in LookupName.
1882 if (unsigned BuiltinID = II->getBuiltinID()) {
1883 if (!(getLangOptions().CPlusPlus &&
1884 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1885 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1886 S, Lookup.isForRedeclaration(),
1887 Lookup.getNameLoc());
1888 if (D) Lookup.addDecl(D);
1889 }
1890 }
1891 }
John McCalle66edc12009-11-24 19:00:30 +00001892 // Sentinel value saying that we didn't do anything special.
1893 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001894}
John McCalld14a8642009-11-21 08:51:07 +00001895
John McCall16df1e52010-03-30 21:47:33 +00001896/// \brief Cast a base object to a member's actual type.
1897///
1898/// Logically this happens in three phases:
1899///
1900/// * First we cast from the base type to the naming class.
1901/// The naming class is the class into which we were looking
1902/// when we found the member; it's the qualifier type if a
1903/// qualifier was provided, and otherwise it's the base type.
1904///
1905/// * Next we cast from the naming class to the declaring class.
1906/// If the member we found was brought into a class's scope by
1907/// a using declaration, this is that class; otherwise it's
1908/// the class declaring the member.
1909///
1910/// * Finally we cast from the declaring class to the "true"
1911/// declaring class of the member. This conversion does not
1912/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001913ExprResult
1914Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001915 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001916 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001917 NamedDecl *Member) {
1918 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1919 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001920 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001921
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001922 QualType DestRecordType;
1923 QualType DestType;
1924 QualType FromRecordType;
1925 QualType FromType = From->getType();
1926 bool PointerConversions = false;
1927 if (isa<FieldDecl>(Member)) {
1928 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001929
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 if (FromType->getAs<PointerType>()) {
1931 DestType = Context.getPointerType(DestRecordType);
1932 FromRecordType = FromType->getPointeeType();
1933 PointerConversions = true;
1934 } else {
1935 DestType = DestRecordType;
1936 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001937 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001938 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1939 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001940 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001941
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001942 DestType = Method->getThisType(Context);
1943 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001944
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001945 if (FromType->getAs<PointerType>()) {
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 FromRecordType = FromType;
1950 DestType = DestRecordType;
1951 }
1952 } else {
1953 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001954 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001955 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001957 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001958 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001959
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 // If the unqualified types are the same, no conversion is necessary.
1961 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001962 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001963
John McCall16df1e52010-03-30 21:47:33 +00001964 SourceRange FromRange = From->getSourceRange();
1965 SourceLocation FromLoc = FromRange.getBegin();
1966
John McCall2536c6d2010-08-25 10:28:54 +00001967 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001968
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001969 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001970 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001971 // class name.
1972 //
1973 // If the member was a qualified name and the qualified referred to a
1974 // specific base subobject type, we'll cast to that intermediate type
1975 // first and then to the object in which the member is declared. That allows
1976 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1977 //
1978 // class Base { public: int x; };
1979 // class Derived1 : public Base { };
1980 // class Derived2 : public Base { };
1981 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1982 //
1983 // void VeryDerived::f() {
1984 // x = 17; // error: ambiguous base subobjects
1985 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1986 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001987 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001988 QualType QType = QualType(Qualifier->getAsType(), 0);
1989 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1990 assert(QType->isRecordType() && "lookup done with non-record type");
1991
1992 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1993
1994 // In C++98, the qualifier type doesn't actually have to be a base
1995 // type of the object type, in which case we just ignore it.
1996 // Otherwise build the appropriate casts.
1997 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001998 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001999 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002000 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002001 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002002
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002003 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002004 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002005 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2006 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002007
2008 FromType = QType;
2009 FromRecordType = QRecordType;
2010
2011 // If the qualifier type was the same as the destination type,
2012 // we're done.
2013 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002014 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002015 }
2016 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002017
John McCall16df1e52010-03-30 21:47:33 +00002018 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002019
John McCall16df1e52010-03-30 21:47:33 +00002020 // If we actually found the member through a using declaration, cast
2021 // down to the using declaration's type.
2022 //
2023 // Pointer equality is fine here because only one declaration of a
2024 // class ever has member declarations.
2025 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2026 assert(isa<UsingShadowDecl>(FoundDecl));
2027 QualType URecordType = Context.getTypeDeclType(
2028 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2029
2030 // We only need to do this if the naming-class to declaring-class
2031 // conversion is non-trivial.
2032 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2033 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002034 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002035 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002036 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002037 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002038
John McCall16df1e52010-03-30 21:47:33 +00002039 QualType UType = URecordType;
2040 if (PointerConversions)
2041 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002042 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2043 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002044 FromType = UType;
2045 FromRecordType = URecordType;
2046 }
2047
2048 // We don't do access control for the conversion from the
2049 // declaring class to the true declaring class.
2050 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002051 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002052
John McCallcf142162010-08-07 06:22:56 +00002053 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2055 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002056 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002057 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002058
John Wiegley01296292011-04-08 18:41:53 +00002059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2060 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002061}
Douglas Gregor3256d042009-06-30 15:47:41 +00002062
John McCalle66edc12009-11-24 19:00:30 +00002063bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002064 const LookupResult &R,
2065 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002066 // Only when used directly as the postfix-expression of a call.
2067 if (!HasTrailingLParen)
2068 return false;
2069
2070 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002071 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002072 return false;
2073
2074 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002075 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002076 return false;
2077
2078 // Turn off ADL when we find certain kinds of declarations during
2079 // normal lookup:
2080 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2081 NamedDecl *D = *I;
2082
2083 // C++0x [basic.lookup.argdep]p3:
2084 // -- a declaration of a class member
2085 // Since using decls preserve this property, we check this on the
2086 // original decl.
John McCall57500772009-12-16 12:17:52 +00002087 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002088 return false;
2089
2090 // C++0x [basic.lookup.argdep]p3:
2091 // -- a block-scope function declaration that is not a
2092 // using-declaration
2093 // NOTE: we also trigger this for function templates (in fact, we
2094 // don't check the decl type at all, since all other decl types
2095 // turn off ADL anyway).
2096 if (isa<UsingShadowDecl>(D))
2097 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2098 else if (D->getDeclContext()->isFunctionOrMethod())
2099 return false;
2100
2101 // C++0x [basic.lookup.argdep]p3:
2102 // -- a declaration that is neither a function or a function
2103 // template
2104 // And also for builtin functions.
2105 if (isa<FunctionDecl>(D)) {
2106 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2107
2108 // But also builtin functions.
2109 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2110 return false;
2111 } else if (!isa<FunctionTemplateDecl>(D))
2112 return false;
2113 }
2114
2115 return true;
2116}
2117
2118
John McCalld14a8642009-11-21 08:51:07 +00002119/// Diagnoses obvious problems with the use of the given declaration
2120/// as an expression. This is only actually called for lookups that
2121/// were not overloaded, and it doesn't promise that the declaration
2122/// will in fact be used.
2123static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002124 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2126 return true;
2127 }
2128
2129 if (isa<ObjCInterfaceDecl>(D)) {
2130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2131 return true;
2132 }
2133
2134 if (isa<NamespaceDecl>(D)) {
2135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2136 return true;
2137 }
2138
2139 return false;
2140}
2141
John McCalldadc5752010-08-24 06:29:42 +00002142ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002143Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002144 LookupResult &R,
2145 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002146 // If this is a single, fully-resolved result and we don't need ADL,
2147 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002148 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002149 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2150 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002151
2152 // We only need to check the declaration if there's exactly one
2153 // result, because in the overloaded case the results can only be
2154 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002155 if (R.isSingleResult() &&
2156 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002157 return ExprError();
2158
John McCall58cc69d2010-01-27 01:50:18 +00002159 // Otherwise, just build an unresolved lookup expression. Suppress
2160 // any lookup-related diagnostics; we'll hash these out later, when
2161 // we've picked a target.
2162 R.suppressDiagnostics();
2163
John McCalld14a8642009-11-21 08:51:07 +00002164 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002165 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002166 SS.getWithLocInContext(Context),
2167 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002168 NeedsADL, R.isOverloadedResult(),
2169 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002170
2171 return Owned(ULE);
2172}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002173
John McCalld14a8642009-11-21 08:51:07 +00002174/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002175ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002176Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002177 const DeclarationNameInfo &NameInfo,
2178 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002179 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002180 assert(!isa<FunctionTemplateDecl>(D) &&
2181 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002182
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002183 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002184 if (CheckDeclInExpr(*this, Loc, D))
2185 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002186
Douglas Gregore7488b92009-12-01 16:58:18 +00002187 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2188 // Specifically diagnose references to class templates that are missing
2189 // a template argument list.
2190 Diag(Loc, diag::err_template_decl_ref)
2191 << Template << SS.getRange();
2192 Diag(Template->getLocation(), diag::note_template_decl_here);
2193 return ExprError();
2194 }
2195
2196 // Make sure that we're referring to a value.
2197 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2198 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002199 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002200 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002201 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002202 return ExprError();
2203 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002204
Douglas Gregor171c45a2009-02-18 21:56:37 +00002205 // Check whether this declaration can be used. Note that we suppress
2206 // this check when we're going to perform argument-dependent lookup
2207 // on this function name, because this might not be the function
2208 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002209 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002210 return ExprError();
2211
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002212 // Only create DeclRefExpr's for valid Decl's.
2213 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002214 return ExprError();
2215
John McCallf3a88602011-02-03 08:15:49 +00002216 // Handle members of anonymous structs and unions. If we got here,
2217 // and the reference is to a class member indirect field, then this
2218 // must be the subject of a pointer-to-member expression.
2219 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2220 if (!indirectField->isCXXClassMember())
2221 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2222 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002223
Chris Lattner2a9d9892008-10-20 05:16:36 +00002224 // If the identifier reference is inside a block, and it refers to a value
2225 // that is outside the block, create a BlockDeclRefExpr instead of a
2226 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2227 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002228 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002229 // We do not do this for things like enum constants, global variables, etc,
2230 // as they do not get snapshotted.
2231 //
John McCall351762c2011-02-07 10:33:21 +00002232 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002233 case CR_Error:
2234 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002235
John McCallc63de662011-02-02 13:00:07 +00002236 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002237 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2238 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2239
2240 case CR_CaptureByRef:
2241 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2242 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002243
2244 case CR_NoCapture: {
2245 // If this reference is not in a block or if the referenced
2246 // variable is within the block, create a normal DeclRefExpr.
2247
2248 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002249 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002250
2251 switch (D->getKind()) {
2252 // Ignore all the non-ValueDecl kinds.
2253#define ABSTRACT_DECL(kind)
2254#define VALUE(type, base)
2255#define DECL(type, base) \
2256 case Decl::type:
2257#include "clang/AST/DeclNodes.inc"
2258 llvm_unreachable("invalid value decl kind");
2259 return ExprError();
2260
2261 // These shouldn't make it here.
2262 case Decl::ObjCAtDefsField:
2263 case Decl::ObjCIvar:
2264 llvm_unreachable("forming non-member reference to ivar?");
2265 return ExprError();
2266
2267 // Enum constants are always r-values and never references.
2268 // Unresolved using declarations are dependent.
2269 case Decl::EnumConstant:
2270 case Decl::UnresolvedUsingValue:
2271 valueKind = VK_RValue;
2272 break;
2273
2274 // Fields and indirect fields that got here must be for
2275 // pointer-to-member expressions; we just call them l-values for
2276 // internal consistency, because this subexpression doesn't really
2277 // exist in the high-level semantics.
2278 case Decl::Field:
2279 case Decl::IndirectField:
2280 assert(getLangOptions().CPlusPlus &&
2281 "building reference to field in C?");
2282
2283 // These can't have reference type in well-formed programs, but
2284 // for internal consistency we do this anyway.
2285 type = type.getNonReferenceType();
2286 valueKind = VK_LValue;
2287 break;
2288
2289 // Non-type template parameters are either l-values or r-values
2290 // depending on the type.
2291 case Decl::NonTypeTemplateParm: {
2292 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2293 type = reftype->getPointeeType();
2294 valueKind = VK_LValue; // even if the parameter is an r-value reference
2295 break;
2296 }
2297
2298 // For non-references, we need to strip qualifiers just in case
2299 // the template parameter was declared as 'const int' or whatever.
2300 valueKind = VK_RValue;
2301 type = type.getUnqualifiedType();
2302 break;
2303 }
2304
2305 case Decl::Var:
2306 // In C, "extern void blah;" is valid and is an r-value.
2307 if (!getLangOptions().CPlusPlus &&
2308 !type.hasQualifiers() &&
2309 type->isVoidType()) {
2310 valueKind = VK_RValue;
2311 break;
2312 }
2313 // fallthrough
2314
2315 case Decl::ImplicitParam:
2316 case Decl::ParmVar:
2317 // These are always l-values.
2318 valueKind = VK_LValue;
2319 type = type.getNonReferenceType();
2320 break;
2321
2322 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002323 const FunctionType *fty = type->castAs<FunctionType>();
2324
2325 // If we're referring to a function with an __unknown_anytype
2326 // result type, make the entire expression __unknown_anytype.
2327 if (fty->getResultType() == Context.UnknownAnyTy) {
2328 type = Context.UnknownAnyTy;
2329 valueKind = VK_RValue;
2330 break;
2331 }
2332
John McCallf4cd4f92011-02-09 01:13:10 +00002333 // Functions are l-values in C++.
2334 if (getLangOptions().CPlusPlus) {
2335 valueKind = VK_LValue;
2336 break;
2337 }
2338
2339 // C99 DR 316 says that, if a function type comes from a
2340 // function definition (without a prototype), that type is only
2341 // used for checking compatibility. Therefore, when referencing
2342 // the function, we pretend that we don't have the full function
2343 // type.
John McCall2979fe02011-04-12 00:42:48 +00002344 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2345 isa<FunctionProtoType>(fty))
2346 type = Context.getFunctionNoProtoType(fty->getResultType(),
2347 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002348
2349 // Functions are r-values in C.
2350 valueKind = VK_RValue;
2351 break;
2352 }
2353
2354 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002355 // If we're referring to a method with an __unknown_anytype
2356 // result type, make the entire expression __unknown_anytype.
2357 // This should only be possible with a type written directly.
2358 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2359 if (proto->getResultType() == Context.UnknownAnyTy) {
2360 type = Context.UnknownAnyTy;
2361 valueKind = VK_RValue;
2362 break;
2363 }
2364
John McCallf4cd4f92011-02-09 01:13:10 +00002365 // C++ methods are l-values if static, r-values if non-static.
2366 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2367 valueKind = VK_LValue;
2368 break;
2369 }
2370 // fallthrough
2371
2372 case Decl::CXXConversion:
2373 case Decl::CXXDestructor:
2374 case Decl::CXXConstructor:
2375 valueKind = VK_RValue;
2376 break;
2377 }
2378
2379 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2380 }
2381
John McCallc63de662011-02-02 13:00:07 +00002382 }
John McCall7decc9e2010-11-18 06:31:45 +00002383
John McCall351762c2011-02-07 10:33:21 +00002384 llvm_unreachable("unknown capture result");
2385 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002386}
Chris Lattnere168f762006-11-10 05:29:30 +00002387
John McCall2979fe02011-04-12 00:42:48 +00002388ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002389 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002390
Chris Lattnere168f762006-11-10 05:29:30 +00002391 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002392 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002393 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2394 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2395 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002396 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002397
Chris Lattnera81a0272008-01-12 08:14:25 +00002398 // Pre-defined identifiers are of type char[x], where x is the length of the
2399 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002400
Anders Carlsson2fb08242009-09-08 18:24:21 +00002401 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002402 if (!currentDecl && getCurBlock())
2403 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002404 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002405 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002406 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002407 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002408
Anders Carlsson0b209a82009-09-11 01:22:35 +00002409 QualType ResTy;
2410 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2411 ResTy = Context.DependentTy;
2412 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002413 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002414
Anders Carlsson0b209a82009-09-11 01:22:35 +00002415 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002416 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002417 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2418 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002419 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002420}
2421
John McCalldadc5752010-08-24 06:29:42 +00002422ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002423 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002424 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002425 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002426 if (Invalid)
2427 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002428
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002429 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002430 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002431 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002432 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002433
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002434 QualType Ty;
2435 if (!getLangOptions().CPlusPlus)
2436 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2437 else if (Literal.isWide())
2438 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002439 else if (Literal.isUTF16())
2440 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2441 else if (Literal.isUTF32())
2442 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002443 else if (Literal.isMultiChar())
2444 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002445 else
2446 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002447
Douglas Gregorfb65e592011-07-27 05:40:30 +00002448 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2449 if (Literal.isWide())
2450 Kind = CharacterLiteral::Wide;
2451 else if (Literal.isUTF16())
2452 Kind = CharacterLiteral::UTF16;
2453 else if (Literal.isUTF32())
2454 Kind = CharacterLiteral::UTF32;
2455
2456 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2457 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002458}
2459
John McCalldadc5752010-08-24 06:29:42 +00002460ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002461 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002462 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2463 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002464 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002465 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002466 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002467 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002468 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002469
Chris Lattner23b7eb62007-06-15 23:05:46 +00002470 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002471 // Add padding so that NumericLiteralParser can overread by one character.
2472 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002473 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002474
Chris Lattner67ca9252007-05-21 01:08:44 +00002475 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002476 bool Invalid = false;
2477 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2478 if (Invalid)
2479 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002480
Mike Stump11289f42009-09-09 15:08:12 +00002481 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002482 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002483 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002484 return ExprError();
2485
Chris Lattner1c20a172007-08-26 03:42:43 +00002486 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002487
Chris Lattner1c20a172007-08-26 03:42:43 +00002488 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002489 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002490 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002491 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002492 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002493 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002494 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002495 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002496
2497 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2498
John McCall53b93a02009-12-24 09:08:04 +00002499 using llvm::APFloat;
2500 APFloat Val(Format);
2501
2502 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002503
2504 // Overflow is always an error, but underflow is only an error if
2505 // we underflowed to zero (APFloat reports denormals as underflow).
2506 if ((result & APFloat::opOverflow) ||
2507 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002508 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002509 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002510 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002511 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002512 APFloat::getLargest(Format).toString(buffer);
2513 } else {
John McCall62abc942010-02-26 23:35:57 +00002514 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002515 APFloat::getSmallest(Format).toString(buffer);
2516 }
2517
2518 Diag(Tok.getLocation(), diagnostic)
2519 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002520 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002521 }
2522
2523 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002524 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002525
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002526 if (Ty == Context.DoubleTy) {
2527 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002528 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002529 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2530 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002531 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002532 }
2533 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002534 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002535 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002536 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002537 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002538
Neil Boothac582c52007-08-29 22:00:19 +00002539 // long long is a C99 feature.
2540 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002541 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002542 Diag(Tok.getLocation(), diag::ext_longlong);
2543
Chris Lattner67ca9252007-05-21 01:08:44 +00002544 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002545 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002546
Chris Lattner67ca9252007-05-21 01:08:44 +00002547 if (Literal.GetIntegerValue(ResultVal)) {
2548 // If this value didn't fit into uintmax_t, warn and force to ull.
2549 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002550 Ty = Context.UnsignedLongLongTy;
2551 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002552 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002553 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002554 // If this value fits into a ULL, try to figure out what else it fits into
2555 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002556
Chris Lattner67ca9252007-05-21 01:08:44 +00002557 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2558 // be an unsigned int.
2559 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2560
2561 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002562 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002563 if (!Literal.isLong && !Literal.isLongLong) {
2564 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002565 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002566
Chris Lattner67ca9252007-05-21 01:08:44 +00002567 // Does it fit in a unsigned int?
2568 if (ResultVal.isIntN(IntSize)) {
2569 // Does it fit in a signed int?
2570 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002571 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002573 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002574 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002575 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002576 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Chris Lattner67ca9252007-05-21 01:08:44 +00002578 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002579 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002580 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 // Does it fit in a unsigned long?
2583 if (ResultVal.isIntN(LongSize)) {
2584 // Does it fit in a signed long?
2585 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002586 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002587 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002588 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002589 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002590 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002591 }
2592
Chris Lattner67ca9252007-05-21 01:08:44 +00002593 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002594 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002595 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002596
Chris Lattner67ca9252007-05-21 01:08:44 +00002597 // Does it fit in a unsigned long long?
2598 if (ResultVal.isIntN(LongLongSize)) {
2599 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002600 // To be compatible with MSVC, hex integer literals ending with the
2601 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002602 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2603 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002604 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002605 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002606 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002607 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002608 }
2609 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002610
Chris Lattner67ca9252007-05-21 01:08:44 +00002611 // If we still couldn't decide a type, we probably have something that
2612 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002613 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002614 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002615 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002616 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002617 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002618
Chris Lattner55258cf2008-05-09 05:59:00 +00002619 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002620 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002621 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002622 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002623 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002624
Chris Lattner1c20a172007-08-26 03:42:43 +00002625 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2626 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002627 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002628 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002629
2630 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002631}
2632
John McCalldadc5752010-08-24 06:29:42 +00002633ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002634 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002635 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002636 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002637}
2638
Chandler Carruth62da79c2011-05-26 08:53:12 +00002639static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2640 SourceLocation Loc,
2641 SourceRange ArgRange) {
2642 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2643 // scalar or vector data type argument..."
2644 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2645 // type (C99 6.2.5p18) or void.
2646 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2647 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2648 << T << ArgRange;
2649 return true;
2650 }
2651
2652 assert((T->isVoidType() || !T->isIncompleteType()) &&
2653 "Scalar types should always be complete");
2654 return false;
2655}
2656
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002657static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2658 SourceLocation Loc,
2659 SourceRange ArgRange,
2660 UnaryExprOrTypeTrait TraitKind) {
2661 // C99 6.5.3.4p1:
2662 if (T->isFunctionType()) {
2663 // alignof(function) is allowed as an extension.
2664 if (TraitKind == UETT_SizeOf)
2665 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2666 return false;
2667 }
2668
2669 // Allow sizeof(void)/alignof(void) as an extension.
2670 if (T->isVoidType()) {
2671 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2672 return false;
2673 }
2674
2675 return true;
2676}
2677
2678static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2679 SourceLocation Loc,
2680 SourceRange ArgRange,
2681 UnaryExprOrTypeTrait TraitKind) {
2682 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2683 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2684 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2685 << T << (TraitKind == UETT_SizeOf)
2686 << ArgRange;
2687 return true;
2688 }
2689
2690 return false;
2691}
2692
Chandler Carruth14502c22011-05-26 08:53:10 +00002693/// \brief Check the constrains on expression operands to unary type expression
2694/// and type traits.
2695///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002696/// Completes any types necessary and validates the constraints on the operand
2697/// expression. The logic mostly mirrors the type-based overload, but may modify
2698/// the expression as it completes the type for that expression through template
2699/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002700bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2701 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002702 QualType ExprTy = Op->getType();
2703
2704 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2705 // the result is the size of the referenced type."
2706 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2707 // result shall be the alignment of the referenced type."
2708 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2709 ExprTy = Ref->getPointeeType();
2710
2711 if (ExprKind == UETT_VecStep)
2712 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2713 Op->getSourceRange());
2714
2715 // Whitelist some types as extensions
2716 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2717 Op->getSourceRange(), ExprKind))
2718 return false;
2719
2720 if (RequireCompleteExprType(Op,
2721 PDiag(diag::err_sizeof_alignof_incomplete_type)
2722 << ExprKind << Op->getSourceRange(),
2723 std::make_pair(SourceLocation(), PDiag(0))))
2724 return true;
2725
2726 // Completeing the expression's type may have changed it.
2727 ExprTy = Op->getType();
2728 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2729 ExprTy = Ref->getPointeeType();
2730
2731 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2732 Op->getSourceRange(), ExprKind))
2733 return true;
2734
Nico Weber0870deb2011-06-15 02:47:03 +00002735 if (ExprKind == UETT_SizeOf) {
2736 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2737 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2738 QualType OType = PVD->getOriginalType();
2739 QualType Type = PVD->getType();
2740 if (Type->isPointerType() && OType->isArrayType()) {
2741 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2742 << Type << OType;
2743 Diag(PVD->getLocation(), diag::note_declared_at);
2744 }
2745 }
2746 }
2747 }
2748
Chandler Carruth7c430c02011-05-27 01:33:31 +00002749 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002750}
2751
2752/// \brief Check the constraints on operands to unary expression and type
2753/// traits.
2754///
2755/// This will complete any types necessary, and validate the various constraints
2756/// on those operands.
2757///
Steve Naroff71b59a92007-06-04 22:22:31 +00002758/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002759/// C99 6.3.2.1p[2-4] all state:
2760/// Except when it is the operand of the sizeof operator ...
2761///
2762/// C++ [expr.sizeof]p4
2763/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2764/// standard conversions are not applied to the operand of sizeof.
2765///
2766/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002767bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2768 SourceLocation OpLoc,
2769 SourceRange ExprRange,
2770 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002771 if (exprType->isDependentType())
2772 return false;
2773
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002774 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2775 // the result is the size of the referenced type."
2776 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2777 // result shall be the alignment of the referenced type."
2778 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2779 exprType = Ref->getPointeeType();
2780
Chandler Carruth62da79c2011-05-26 08:53:12 +00002781 if (ExprKind == UETT_VecStep)
2782 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002783
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002784 // Whitelist some types as extensions
2785 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2786 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002787 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002788
Chris Lattner62975a72009-04-24 00:30:45 +00002789 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002790 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002791 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002792 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002793
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002794 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2795 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002796 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattner62975a72009-04-24 00:30:45 +00002798 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002799}
2800
Chandler Carruth14502c22011-05-26 08:53:10 +00002801static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002802 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002803
Mike Stump11289f42009-09-09 15:08:12 +00002804 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002805 if (isa<DeclRefExpr>(E))
2806 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002807
2808 // Cannot know anything else if the expression is dependent.
2809 if (E->isTypeDependent())
2810 return false;
2811
Douglas Gregor71235ec2009-05-02 02:18:30 +00002812 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002813 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2814 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002815 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002816 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002817
2818 // Alignment of a field access is always okay, so long as it isn't a
2819 // bit-field.
2820 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002821 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002822 return false;
2823
Chandler Carruth14502c22011-05-26 08:53:10 +00002824 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002825}
2826
Chandler Carruth14502c22011-05-26 08:53:10 +00002827bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002828 E = E->IgnoreParens();
2829
2830 // Cannot know anything else if the expression is dependent.
2831 if (E->isTypeDependent())
2832 return false;
2833
Chandler Carruth14502c22011-05-26 08:53:10 +00002834 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002835}
2836
Douglas Gregor0950e412009-03-13 21:01:28 +00002837/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002838ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002839Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2840 SourceLocation OpLoc,
2841 UnaryExprOrTypeTrait ExprKind,
2842 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002843 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002844 return ExprError();
2845
John McCallbcd03502009-12-07 02:54:59 +00002846 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002847
Douglas Gregor0950e412009-03-13 21:01:28 +00002848 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002849 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002850 return ExprError();
2851
2852 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002853 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2854 Context.getSizeType(),
2855 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002856}
2857
2858/// \brief Build a sizeof or alignof expression given an expression
2859/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002860ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002861Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2862 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002863 ExprResult PE = CheckPlaceholderExpr(E);
2864 if (PE.isInvalid())
2865 return ExprError();
2866
2867 E = PE.get();
2868
Douglas Gregor0950e412009-03-13 21:01:28 +00002869 // Verify that the operand is valid.
2870 bool isInvalid = false;
2871 if (E->isTypeDependent()) {
2872 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002873 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002874 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002875 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002876 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002877 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002878 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002879 isInvalid = true;
2880 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002881 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002882 }
2883
2884 if (isInvalid)
2885 return ExprError();
2886
2887 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002888 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002889 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002890 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002891}
2892
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2894/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002895/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002896ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2898 UnaryExprOrTypeTrait ExprKind, bool isType,
2899 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002900 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002901 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002902
Sebastian Redl6f282892008-11-11 17:56:53 +00002903 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002904 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002905 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002906 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002907 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002908
Douglas Gregor0950e412009-03-13 21:01:28 +00002909 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002910 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002911 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002912}
2913
John Wiegley01296292011-04-08 18:41:53 +00002914static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002915 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002916 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002917 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002918
John McCall34376a62010-12-04 03:47:34 +00002919 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002920 if (V.get()->getObjectKind() != OK_Ordinary) {
2921 V = S.DefaultLvalueConversion(V.take());
2922 if (V.isInvalid())
2923 return QualType();
2924 }
John McCall34376a62010-12-04 03:47:34 +00002925
Chris Lattnere267f5d2007-08-26 05:39:26 +00002926 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002927 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002928 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002929
Chris Lattnere267f5d2007-08-26 05:39:26 +00002930 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002931 if (V.get()->getType()->isArithmeticType())
2932 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002933
John McCall36226622010-10-12 02:09:17 +00002934 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002935 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002936 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002937 if (PR.get() != V.get()) {
2938 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002939 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002940 }
2941
Chris Lattnere267f5d2007-08-26 05:39:26 +00002942 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002943 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002944 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002945 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002946}
2947
2948
Chris Lattnere168f762006-11-10 05:29:30 +00002949
John McCalldadc5752010-08-24 06:29:42 +00002950ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002951Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002952 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002953 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002954 switch (Kind) {
2955 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002956 case tok::plusplus: Opc = UO_PostInc; break;
2957 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002958 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002959
John McCallb268a282010-08-23 23:25:46 +00002960 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002961}
2962
John McCalldadc5752010-08-24 06:29:42 +00002963ExprResult
John McCallb268a282010-08-23 23:25:46 +00002964Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2965 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002966 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002967 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002968 if (Result.isInvalid()) return ExprError();
2969 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002970
John McCallb268a282010-08-23 23:25:46 +00002971 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregor40412ac2008-11-19 17:17:41 +00002973 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002974 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002975 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002976 Context.DependentTy,
2977 VK_LValue, OK_Ordinary,
2978 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002979 }
2980
Mike Stump11289f42009-09-09 15:08:12 +00002981 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002982 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002983 LHSExp->getType()->isEnumeralType() ||
2984 RHSExp->getType()->isRecordType() ||
2985 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002986 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002987 }
2988
John McCallb268a282010-08-23 23:25:46 +00002989 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002990}
2991
2992
John McCalldadc5752010-08-24 06:29:42 +00002993ExprResult
John McCallb268a282010-08-23 23:25:46 +00002994Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2995 Expr *Idx, SourceLocation RLoc) {
2996 Expr *LHSExp = Base;
2997 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002998
Chris Lattner36d572b2007-07-16 00:14:47 +00002999 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003000 if (!LHSExp->getType()->getAs<VectorType>()) {
3001 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3002 if (Result.isInvalid())
3003 return ExprError();
3004 LHSExp = Result.take();
3005 }
3006 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3007 if (Result.isInvalid())
3008 return ExprError();
3009 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010
Chris Lattner36d572b2007-07-16 00:14:47 +00003011 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003012 ExprValueKind VK = VK_LValue;
3013 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003014
Steve Naroffc1aadb12007-03-28 21:49:40 +00003015 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003016 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003017 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003018 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003019 Expr *BaseExpr, *IndexExpr;
3020 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003021 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3022 BaseExpr = LHSExp;
3023 IndexExpr = RHSExp;
3024 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003025 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003026 BaseExpr = LHSExp;
3027 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003028 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003029 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003030 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003031 BaseExpr = RHSExp;
3032 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003033 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003034 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003035 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003036 BaseExpr = LHSExp;
3037 IndexExpr = RHSExp;
3038 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003039 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003040 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003041 // Handle the uncommon case of "123[Ptr]".
3042 BaseExpr = RHSExp;
3043 IndexExpr = LHSExp;
3044 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003045 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003046 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003047 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003048 VK = LHSExp->getValueKind();
3049 if (VK != VK_RValue)
3050 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003051
Chris Lattner36d572b2007-07-16 00:14:47 +00003052 // FIXME: need to deal with const...
3053 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003054 } else if (LHSTy->isArrayType()) {
3055 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003056 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003057 // wasn't promoted because of the C90 rule that doesn't
3058 // allow promoting non-lvalue arrays. Warn, then
3059 // force the promotion here.
3060 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3061 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003062 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3063 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003064 LHSTy = LHSExp->getType();
3065
3066 BaseExpr = LHSExp;
3067 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003068 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003069 } else if (RHSTy->isArrayType()) {
3070 // Same as previous, except for 123[f().a] case
3071 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3072 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003073 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3074 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003075 RHSTy = RHSExp->getType();
3076
3077 BaseExpr = RHSExp;
3078 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003079 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003080 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003081 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3082 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003083 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003084 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003085 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003086 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3087 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003088
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003089 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003090 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3091 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003092 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3093
Douglas Gregorac1fb652009-03-24 19:52:54 +00003094 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003095 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3096 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003097 // incomplete types are not object types.
3098 if (ResultType->isFunctionType()) {
3099 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3100 << ResultType << BaseExpr->getSourceRange();
3101 return ExprError();
3102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003104 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3105 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003106 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3107 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003108
3109 // C forbids expressions of unqualified void type from being l-values.
3110 // See IsCForbiddenLValueType.
3111 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003112 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003113 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003114 PDiag(diag::err_subscript_incomplete_type)
3115 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003116 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003117
Chris Lattner62975a72009-04-24 00:30:45 +00003118 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003119 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003120 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3121 << ResultType << BaseExpr->getSourceRange();
3122 return ExprError();
3123 }
Mike Stump11289f42009-09-09 15:08:12 +00003124
John McCall4bc41ae2010-11-18 19:01:18 +00003125 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003126 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003127
Mike Stump4e1f26a2009-02-19 03:04:26 +00003128 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003129 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003130}
3131
John McCalldadc5752010-08-24 06:29:42 +00003132ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003133 FunctionDecl *FD,
3134 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003135 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003136 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003137 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003138 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003139 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003140 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003141 return ExprError();
3142 }
3143
3144 if (Param->hasUninstantiatedDefaultArg()) {
3145 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003146
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003147 // Instantiate the expression.
3148 MultiLevelTemplateArgumentList ArgList
3149 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003150
Nico Weber44887f62010-11-29 18:19:25 +00003151 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003152 = ArgList.getInnermost();
3153 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3154 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003155
Nico Weber44887f62010-11-29 18:19:25 +00003156 ExprResult Result;
3157 {
3158 // C++ [dcl.fct.default]p5:
3159 // The names in the [default argument] expression are bound, and
3160 // the semantic constraints are checked, at the point where the
3161 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003162 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003163 Result = SubstExpr(UninstExpr, ArgList);
3164 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003165 if (Result.isInvalid())
3166 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003167
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003168 // Check the expression as an initializer for the parameter.
3169 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003170 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003171 InitializationKind Kind
3172 = InitializationKind::CreateCopy(Param->getLocation(),
3173 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3174 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003175
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003176 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3177 Result = InitSeq.Perform(*this, Entity, Kind,
3178 MultiExprArg(*this, &ResultE, 1));
3179 if (Result.isInvalid())
3180 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003181
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003182 // Build the default argument expression.
3183 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3184 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003185 }
3186
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003187 // If the default expression creates temporaries, we need to
3188 // push them to the current stack of expression temporaries so they'll
3189 // be properly destroyed.
3190 // FIXME: We should really be rebuilding the default argument with new
3191 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003192 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3193 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3194 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3195 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3196 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003197 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003198 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003199
3200 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003201 // Just mark all of the declarations in this potentially-evaluated expression
3202 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003203 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003204 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003205}
3206
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003207/// ConvertArgumentsForCall - Converts the arguments specified in
3208/// Args/NumArgs to the parameter types of the function FDecl with
3209/// function prototype Proto. Call is the call expression itself, and
3210/// Fn is the function expression. For a C++ member function, this
3211/// routine does not attempt to convert the object argument. Returns
3212/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003213bool
3214Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003215 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003216 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003217 Expr **Args, unsigned NumArgs,
3218 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003219 // Bail out early if calling a builtin with custom typechecking.
3220 // We don't need to do this in the
3221 if (FDecl)
3222 if (unsigned ID = FDecl->getBuiltinID())
3223 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3224 return false;
3225
Mike Stump4e1f26a2009-02-19 03:04:26 +00003226 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003227 // assignment, to the types of the corresponding parameter, ...
3228 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003229 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003230
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003231 // If too few arguments are available (and we don't have default
3232 // arguments for the remaining parameters), don't make the call.
3233 if (NumArgs < NumArgsInProto) {
3234 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3235 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003236 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003237 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003238 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003239 }
3240
3241 // If too many are passed and not variadic, error on the extras and drop
3242 // them.
3243 if (NumArgs > NumArgsInProto) {
3244 if (!Proto->isVariadic()) {
3245 Diag(Args[NumArgsInProto]->getLocStart(),
3246 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003247 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003248 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003249 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3250 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003251
3252 // Emit the location of the prototype.
3253 if (FDecl && !FDecl->getBuiltinID())
3254 Diag(FDecl->getLocStart(),
3255 diag::note_typecheck_call_too_many_args)
3256 << FDecl;
3257
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003258 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003259 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003260 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003261 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003262 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003263 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003264 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003265 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3266 if (Fn->getType()->isBlockPointerType())
3267 CallType = VariadicBlock; // Block
3268 else if (isa<MemberExpr>(Fn))
3269 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003270 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003271 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003272 if (Invalid)
3273 return true;
3274 unsigned TotalNumArgs = AllArgs.size();
3275 for (unsigned i = 0; i < TotalNumArgs; ++i)
3276 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003277
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003278 return false;
3279}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003280
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003281bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3282 FunctionDecl *FDecl,
3283 const FunctionProtoType *Proto,
3284 unsigned FirstProtoArg,
3285 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003287 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003288 unsigned NumArgsInProto = Proto->getNumArgs();
3289 unsigned NumArgsToCheck = NumArgs;
3290 bool Invalid = false;
3291 if (NumArgs != NumArgsInProto)
3292 // Use default arguments for missing arguments
3293 NumArgsToCheck = NumArgsInProto;
3294 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003295 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003296 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003297 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003298
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003299 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003300 if (ArgIx < NumArgs) {
3301 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003302
Eli Friedman3164fb12009-03-22 22:00:50 +00003303 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3304 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003305 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003306 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003307 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003308
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003309 // Pass the argument
3310 ParmVarDecl *Param = 0;
3311 if (FDecl && i < FDecl->getNumParams())
3312 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003313
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003314 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003315 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003316 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3317 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003318 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003319 SourceLocation(),
3320 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003321 if (ArgE.isInvalid())
3322 return true;
3323
3324 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003325 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003326 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003327
John McCalldadc5752010-08-24 06:29:42 +00003328 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003330 if (ArgExpr.isInvalid())
3331 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003332
Anders Carlsson355933d2009-08-25 03:49:14 +00003333 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003334 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003335 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003336 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003337
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003339 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003340
3341 // Assume that extern "C" functions with variadic arguments that
3342 // return __unknown_anytype aren't *really* variadic.
3343 if (Proto->getResultType() == Context.UnknownAnyTy &&
3344 FDecl && FDecl->isExternC()) {
3345 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3346 ExprResult arg;
3347 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3348 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3349 else
3350 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3351 Invalid |= arg.isInvalid();
3352 AllArgs.push_back(arg.take());
3353 }
3354
3355 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3356 } else {
3357 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3358 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3359 Invalid |= Arg.isInvalid();
3360 AllArgs.push_back(Arg.take());
3361 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003362 }
3363 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003364 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003365}
3366
John McCall2979fe02011-04-12 00:42:48 +00003367/// Given a function expression of unknown-any type, try to rebuild it
3368/// to have a function type.
3369static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3370
Steve Naroff83895f72007-09-16 03:34:24 +00003371/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003372/// This provides the location of the left/right parens and a list of comma
3373/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003374ExprResult
John McCallb268a282010-08-23 23:25:46 +00003375Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003376 MultiExprArg args, SourceLocation RParenLoc,
3377 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003378 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003379
3380 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003381 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003382 if (Result.isInvalid()) return ExprError();
3383 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003384
John McCallb268a282010-08-23 23:25:46 +00003385 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003386
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003387 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003388 // If this is a pseudo-destructor expression, build the call immediately.
3389 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3390 if (NumArgs > 0) {
3391 // Pseudo-destructor calls should not have any arguments.
3392 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003393 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003394 SourceRange(Args[0]->getLocStart(),
3395 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003396
Douglas Gregorad8a3362009-09-04 17:36:40 +00003397 NumArgs = 0;
3398 }
Mike Stump11289f42009-09-09 15:08:12 +00003399
Douglas Gregorad8a3362009-09-04 17:36:40 +00003400 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003401 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003404 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003405 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003406 // FIXME: Will need to cache the results of name lookup (including ADL) in
3407 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003408 bool Dependent = false;
3409 if (Fn->isTypeDependent())
3410 Dependent = true;
3411 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3412 Dependent = true;
3413
Peter Collingbourne41f85462011-02-09 21:07:24 +00003414 if (Dependent) {
3415 if (ExecConfig) {
3416 return Owned(new (Context) CUDAKernelCallExpr(
3417 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3418 Context.DependentTy, VK_RValue, RParenLoc));
3419 } else {
3420 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3421 Context.DependentTy, VK_RValue,
3422 RParenLoc));
3423 }
3424 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003425
3426 // Determine whether this is a call to an object (C++ [over.call.object]).
3427 if (Fn->getType()->isRecordType())
3428 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003429 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003430
John McCall2979fe02011-04-12 00:42:48 +00003431 if (Fn->getType() == Context.UnknownAnyTy) {
3432 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3433 if (result.isInvalid()) return ExprError();
3434 Fn = result.take();
3435 }
3436
John McCall0009fcc2011-04-26 20:42:42 +00003437 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003438 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003439 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003440 }
John McCall0009fcc2011-04-26 20:42:42 +00003441 }
John McCall10eae182009-11-30 22:42:35 +00003442
John McCall0009fcc2011-04-26 20:42:42 +00003443 // Check for overloaded calls. This can happen even in C due to extensions.
3444 if (Fn->getType() == Context.OverloadTy) {
3445 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3446
3447 // We aren't supposed to apply this logic if there's an '&' involved.
3448 if (!find.IsAddressOfOperand) {
3449 OverloadExpr *ovl = find.Expression;
3450 if (isa<UnresolvedLookupExpr>(ovl)) {
3451 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3452 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3453 RParenLoc, ExecConfig);
3454 } else {
John McCall2d74de92009-12-01 22:10:20 +00003455 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003456 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003457 }
3458 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003459 }
3460
Douglas Gregore254f902009-02-04 00:32:51 +00003461 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003462
Eli Friedmane14b1992009-12-26 03:35:45 +00003463 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003464
John McCall57500772009-12-16 12:17:52 +00003465 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003466 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3467 if (UnOp->getOpcode() == UO_AddrOf)
3468 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3469
John McCall57500772009-12-16 12:17:52 +00003470 if (isa<DeclRefExpr>(NakedFn))
3471 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003472 else if (isa<MemberExpr>(NakedFn))
3473 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003474
Peter Collingbourne41f85462011-02-09 21:07:24 +00003475 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3476 ExecConfig);
3477}
3478
3479ExprResult
3480Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3481 MultiExprArg execConfig, SourceLocation GGGLoc) {
3482 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3483 if (!ConfigDecl)
3484 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3485 << "cudaConfigureCall");
3486 QualType ConfigQTy = ConfigDecl->getType();
3487
3488 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3489 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3490
3491 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003492}
3493
Tanya Lattner55808c12011-06-04 00:47:47 +00003494/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3495///
3496/// __builtin_astype( value, dst type )
3497///
3498ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3499 SourceLocation BuiltinLoc,
3500 SourceLocation RParenLoc) {
3501 ExprValueKind VK = VK_RValue;
3502 ExprObjectKind OK = OK_Ordinary;
3503 QualType DstTy = GetTypeFromParser(destty);
3504 QualType SrcTy = expr->getType();
3505 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3506 return ExprError(Diag(BuiltinLoc,
3507 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003508 << DstTy
3509 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003510 << expr->getSourceRange());
3511 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3512}
3513
John McCall57500772009-12-16 12:17:52 +00003514/// BuildResolvedCallExpr - Build a call to a resolved expression,
3515/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003516/// unary-convert to an expression of function-pointer or
3517/// block-pointer type.
3518///
3519/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003520ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003521Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3522 SourceLocation LParenLoc,
3523 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003524 SourceLocation RParenLoc,
3525 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003526 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3527
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003528 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003529 ExprResult Result = UsualUnaryConversions(Fn);
3530 if (Result.isInvalid())
3531 return ExprError();
3532 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003533
Chris Lattner08464942007-12-28 05:29:59 +00003534 // Make the call expr early, before semantic checks. This guarantees cleanup
3535 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003536 CallExpr *TheCall;
3537 if (Config) {
3538 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3539 cast<CallExpr>(Config),
3540 Args, NumArgs,
3541 Context.BoolTy,
3542 VK_RValue,
3543 RParenLoc);
3544 } else {
3545 TheCall = new (Context) CallExpr(Context, Fn,
3546 Args, NumArgs,
3547 Context.BoolTy,
3548 VK_RValue,
3549 RParenLoc);
3550 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003551
John McCallbebede42011-02-26 05:39:39 +00003552 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3553
3554 // Bail out early if calling a builtin with custom typechecking.
3555 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3556 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3557
John McCall31996342011-04-07 08:22:57 +00003558 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003559 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003560 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003561 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3562 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003563 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003564 if (FuncT == 0)
3565 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3566 << Fn->getType() << Fn->getSourceRange());
3567 } else if (const BlockPointerType *BPT =
3568 Fn->getType()->getAs<BlockPointerType>()) {
3569 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3570 } else {
John McCall31996342011-04-07 08:22:57 +00003571 // Handle calls to expressions of unknown-any type.
3572 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003573 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003574 if (rewrite.isInvalid()) return ExprError();
3575 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003576 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003577 goto retry;
3578 }
3579
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003580 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3581 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003582 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003583
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003584 if (getLangOptions().CUDA) {
3585 if (Config) {
3586 // CUDA: Kernel calls must be to global functions
3587 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3588 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3589 << FDecl->getName() << Fn->getSourceRange());
3590
3591 // CUDA: Kernel function must have 'void' return type
3592 if (!FuncT->getResultType()->isVoidType())
3593 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3594 << Fn->getType() << Fn->getSourceRange());
3595 }
3596 }
3597
Eli Friedman3164fb12009-03-22 22:00:50 +00003598 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003599 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003600 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003601 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003602 return ExprError();
3603
Chris Lattner08464942007-12-28 05:29:59 +00003604 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003605 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003606 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003607
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003608 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003609 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003610 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003611 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003612 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003613 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003614
Douglas Gregord8e97de2009-04-02 15:37:10 +00003615 if (FDecl) {
3616 // Check if we have too few/too many template arguments, based
3617 // on our knowledge of the function definition.
3618 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003619 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003620 const FunctionProtoType *Proto
3621 = Def->getType()->getAs<FunctionProtoType>();
3622 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003623 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3624 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003625 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003626
3627 // If the function we're calling isn't a function prototype, but we have
3628 // a function prototype from a prior declaratiom, use that prototype.
3629 if (!FDecl->hasPrototype())
3630 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003631 }
3632
Steve Naroff0b661582007-08-28 23:30:39 +00003633 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003634 for (unsigned i = 0; i != NumArgs; i++) {
3635 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003636
3637 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003638 InitializedEntity Entity
3639 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003640 Proto->getArgType(i),
3641 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003642 ExprResult ArgE = PerformCopyInitialization(Entity,
3643 SourceLocation(),
3644 Owned(Arg));
3645 if (ArgE.isInvalid())
3646 return true;
3647
3648 Arg = ArgE.takeAs<Expr>();
3649
3650 } else {
John Wiegley01296292011-04-08 18:41:53 +00003651 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3652
3653 if (ArgE.isInvalid())
3654 return true;
3655
3656 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003657 }
3658
Douglas Gregor83025412010-10-26 05:45:40 +00003659 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3660 Arg->getType(),
3661 PDiag(diag::err_call_incomplete_argument)
3662 << Arg->getSourceRange()))
3663 return ExprError();
3664
Chris Lattner08464942007-12-28 05:29:59 +00003665 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003666 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003667 }
Chris Lattner08464942007-12-28 05:29:59 +00003668
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003669 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3670 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003671 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3672 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003673
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003674 // Check for sentinels
3675 if (NDecl)
3676 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003677
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003678 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003679 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003680 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003681 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003682
John McCallbebede42011-02-26 05:39:39 +00003683 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003684 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003685 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003686 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003687 return ExprError();
3688 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003689
John McCallb268a282010-08-23 23:25:46 +00003690 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003691}
3692
John McCalldadc5752010-08-24 06:29:42 +00003693ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003694Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003695 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003696 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003697 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003698 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003699
3700 TypeSourceInfo *TInfo;
3701 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3702 if (!TInfo)
3703 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3704
John McCallb268a282010-08-23 23:25:46 +00003705 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003706}
3707
John McCalldadc5752010-08-24 06:29:42 +00003708ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003709Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003710 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003711 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003712
Eli Friedman37a186d2008-05-20 05:22:08 +00003713 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003714 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3715 PDiag(diag::err_illegal_decl_array_incomplete_type)
3716 << SourceRange(LParenLoc,
3717 literalExpr->getSourceRange().getEnd())))
3718 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003719 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003720 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3721 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003722 } else if (!literalType->isDependentType() &&
3723 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003724 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003725 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003726 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003727 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003728
Douglas Gregor85dabae2009-12-16 01:38:02 +00003729 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003730 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003731 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003732 = InitializationKind::CreateCStyleCast(LParenLoc,
3733 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003734 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003735 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003736 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003737 &literalType);
3738 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003739 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003740 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003741
Chris Lattner79413952008-12-04 23:50:19 +00003742 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003743 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003744 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003745 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003746 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003747
John McCall7decc9e2010-11-18 06:31:45 +00003748 // In C, compound literals are l-values for some reason.
3749 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3750
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003751 return MaybeBindToTemporary(
3752 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3753 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003754}
3755
John McCalldadc5752010-08-24 06:29:42 +00003756ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003757Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003758 SourceLocation RBraceLoc) {
3759 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003760 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003761
Steve Naroff30d242c2007-09-15 18:49:24 +00003762 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003763 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003764
Ted Kremenekac034612010-04-13 23:39:13 +00003765 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3766 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003767 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003768 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003769}
3770
John McCalld7646252010-11-14 08:17:51 +00003771/// Prepares for a scalar cast, performing all the necessary stages
3772/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003773static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003774 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3775 // Also, callers should have filtered out the invalid cases with
3776 // pointers. Everything else should be possible.
3777
John Wiegley01296292011-04-08 18:41:53 +00003778 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003779 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003780 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003781
John McCall8cb679e2010-11-15 09:13:47 +00003782 switch (SrcTy->getScalarTypeKind()) {
3783 case Type::STK_MemberPointer:
3784 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003785
John McCall8cb679e2010-11-15 09:13:47 +00003786 case Type::STK_Pointer:
3787 switch (DestTy->getScalarTypeKind()) {
3788 case Type::STK_Pointer:
3789 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003790 CK_AnyPointerToObjCPointerCast :
3791 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003792 case Type::STK_Bool:
3793 return CK_PointerToBoolean;
3794 case Type::STK_Integral:
3795 return CK_PointerToIntegral;
3796 case Type::STK_Floating:
3797 case Type::STK_FloatingComplex:
3798 case Type::STK_IntegralComplex:
3799 case Type::STK_MemberPointer:
3800 llvm_unreachable("illegal cast from pointer");
3801 }
3802 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003803
John McCall8cb679e2010-11-15 09:13:47 +00003804 case Type::STK_Bool: // casting from bool is like casting from an integer
3805 case Type::STK_Integral:
3806 switch (DestTy->getScalarTypeKind()) {
3807 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003808 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003809 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003810 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003811 case Type::STK_Bool:
3812 return CK_IntegralToBoolean;
3813 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003814 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003815 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003816 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003817 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003818 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3819 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003820 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003821 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003822 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3823 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003824 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003825 case Type::STK_MemberPointer:
3826 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003827 }
3828 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003829
John McCall8cb679e2010-11-15 09:13:47 +00003830 case Type::STK_Floating:
3831 switch (DestTy->getScalarTypeKind()) {
3832 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003833 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003834 case Type::STK_Bool:
3835 return CK_FloatingToBoolean;
3836 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003837 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003838 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003839 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3840 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003841 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003842 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003843 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3844 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003845 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003846 case Type::STK_Pointer:
3847 llvm_unreachable("valid float->pointer cast?");
3848 case Type::STK_MemberPointer:
3849 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003850 }
3851 break;
3852
John McCall8cb679e2010-11-15 09:13:47 +00003853 case Type::STK_FloatingComplex:
3854 switch (DestTy->getScalarTypeKind()) {
3855 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003856 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003857 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003858 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003859 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003860 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003861 if (S.Context.hasSameType(ET, DestTy))
3862 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003863 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003864 return CK_FloatingCast;
3865 }
John McCall8cb679e2010-11-15 09:13:47 +00003866 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003867 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003868 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003869 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3870 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003871 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003872 case Type::STK_Pointer:
3873 llvm_unreachable("valid complex float->pointer cast?");
3874 case Type::STK_MemberPointer:
3875 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003876 }
3877 break;
3878
John McCall8cb679e2010-11-15 09:13:47 +00003879 case Type::STK_IntegralComplex:
3880 switch (DestTy->getScalarTypeKind()) {
3881 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003882 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003883 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003884 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003885 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003886 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003887 if (S.Context.hasSameType(ET, DestTy))
3888 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003889 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003890 return CK_IntegralCast;
3891 }
John McCall8cb679e2010-11-15 09:13:47 +00003892 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003893 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003894 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003895 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3896 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003897 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003898 case Type::STK_Pointer:
3899 llvm_unreachable("valid complex int->pointer cast?");
3900 case Type::STK_MemberPointer:
3901 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003902 }
3903 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003904 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003905
John McCalld7646252010-11-14 08:17:51 +00003906 llvm_unreachable("Unhandled scalar cast");
3907 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003908}
3909
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003910/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003911ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3912 QualType castType, Expr *castExpr,
3913 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003914 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003915 if (castExpr->getType() == Context.UnknownAnyTy)
3916 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3917
Sebastian Redl9f831db2009-07-25 15:41:38 +00003918 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003919 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003920 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003921 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003922 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003923
John McCall3aef3d82011-04-10 19:13:55 +00003924 assert(!castExpr->getType()->isPlaceholderType());
3925
John McCall7decc9e2010-11-18 06:31:45 +00003926 // We only support r-value casts in C.
3927 VK = VK_RValue;
3928
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003929 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3930 // type needs to be scalar.
3931 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003932 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003933 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3934 if (castExprRes.isInvalid())
3935 return ExprError();
3936 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003937
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003938 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003939 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003940 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003941 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003942
John Wiegley01296292011-04-08 18:41:53 +00003943 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3944 if (castExprRes.isInvalid())
3945 return ExprError();
3946 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003947
Eli Friedmane98194d2010-07-17 20:43:49 +00003948 if (RequireCompleteType(TyR.getBegin(), castType,
3949 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003950 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003951
Anders Carlssonef918ac2009-10-16 02:35:04 +00003952 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003953 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003954 (castType->isStructureType() || castType->isUnionType())) {
3955 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003956 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003957 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3958 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003959 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003960 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003961 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003962
Anders Carlsson525b76b2009-10-16 02:48:28 +00003963 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003964 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003965 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003966 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003967 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003968 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003969 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003970 castExpr->getType()) &&
3971 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003972 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3973 << castExpr->getSourceRange();
3974 break;
3975 }
3976 }
John Wiegley01296292011-04-08 18:41:53 +00003977 if (Field == FieldEnd) {
3978 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003979 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003980 return ExprError();
3981 }
John McCalle3027922010-08-25 11:45:40 +00003982 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00003983 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003985
Anders Carlsson525b76b2009-10-16 02:48:28 +00003986 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00003987 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00003988 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003989 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003990 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003991
John McCalld7646252010-11-14 08:17:51 +00003992 // The type we're casting to is known to be a scalar or vector.
3993
3994 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003995 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003996 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00003997 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003998 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003999 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004000 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004001 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004002
4003 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004004 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004005
Anton Yartsev28ccef72011-03-27 09:32:40 +00004006 if (castType->isVectorType()) {
4007 if (castType->getAs<VectorType>()->getVectorKind() ==
4008 VectorType::AltiVecVector &&
4009 (castExpr->getType()->isIntegerType() ||
4010 castExpr->getType()->isFloatingType())) {
4011 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004012 return Owned(castExpr);
4013 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4014 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004015 } else
John Wiegley01296292011-04-08 18:41:53 +00004016 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004017 }
John Wiegley01296292011-04-08 18:41:53 +00004018 if (castExpr->getType()->isVectorType()) {
4019 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4020 return ExprError();
4021 else
4022 return Owned(castExpr);
4023 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004024
John McCalld7646252010-11-14 08:17:51 +00004025 // The source and target types are both scalars, i.e.
4026 // - arithmetic types (fundamental, enum, and complex)
4027 // - all kinds of pointers
4028 // Note that member pointers were filtered out with C++, above.
4029
John Wiegley01296292011-04-08 18:41:53 +00004030 if (isa<ObjCSelectorExpr>(castExpr)) {
4031 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4032 return ExprError();
4033 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004034
John McCalld7646252010-11-14 08:17:51 +00004035 // If either type is a pointer, the other type has to be either an
4036 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004037 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004038 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004039 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004040 castExprType->isArithmeticType()) {
4041 Diag(castExpr->getLocStart(),
4042 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004043 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004044 return ExprError();
4045 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004046 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004047 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4048 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004049 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004050 return ExprError();
4051 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004052 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004053
John McCall31168b02011-06-15 23:02:42 +00004054 if (getLangOptions().ObjCAutoRefCount) {
4055 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4056 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4057 castType, castExpr, CCK_CStyleCast);
4058
4059 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4060 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4061 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4062 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4063 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4064 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4065 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4066 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004067 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004068 << castExprType << castType << AA_Casting
4069 << castExpr->getSourceRange();
4070
4071 return ExprError();
4072 }
4073 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004074 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004075 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4076 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004077 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004078 << castExprType << castType
4079 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004080 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004081 }
4082 }
4083
John Wiegley01296292011-04-08 18:41:53 +00004084 castExprRes = Owned(castExpr);
4085 Kind = PrepareScalarCast(*this, castExprRes, castType);
4086 if (castExprRes.isInvalid())
4087 return ExprError();
4088 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004089
John McCalld7646252010-11-14 08:17:51 +00004090 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004091 CheckCastAlign(castExpr, castType, TyR);
4092
John Wiegley01296292011-04-08 18:41:53 +00004093 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004094}
4095
Anders Carlsson525b76b2009-10-16 02:48:28 +00004096bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004097 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004098 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004099
Anders Carlssonde71adf2007-11-27 05:51:55 +00004100 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004101 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004102 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004103 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004104 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004105 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004106 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004107 } else
4108 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004109 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004110 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004111
John McCalle3027922010-08-25 11:45:40 +00004112 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004113 return false;
4114}
4115
John Wiegley01296292011-04-08 18:41:53 +00004116ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4117 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004118 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004119
Anders Carlsson43d70f82009-10-16 05:23:41 +00004120 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004121
Nate Begemanc8961a42009-06-27 22:05:55 +00004122 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4123 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004124 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004125 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4126 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004127 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004128 return ExprError();
4129 }
John McCalle3027922010-08-25 11:45:40 +00004130 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004131 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004132 }
4133
Nate Begemanbd956c42009-06-28 02:36:38 +00004134 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004135 // conversion will take place first from scalar to elt type, and then
4136 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004137 if (SrcTy->isPointerType())
4138 return Diag(R.getBegin(),
4139 diag::err_invalid_conversion_between_vector_and_scalar)
4140 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004141
4142 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004143 ExprResult CastExprRes = Owned(CastExpr);
4144 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4145 if (CastExprRes.isInvalid())
4146 return ExprError();
4147 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004148
John McCalle3027922010-08-25 11:45:40 +00004149 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004150 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004151}
4152
John McCalldadc5752010-08-24 06:29:42 +00004153ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004154Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4155 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004156 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004157 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004158 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004159
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004160 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4161 if (D.isInvalidType())
4162 return ExprError();
4163
4164 if (getLangOptions().CPlusPlus) {
4165 // Check that there are no default arguments (C++ only).
4166 CheckExtraCXXDefaultArguments(D);
4167 }
4168
4169 QualType castType = castTInfo->getType();
4170 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004171
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004172 bool isVectorLiteral = false;
4173
4174 // Check for an altivec or OpenCL literal,
4175 // i.e. all the elements are integer constants.
4176 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4177 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4178 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4179 if (PLE && PLE->getNumExprs() == 0) {
4180 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4181 return ExprError();
4182 }
4183 if (PE || PLE->getNumExprs() == 1) {
4184 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4185 if (!E->getType()->isVectorType())
4186 isVectorLiteral = true;
4187 }
4188 else
4189 isVectorLiteral = true;
4190 }
4191
4192 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4193 // then handle it as such.
4194 if (isVectorLiteral)
4195 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4196
Nate Begeman5ec4b312009-08-10 23:49:36 +00004197 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004198 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4199 // sequence of BinOp comma operators.
4200 if (isa<ParenListExpr>(castExpr)) {
4201 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4202 if (Result.isInvalid()) return ExprError();
4203 castExpr = Result.take();
4204 }
John McCallebe54742010-01-15 18:56:44 +00004205
John McCallb268a282010-08-23 23:25:46 +00004206 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004207}
4208
John McCalldadc5752010-08-24 06:29:42 +00004209ExprResult
John McCallebe54742010-01-15 18:56:44 +00004210Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004211 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004212 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004213 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004214 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004215 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004216 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4217 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004218 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004219 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004220 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004221
John McCallcf142162010-08-07 06:22:56 +00004222 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004223 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004224 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004225 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004226}
4227
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004228ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4229 SourceLocation RParenLoc, Expr *E,
4230 TypeSourceInfo *TInfo) {
4231 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4232 "Expected paren or paren list expression");
4233
4234 Expr **exprs;
4235 unsigned numExprs;
4236 Expr *subExpr;
4237 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4238 exprs = PE->getExprs();
4239 numExprs = PE->getNumExprs();
4240 } else {
4241 subExpr = cast<ParenExpr>(E)->getSubExpr();
4242 exprs = &subExpr;
4243 numExprs = 1;
4244 }
4245
4246 QualType Ty = TInfo->getType();
4247 assert(Ty->isVectorType() && "Expected vector type");
4248
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004249 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004250 const VectorType *VTy = Ty->getAs<VectorType>();
4251 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4252
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004253 // '(...)' form of vector initialization in AltiVec: the number of
4254 // initializers must be one or must match the size of the vector.
4255 // If a single value is specified in the initializer then it will be
4256 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004257 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004258 // The number of initializers must be one or must match the size of the
4259 // vector. If a single value is specified in the initializer then it will
4260 // be replicated to all the components of the vector
4261 if (numExprs == 1) {
4262 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4263 ExprResult Literal = Owned(exprs[0]);
4264 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4265 PrepareScalarCast(*this, Literal, ElemTy));
4266 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4267 }
4268 else if (numExprs < numElems) {
4269 Diag(E->getExprLoc(),
4270 diag::err_incorrect_number_of_vector_initializers);
4271 return ExprError();
4272 }
4273 else
4274 for (unsigned i = 0, e = numExprs; i != e; ++i)
4275 initExprs.push_back(exprs[i]);
4276 }
Tanya Lattner83559382011-07-15 23:07:01 +00004277 else {
4278 // For OpenCL, when the number of initializers is a single value,
4279 // it will be replicated to all components of the vector.
4280 if (getLangOptions().OpenCL &&
4281 VTy->getVectorKind() == VectorType::GenericVector &&
4282 numExprs == 1) {
4283 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4284 ExprResult Literal = Owned(exprs[0]);
4285 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4286 PrepareScalarCast(*this, Literal, ElemTy));
4287 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4288 }
4289
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004290 for (unsigned i = 0, e = numExprs; i != e; ++i)
4291 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004292 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004293 // FIXME: This means that pretty-printing the final AST will produce curly
4294 // braces instead of the original commas.
4295 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4296 &initExprs[0],
4297 initExprs.size(), RParenLoc);
4298 initE->setType(Ty);
4299 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4300}
4301
Nate Begeman5ec4b312009-08-10 23:49:36 +00004302/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4303/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004304ExprResult
John McCallb268a282010-08-23 23:25:46 +00004305Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004306 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4307 if (!E)
4308 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCalldadc5752010-08-24 06:29:42 +00004310 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004311
Nate Begeman5ec4b312009-08-10 23:49:36 +00004312 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004313 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4314 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004315
John McCallb268a282010-08-23 23:25:46 +00004316 if (Result.isInvalid()) return ExprError();
4317
4318 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004319}
4320
John McCalldadc5752010-08-24 06:29:42 +00004321ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004322 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004323 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004324 unsigned nexprs = Val.size();
4325 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004326 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4327 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004328 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004329 expr = new (Context) ParenExpr(L, R, exprs[0]);
4330 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004331 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4332 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004333 return Owned(expr);
4334}
4335
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004336/// \brief Emit a specialized diagnostic when one expression is a null pointer
4337/// constant and the other is not a pointer.
4338bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4339 SourceLocation QuestionLoc) {
4340 Expr *NullExpr = LHS;
4341 Expr *NonPointerExpr = RHS;
4342 Expr::NullPointerConstantKind NullKind =
4343 NullExpr->isNullPointerConstant(Context,
4344 Expr::NPC_ValueDependentIsNotNull);
4345
4346 if (NullKind == Expr::NPCK_NotNull) {
4347 NullExpr = RHS;
4348 NonPointerExpr = LHS;
4349 NullKind =
4350 NullExpr->isNullPointerConstant(Context,
4351 Expr::NPC_ValueDependentIsNotNull);
4352 }
4353
4354 if (NullKind == Expr::NPCK_NotNull)
4355 return false;
4356
4357 if (NullKind == Expr::NPCK_ZeroInteger) {
4358 // In this case, check to make sure that we got here from a "NULL"
4359 // string in the source code.
4360 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004361 SourceLocation loc = NullExpr->getExprLoc();
4362 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004363 return false;
4364 }
4365
4366 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4367 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4368 << NonPointerExpr->getType() << DiagType
4369 << NonPointerExpr->getSourceRange();
4370 return true;
4371}
4372
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004373/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4374/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004375/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004376QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004377 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004378 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004379
John McCall3aef3d82011-04-10 19:13:55 +00004380 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004381 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004382 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004383
John McCall3aef3d82011-04-10 19:13:55 +00004384 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004385 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004386 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004387
Sebastian Redl1a99f442009-04-16 17:51:27 +00004388 // C++ is sufficiently different to merit its own checker.
4389 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004390 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004391
4392 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004393 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004394
John Wiegley01296292011-04-08 18:41:53 +00004395 Cond = UsualUnaryConversions(Cond.take());
4396 if (Cond.isInvalid())
4397 return QualType();
4398 LHS = UsualUnaryConversions(LHS.take());
4399 if (LHS.isInvalid())
4400 return QualType();
4401 RHS = UsualUnaryConversions(RHS.take());
4402 if (RHS.isInvalid())
4403 return QualType();
4404
4405 QualType CondTy = Cond.get()->getType();
4406 QualType LHSTy = LHS.get()->getType();
4407 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004408
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004409 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004410 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004411 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4412 // Throw an error if its not either.
4413 if (getLangOptions().OpenCL) {
4414 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004415 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004416 diag::err_typecheck_cond_expect_scalar_or_vector)
4417 << CondTy;
4418 return QualType();
4419 }
4420 }
4421 else {
John Wiegley01296292011-04-08 18:41:53 +00004422 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004423 << CondTy;
4424 return QualType();
4425 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004426 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004427
Chris Lattnere2949f42008-01-06 22:42:25 +00004428 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004429 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004430 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004431
Nate Begemanabb5a732010-09-20 22:41:17 +00004432 // OpenCL: If the condition is a vector, and both operands are scalar,
4433 // attempt to implicity convert them to the vector type to act like the
4434 // built in select.
4435 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4436 // Both operands should be of scalar type.
4437 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004438 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004439 << CondTy;
4440 return QualType();
4441 }
4442 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004443 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004444 << CondTy;
4445 return QualType();
4446 }
4447 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004448 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4449 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004450 }
4451
Chris Lattnere2949f42008-01-06 22:42:25 +00004452 // If both operands have arithmetic type, do the usual arithmetic conversions
4453 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004454 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4455 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004456 if (LHS.isInvalid() || RHS.isInvalid())
4457 return QualType();
4458 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004459 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004460
Chris Lattnere2949f42008-01-06 22:42:25 +00004461 // If both operands are the same structure or union type, the result is that
4462 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004463 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4464 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004465 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004466 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004467 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004468 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004469 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004470 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004471
Chris Lattnere2949f42008-01-06 22:42:25 +00004472 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004473 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004474 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4475 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004476 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4477 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004478 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004479 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4480 << LHS.get()->getSourceRange();
4481 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4482 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004483 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004484 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004485 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4486 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004487 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004488 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004489 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004490 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004491 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004492 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004493 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004494 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4495 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004496 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004497 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004498
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004499 // All objective-c pointer type analysis is done here.
4500 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4501 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004502 if (LHS.isInvalid() || RHS.isInvalid())
4503 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004504 if (!compositeType.isNull())
4505 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004506
4507
Steve Naroff05efa972009-07-01 14:36:47 +00004508 // Handle block pointer types.
4509 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4510 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4511 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4512 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004513 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4514 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004515 return destType;
4516 }
4517 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004518 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004519 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004520 }
Steve Naroff05efa972009-07-01 14:36:47 +00004521 // We have 2 block pointer types.
4522 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4523 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004524 return LHSTy;
4525 }
Steve Naroff05efa972009-07-01 14:36:47 +00004526 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004527 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4528 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004529
Steve Naroff05efa972009-07-01 14:36:47 +00004530 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4531 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004532 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004533 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004534 // In this situation, we assume void* type. No especially good
4535 // reason, but this is what gcc does, and we do have to pick
4536 // to get a consistent AST.
4537 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004538 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4539 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004540 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004541 }
Steve Naroff05efa972009-07-01 14:36:47 +00004542 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004543 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4544 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004545 return LHSTy;
4546 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004547
Steve Naroff05efa972009-07-01 14:36:47 +00004548 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4549 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4550 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004551 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4552 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004553
4554 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4555 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4556 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004557 QualType destPointee
4558 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004559 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004560 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004561 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004562 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004563 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004564 return destType;
4565 }
4566 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004567 QualType destPointee
4568 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004569 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004570 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004571 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004572 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004573 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004574 return destType;
4575 }
4576
4577 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4578 // Two identical pointer types are always compatible.
4579 return LHSTy;
4580 }
4581 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4582 rhptee.getUnqualifiedType())) {
4583 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004584 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004585 // In this situation, we assume void* type. No especially good
4586 // reason, but this is what gcc does, and we do have to pick
4587 // to get a consistent AST.
4588 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004589 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4590 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004591 return incompatTy;
4592 }
4593 // The pointer types are compatible.
4594 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4595 // differently qualified versions of compatible types, the result type is
4596 // a pointer to an appropriately qualified version of the *composite*
4597 // type.
4598 // FIXME: Need to calculate the composite type.
4599 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004600 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4601 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004602 return LHSTy;
4603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
John McCalle84af4e2010-11-13 01:35:44 +00004605 // GCC compatibility: soften pointer/integer mismatch. Note that
4606 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004607 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4608 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004609 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4610 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004611 return RHSTy;
4612 }
4613 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4614 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004615 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4616 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004617 return LHSTy;
4618 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004619
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004620 // Emit a better diagnostic if one of the expressions is a null pointer
4621 // constant and the other is not a pointer type. In this case, the user most
4622 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004623 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004624 return QualType();
4625
Chris Lattnere2949f42008-01-06 22:42:25 +00004626 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004627 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004628 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004629 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004630}
4631
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004632/// FindCompositeObjCPointerType - Helper method to find composite type of
4633/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004634QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004635 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004636 QualType LHSTy = LHS.get()->getType();
4637 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004638
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004639 // Handle things like Class and struct objc_class*. Here we case the result
4640 // to the pseudo-builtin, because that will be implicitly cast back to the
4641 // redefinition type if an attempt is made to access its fields.
4642 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004643 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004644 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004645 return LHSTy;
4646 }
4647 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004648 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004649 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004650 return RHSTy;
4651 }
4652 // And the same for struct objc_object* / id
4653 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004654 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004655 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004656 return LHSTy;
4657 }
4658 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004659 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004660 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004661 return RHSTy;
4662 }
4663 // And the same for struct objc_selector* / SEL
4664 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004665 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004666 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004667 return LHSTy;
4668 }
4669 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004670 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004671 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004672 return RHSTy;
4673 }
4674 // Check constraints for Objective-C object pointers types.
4675 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004676
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004677 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4678 // Two identical object pointer types are always compatible.
4679 return LHSTy;
4680 }
4681 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4682 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4683 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004684
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004685 // If both operands are interfaces and either operand can be
4686 // assigned to the other, use that type as the composite
4687 // type. This allows
4688 // xxx ? (A*) a : (B*) b
4689 // where B is a subclass of A.
4690 //
4691 // Additionally, as for assignment, if either type is 'id'
4692 // allow silent coercion. Finally, if the types are
4693 // incompatible then make sure to use 'id' as the composite
4694 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004695
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004696 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4697 // It could return the composite type.
4698 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4699 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4700 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4701 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4702 } else if ((LHSTy->isObjCQualifiedIdType() ||
4703 RHSTy->isObjCQualifiedIdType()) &&
4704 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4705 // Need to handle "id<xx>" explicitly.
4706 // GCC allows qualified id and any Objective-C type to devolve to
4707 // id. Currently localizing to here until clear this should be
4708 // part of ObjCQualifiedIdTypesAreCompatible.
4709 compositeType = Context.getObjCIdType();
4710 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4711 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004712 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004713 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4714 ;
4715 else {
4716 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4717 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004719 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004720 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4721 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004722 return incompatTy;
4723 }
4724 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004725 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4726 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004727 return compositeType;
4728 }
4729 // Check Objective-C object pointer types and 'void *'
4730 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4731 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4732 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4733 QualType destPointee
4734 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4735 QualType destType = Context.getPointerType(destPointee);
4736 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004737 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004738 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004739 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004740 return destType;
4741 }
4742 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4743 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4744 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4745 QualType destPointee
4746 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4747 QualType destType = Context.getPointerType(destPointee);
4748 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004749 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004750 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004751 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004752 return destType;
4753 }
4754 return QualType();
4755}
4756
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004757/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004758/// ParenRange in parentheses.
4759static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004760 const PartialDiagnostic &Note,
4761 SourceRange ParenRange) {
4762 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4763 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4764 EndLoc.isValid()) {
4765 Self.Diag(Loc, Note)
4766 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4767 << FixItHint::CreateInsertion(EndLoc, ")");
4768 } else {
4769 // We can't display the parentheses, so just show the bare note.
4770 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004771 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004772}
4773
4774static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4775 return Opc >= BO_Mul && Opc <= BO_Shr;
4776}
4777
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004778/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4779/// expression, either using a built-in or overloaded operator,
4780/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4781static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4782 Expr **RHS) {
4783 E = E->IgnoreParenImpCasts();
4784 E = E->IgnoreConversionOperator();
4785 E = E->IgnoreParenImpCasts();
4786
4787 // Built-in binary operator.
4788 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4789 if (IsArithmeticOp(OP->getOpcode())) {
4790 *Opcode = OP->getOpcode();
4791 *RHS = OP->getRHS();
4792 return true;
4793 }
4794 }
4795
4796 // Overloaded operator.
4797 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4798 if (Call->getNumArgs() != 2)
4799 return false;
4800
4801 // Make sure this is really a binary operator that is safe to pass into
4802 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4803 OverloadedOperatorKind OO = Call->getOperator();
4804 if (OO < OO_Plus || OO > OO_Arrow)
4805 return false;
4806
4807 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4808 if (IsArithmeticOp(OpKind)) {
4809 *Opcode = OpKind;
4810 *RHS = Call->getArg(1);
4811 return true;
4812 }
4813 }
4814
4815 return false;
4816}
4817
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004818static bool IsLogicOp(BinaryOperatorKind Opc) {
4819 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4820}
4821
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004822/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4823/// or is a logical expression such as (x==y) which has int type, but is
4824/// commonly interpreted as boolean.
4825static bool ExprLooksBoolean(Expr *E) {
4826 E = E->IgnoreParenImpCasts();
4827
4828 if (E->getType()->isBooleanType())
4829 return true;
4830 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4831 return IsLogicOp(OP->getOpcode());
4832 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4833 return OP->getOpcode() == UO_LNot;
4834
4835 return false;
4836}
4837
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004838/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4839/// and binary operator are mixed in a way that suggests the programmer assumed
4840/// the conditional operator has higher precedence, for example:
4841/// "int x = a + someBinaryCondition ? 1 : 2".
4842static void DiagnoseConditionalPrecedence(Sema &Self,
4843 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004844 Expr *Condition,
4845 Expr *LHS,
4846 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004847 BinaryOperatorKind CondOpcode;
4848 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004849
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004850 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004851 return;
4852 if (!ExprLooksBoolean(CondRHS))
4853 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004854
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004855 // The condition is an arithmetic binary expression, with a right-
4856 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004857
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004858 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004859 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004860 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004861
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004862 SuggestParentheses(Self, OpLoc,
4863 Self.PDiag(diag::note_precedence_conditional_silence)
4864 << BinaryOperator::getOpcodeStr(CondOpcode),
4865 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004866
4867 SuggestParentheses(Self, OpLoc,
4868 Self.PDiag(diag::note_precedence_conditional_first),
4869 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004870}
4871
Steve Naroff83895f72007-09-16 03:34:24 +00004872/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004873/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004874ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004875 SourceLocation ColonLoc,
4876 Expr *CondExpr, Expr *LHSExpr,
4877 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004878 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4879 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004880 OpaqueValueExpr *opaqueValue = 0;
4881 Expr *commonExpr = 0;
4882 if (LHSExpr == 0) {
4883 commonExpr = CondExpr;
4884
4885 // We usually want to apply unary conversions *before* saving, except
4886 // in the special case of a C++ l-value conditional.
4887 if (!(getLangOptions().CPlusPlus
4888 && !commonExpr->isTypeDependent()
4889 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4890 && commonExpr->isGLValue()
4891 && commonExpr->isOrdinaryOrBitFieldObject()
4892 && RHSExpr->isOrdinaryOrBitFieldObject()
4893 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004894 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4895 if (commonRes.isInvalid())
4896 return ExprError();
4897 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004898 }
4899
4900 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4901 commonExpr->getType(),
4902 commonExpr->getValueKind(),
4903 commonExpr->getObjectKind());
4904 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004905 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004906
John McCall7decc9e2010-11-18 06:31:45 +00004907 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004908 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004909 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4910 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004911 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004912 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4913 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004914 return ExprError();
4915
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004916 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4917 RHS.get());
4918
John McCallc07a0c72011-02-17 10:25:35 +00004919 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004920 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4921 LHS.take(), ColonLoc,
4922 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004923
4924 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004925 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4926 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004927}
4928
John McCallaba90822011-01-31 23:13:11 +00004929// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004930// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004931// routine is it effectively iqnores the qualifiers on the top level pointee.
4932// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4933// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004934static Sema::AssignConvertType
4935checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4936 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4937 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004938
Steve Naroff1f4d7272007-05-11 04:00:31 +00004939 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004940 const Type *lhptee, *rhptee;
4941 Qualifiers lhq, rhq;
4942 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4943 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004944
John McCallaba90822011-01-31 23:13:11 +00004945 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004946
4947 // C99 6.5.16.1p1: This following citation is common to constraints
4948 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4949 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004950 Qualifiers lq;
4951
John McCall31168b02011-06-15 23:02:42 +00004952 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4953 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4954 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4955 // Ignore lifetime for further calculation.
4956 lhq.removeObjCLifetime();
4957 rhq.removeObjCLifetime();
4958 }
4959
John McCall4fff8f62011-02-01 00:10:29 +00004960 if (!lhq.compatiblyIncludes(rhq)) {
4961 // Treat address-space mismatches as fatal. TODO: address subspaces
4962 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4963 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4964
John McCall31168b02011-06-15 23:02:42 +00004965 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004966 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004967 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4968 .compatiblyIncludes(
4969 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004970 && (lhptee->isVoidType() || rhptee->isVoidType()))
4971 ; // keep old
4972
John McCall31168b02011-06-15 23:02:42 +00004973 // Treat lifetime mismatches as fatal.
4974 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4975 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4976
John McCall4fff8f62011-02-01 00:10:29 +00004977 // For GCC compatibility, other qualifier mismatches are treated
4978 // as still compatible in C.
4979 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4980 }
Steve Naroff3f597292007-05-11 22:18:03 +00004981
Mike Stump4e1f26a2009-02-19 03:04:26 +00004982 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4983 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004984 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004985 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004986 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004987 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004988
Chris Lattner0a788432008-01-03 22:56:36 +00004989 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004990 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004991 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004992 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004993
Chris Lattner0a788432008-01-03 22:56:36 +00004994 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004995 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004996 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004997
4998 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004999 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005000 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005001 }
John McCall4fff8f62011-02-01 00:10:29 +00005002
Mike Stump4e1f26a2009-02-19 03:04:26 +00005003 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005004 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005005 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5006 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005007 // Check if the pointee types are compatible ignoring the sign.
5008 // We explicitly check for char so that we catch "char" vs
5009 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005010 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005011 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005012 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005013 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005014
Chris Lattnerec3a1562009-10-17 20:33:28 +00005015 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005016 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005017 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005018 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005019
John McCall4fff8f62011-02-01 00:10:29 +00005020 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005021 // Types are compatible ignoring the sign. Qualifier incompatibility
5022 // takes priority over sign incompatibility because the sign
5023 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005024 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005025 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005026
John McCallaba90822011-01-31 23:13:11 +00005027 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005028 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005029
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005030 // If we are a multi-level pointer, it's possible that our issue is simply
5031 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5032 // the eventual target type is the same and the pointers have the same
5033 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005034 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005035 do {
John McCall4fff8f62011-02-01 00:10:29 +00005036 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5037 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005038 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005039
John McCall4fff8f62011-02-01 00:10:29 +00005040 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005041 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005042 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005043
Eli Friedman80160bd2009-03-22 23:59:44 +00005044 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005045 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005046 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005047 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005048}
5049
John McCallaba90822011-01-31 23:13:11 +00005050/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005051/// block pointer types are compatible or whether a block and normal pointer
5052/// are compatible. It is more restrict than comparing two function pointer
5053// types.
John McCallaba90822011-01-31 23:13:11 +00005054static Sema::AssignConvertType
5055checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5056 QualType rhsType) {
5057 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5058 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5059
Steve Naroff081c7422008-09-04 15:10:53 +00005060 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005061
Steve Naroff081c7422008-09-04 15:10:53 +00005062 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005063 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5064 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005065
John McCallaba90822011-01-31 23:13:11 +00005066 // In C++, the types have to match exactly.
5067 if (S.getLangOptions().CPlusPlus)
5068 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005069
John McCallaba90822011-01-31 23:13:11 +00005070 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005071
Steve Naroff081c7422008-09-04 15:10:53 +00005072 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005073 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5074 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005075
John McCallaba90822011-01-31 23:13:11 +00005076 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5077 return Sema::IncompatibleBlockPointer;
5078
Steve Naroff081c7422008-09-04 15:10:53 +00005079 return ConvTy;
5080}
5081
John McCallaba90822011-01-31 23:13:11 +00005082/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005083/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005084static Sema::AssignConvertType
5085checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5086 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5087 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5088
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005089 if (lhsType->isObjCBuiltinType()) {
5090 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005091 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5092 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005093 return Sema::IncompatiblePointer;
5094 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005095 }
5096 if (rhsType->isObjCBuiltinType()) {
5097 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005098 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5099 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005100 return Sema::IncompatiblePointer;
5101 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005102 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005103 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005104 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005105 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005106 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005107
John McCallaba90822011-01-31 23:13:11 +00005108 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5109 return Sema::CompatiblePointerDiscardsQualifiers;
5110
5111 if (S.Context.typesAreCompatible(lhsType, rhsType))
5112 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005113 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005114 return Sema::IncompatibleObjCQualifiedId;
5115 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005116}
5117
John McCall29600e12010-11-16 02:32:08 +00005118Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005119Sema::CheckAssignmentConstraints(SourceLocation Loc,
5120 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005121 // Fake up an opaque expression. We don't actually care about what
5122 // cast operations are required, so if CheckAssignmentConstraints
5123 // adds casts to this they'll be wasted, but fortunately that doesn't
5124 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005125 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005126 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005127 CastKind K = CK_Invalid;
5128
5129 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5130}
5131
Mike Stump4e1f26a2009-02-19 03:04:26 +00005132/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5133/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005134/// pointers. Here are some objectionable examples that GCC considers warnings:
5135///
5136/// int a, *pint;
5137/// short *pshort;
5138/// struct foo *pfoo;
5139///
5140/// pint = pshort; // warning: assignment from incompatible pointer type
5141/// a = pint; // warning: assignment makes integer from pointer without a cast
5142/// pint = a; // warning: assignment makes pointer from integer without a cast
5143/// pint = pfoo; // warning: assignment from incompatible pointer type
5144///
5145/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005146/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005147///
John McCall8cb679e2010-11-15 09:13:47 +00005148/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005149Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005150Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005151 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005152 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005153 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005154
Chris Lattnera52c2f22008-01-04 23:18:45 +00005155 // Get canonical types. We're not formatting these types, just comparing
5156 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005157 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5158 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005159
John McCalle5255932011-01-31 22:28:28 +00005160 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005161 if (lhsType == rhsType) {
5162 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005163 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005164 }
5165
Douglas Gregor6b754842008-10-28 00:22:11 +00005166 // If the left-hand side is a reference type, then we are in a
5167 // (rare!) case where we've allowed the use of references in C,
5168 // e.g., as a parameter type in a built-in function. In this case,
5169 // just make sure that the type referenced is compatible with the
5170 // right-hand side type. The caller is responsible for adjusting
5171 // lhsType so that the resulting expression does not have reference
5172 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005173 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005174 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5175 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005176 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005177 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005178 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005179 }
John McCalle5255932011-01-31 22:28:28 +00005180
Nate Begemanbd956c42009-06-28 02:36:38 +00005181 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5182 // to the same ExtVector type.
5183 if (lhsType->isExtVectorType()) {
5184 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005185 return Incompatible;
5186 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005187 // CK_VectorSplat does T -> vector T, so first cast to the
5188 // element type.
5189 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5190 if (elType != rhsType) {
5191 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005192 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005193 }
5194 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005195 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005196 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005197 }
Mike Stump11289f42009-09-09 15:08:12 +00005198
John McCalle5255932011-01-31 22:28:28 +00005199 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005200 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005201 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005202 // Allow assignments of an AltiVec vector type to an equivalent GCC
5203 // vector type and vice versa
5204 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5205 Kind = CK_BitCast;
5206 return Compatible;
5207 }
5208
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005209 // If we are allowing lax vector conversions, and LHS and RHS are both
5210 // vectors, the total size only needs to be the same. This is a bitcast;
5211 // no bits are changed but the result type is different.
5212 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005213 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005214 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005215 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005216 }
Chris Lattner881a2122008-01-04 23:32:24 +00005217 }
5218 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005219 }
Eli Friedman3360d892008-05-30 18:07:22 +00005220
John McCalle5255932011-01-31 22:28:28 +00005221 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005222 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005223 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005224 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005225 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005226 }
Eli Friedman3360d892008-05-30 18:07:22 +00005227
John McCalle5255932011-01-31 22:28:28 +00005228 // Conversions to normal pointers.
5229 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5230 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005231 if (isa<PointerType>(rhsType)) {
5232 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005233 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005235
John McCalle5255932011-01-31 22:28:28 +00005236 // int -> T*
5237 if (rhsType->isIntegerType()) {
5238 Kind = CK_IntegralToPointer; // FIXME: null?
5239 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005240 }
John McCalle5255932011-01-31 22:28:28 +00005241
5242 // C pointers are not compatible with ObjC object pointers,
5243 // with two exceptions:
5244 if (isa<ObjCObjectPointerType>(rhsType)) {
5245 // - conversions to void*
5246 if (lhsPointer->getPointeeType()->isVoidType()) {
5247 Kind = CK_AnyPointerToObjCPointerCast;
5248 return Compatible;
5249 }
5250
5251 // - conversions from 'Class' to the redefinition type
5252 if (rhsType->isObjCClassType() &&
5253 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005254 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005255 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005256 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005257
John McCalle5255932011-01-31 22:28:28 +00005258 Kind = CK_BitCast;
5259 return IncompatiblePointer;
5260 }
5261
5262 // U^ -> void*
5263 if (rhsType->getAs<BlockPointerType>()) {
5264 if (lhsPointer->getPointeeType()->isVoidType()) {
5265 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005266 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005267 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005268 }
John McCalle5255932011-01-31 22:28:28 +00005269
Steve Naroff081c7422008-09-04 15:10:53 +00005270 return Incompatible;
5271 }
5272
John McCalle5255932011-01-31 22:28:28 +00005273 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005274 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005275 // U^ -> T^
5276 if (rhsType->isBlockPointerType()) {
5277 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005278 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005279 }
5280
5281 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005282 if (rhsType->isIntegerType()) {
5283 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005284 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005285 }
5286
John McCalle5255932011-01-31 22:28:28 +00005287 // id -> T^
5288 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5289 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005290 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005291 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005292
John McCalle5255932011-01-31 22:28:28 +00005293 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005294 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005295 if (RHSPT->getPointeeType()->isVoidType()) {
5296 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005297 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005298 }
John McCall8cb679e2010-11-15 09:13:47 +00005299
Chris Lattnera52c2f22008-01-04 23:18:45 +00005300 return Incompatible;
5301 }
5302
John McCalle5255932011-01-31 22:28:28 +00005303 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005304 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005305 // A* -> B*
5306 if (rhsType->isObjCObjectPointerType()) {
5307 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005308 Sema::AssignConvertType result =
5309 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5310 if (getLangOptions().ObjCAutoRefCount &&
5311 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005312 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5313 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005314 return result;
John McCalle5255932011-01-31 22:28:28 +00005315 }
5316
5317 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005318 if (rhsType->isIntegerType()) {
5319 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005320 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005321 }
5322
John McCalle5255932011-01-31 22:28:28 +00005323 // In general, C pointers are not compatible with ObjC object pointers,
5324 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005325 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005326 // - conversions from 'void*'
5327 if (rhsType->isVoidPointerType()) {
5328 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005329 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005330 }
5331
5332 // - conversions to 'Class' from its redefinition type
5333 if (lhsType->isObjCClassType() &&
5334 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5335 Kind = CK_BitCast;
5336 return Compatible;
5337 }
5338
5339 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005340 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005341 }
John McCalle5255932011-01-31 22:28:28 +00005342
5343 // T^ -> A*
5344 if (rhsType->isBlockPointerType()) {
5345 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005346 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005347 }
5348
Steve Naroff7cae42b2009-07-10 23:34:53 +00005349 return Incompatible;
5350 }
John McCalle5255932011-01-31 22:28:28 +00005351
5352 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005353 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005354 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005355 if (lhsType == Context.BoolTy) {
5356 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005357 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005358 }
Eli Friedman3360d892008-05-30 18:07:22 +00005359
John McCalle5255932011-01-31 22:28:28 +00005360 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005361 if (lhsType->isIntegerType()) {
5362 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005363 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005364 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005365
Chris Lattnera52c2f22008-01-04 23:18:45 +00005366 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005367 }
John McCalle5255932011-01-31 22:28:28 +00005368
5369 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005370 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005371 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005372 if (lhsType == Context.BoolTy) {
5373 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005374 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005375 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005376
John McCalle5255932011-01-31 22:28:28 +00005377 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005378 if (lhsType->isIntegerType()) {
5379 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005380 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005381 }
5382
Steve Naroff7cae42b2009-07-10 23:34:53 +00005383 return Incompatible;
5384 }
Eli Friedman3360d892008-05-30 18:07:22 +00005385
John McCalle5255932011-01-31 22:28:28 +00005386 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005387 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005388 if (Context.typesAreCompatible(lhsType, rhsType)) {
5389 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005390 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005391 }
Bill Wendling216423b2007-05-30 06:30:29 +00005392 }
John McCalle5255932011-01-31 22:28:28 +00005393
Steve Naroff98cf3e92007-06-06 18:38:38 +00005394 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005395}
5396
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005397/// \brief Constructs a transparent union from an expression that is
5398/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005399static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005400 QualType UnionType, FieldDecl *Field) {
5401 // Build an initializer list that designates the appropriate member
5402 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005403 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005404 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005405 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005406 SourceLocation());
5407 Initializer->setType(UnionType);
5408 Initializer->setInitializedFieldInUnion(Field);
5409
5410 // Build a compound literal constructing a value of the transparent
5411 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005412 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005413 EResult = S.Owned(
5414 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5415 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005416}
5417
5418Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005419Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5420 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005421
Mike Stump11289f42009-09-09 15:08:12 +00005422 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005423 // transparent_union GCC extension.
5424 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005425 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005426 return Incompatible;
5427
5428 // The field to initialize within the transparent union.
5429 RecordDecl *UD = UT->getDecl();
5430 FieldDecl *InitField = 0;
5431 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005432 for (RecordDecl::field_iterator it = UD->field_begin(),
5433 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005434 it != itend; ++it) {
5435 if (it->getType()->isPointerType()) {
5436 // If the transparent union contains a pointer type, we allow:
5437 // 1) void pointer
5438 // 2) null pointer constant
5439 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005440 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005441 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005442 InitField = *it;
5443 break;
5444 }
Mike Stump11289f42009-09-09 15:08:12 +00005445
John Wiegley01296292011-04-08 18:41:53 +00005446 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005447 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005448 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005449 InitField = *it;
5450 break;
5451 }
5452 }
5453
John McCall8cb679e2010-11-15 09:13:47 +00005454 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005455 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005456 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005457 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005458 InitField = *it;
5459 break;
5460 }
5461 }
5462
5463 if (!InitField)
5464 return Incompatible;
5465
John Wiegley01296292011-04-08 18:41:53 +00005466 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005467 return Compatible;
5468}
5469
Chris Lattner9bad62c2008-01-04 18:04:52 +00005470Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005471Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005472 if (getLangOptions().CPlusPlus) {
5473 if (!lhsType->isRecordType()) {
5474 // C++ 5.17p3: If the left operand is not of class type, the
5475 // expression is implicitly converted (C++ 4) to the
5476 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005477 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5478 lhsType.getUnqualifiedType(),
5479 AA_Assigning);
5480 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005481 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005482 Sema::AssignConvertType result = Compatible;
5483 if (getLangOptions().ObjCAutoRefCount &&
5484 !CheckObjCARCUnavailableWeakConversion(lhsType, rExpr.get()->getType()))
5485 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005486 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005487 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005488 }
5489
5490 // FIXME: Currently, we fall through and treat C++ classes like C
5491 // structures.
John McCall34376a62010-12-04 03:47:34 +00005492 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005493
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005494 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5495 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005496 if ((lhsType->isPointerType() ||
5497 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005498 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005499 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005500 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005501 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005502 return Compatible;
5503 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005504
Chris Lattnere6dcd502007-10-16 02:55:40 +00005505 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005506 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005507 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005508 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005509 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005510 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005511 if (!lhsType->isReferenceType()) {
5512 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5513 if (rExpr.isInvalid())
5514 return Incompatible;
5515 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005516
John McCall8cb679e2010-11-15 09:13:47 +00005517 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005518 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005519 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005520
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005521 // C99 6.5.16.1p2: The value of the right operand is converted to the
5522 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005523 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5524 // so that we can use references in built-in functions even in C.
5525 // The getNonReferenceType() call makes sure that the resulting expression
5526 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005527 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5528 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005529 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005530}
5531
John Wiegley01296292011-04-08 18:41:53 +00005532QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005533 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005534 << lex.get()->getType() << rex.get()->getType()
5535 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005536 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005537}
5538
Eli Friedman1408bc92011-06-23 18:10:35 +00005539QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5540 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005541 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005542 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005543 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005544 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005545 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005546 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005547
Nate Begeman191a6b12008-07-14 18:02:46 +00005548 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005549 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005550 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005551
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005552 // Handle the case of equivalent AltiVec and GCC vector types
5553 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5554 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005555 if (lhsType->isExtVectorType()) {
5556 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5557 return lhsType;
5558 }
5559
5560 if (!isCompAssign)
5561 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005562 return rhsType;
5563 }
5564
Eli Friedman1408bc92011-06-23 18:10:35 +00005565 if (getLangOptions().LaxVectorConversions &&
5566 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5567 // If we are allowing lax vector conversions, and LHS and RHS are both
5568 // vectors, the total size only needs to be the same. This is a
5569 // bitcast; no bits are changed but the result type is different.
5570 // FIXME: Should we really be allowing this?
5571 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5572 return lhsType;
5573 }
5574
Nate Begemanbd956c42009-06-28 02:36:38 +00005575 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5576 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5577 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005578 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005579 swapped = true;
5580 std::swap(rex, lex);
5581 std::swap(rhsType, lhsType);
5582 }
Mike Stump11289f42009-09-09 15:08:12 +00005583
Nate Begeman886448d2009-06-28 19:12:57 +00005584 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005585 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005586 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005587 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005588 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5589 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005590 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005591 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005592 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005593 if (swapped) std::swap(rex, lex);
5594 return lhsType;
5595 }
5596 }
5597 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5598 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005599 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5600 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005601 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005602 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005603 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005604 if (swapped) std::swap(rex, lex);
5605 return lhsType;
5606 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005607 }
5608 }
Mike Stump11289f42009-09-09 15:08:12 +00005609
Nate Begeman886448d2009-06-28 19:12:57 +00005610 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005611 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005612 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005613 << lex.get()->getType() << rex.get()->getType()
5614 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005615 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005616}
5617
Chris Lattnerfaa54172010-01-12 21:23:57 +00005618QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005619 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5620 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005621 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005622
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005623 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005624 if (lex.isInvalid() || rex.isInvalid())
5625 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005626
John Wiegley01296292011-04-08 18:41:53 +00005627 if (!lex.get()->getType()->isArithmeticType() ||
5628 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005629 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005630
Chris Lattnerfaa54172010-01-12 21:23:57 +00005631 // Check for division by zero.
5632 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005633 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5634 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5635 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005636
Chris Lattnerfaa54172010-01-12 21:23:57 +00005637 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005638}
5639
Chris Lattnerfaa54172010-01-12 21:23:57 +00005640QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005641 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5642 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5643 if (lex.get()->getType()->hasIntegerRepresentation() &&
5644 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005645 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005646 return InvalidOperands(Loc, lex, rex);
5647 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005648
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005649 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005650 if (lex.isInvalid() || rex.isInvalid())
5651 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005652
John Wiegley01296292011-04-08 18:41:53 +00005653 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005654 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005655
Chris Lattnerfaa54172010-01-12 21:23:57 +00005656 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005657 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5658 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5659 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005660
Chris Lattnerfaa54172010-01-12 21:23:57 +00005661 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005662}
5663
Chandler Carruthc9332212011-06-27 08:02:19 +00005664/// \brief Diagnose invalid arithmetic on two void pointers.
5665static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5666 Expr *LHS, Expr *RHS) {
5667 S.Diag(Loc, S.getLangOptions().CPlusPlus
5668 ? diag::err_typecheck_pointer_arith_void_type
5669 : diag::ext_gnu_void_ptr)
5670 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5671}
5672
5673/// \brief Diagnose invalid arithmetic on a void pointer.
5674static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5675 Expr *Pointer) {
5676 S.Diag(Loc, S.getLangOptions().CPlusPlus
5677 ? diag::err_typecheck_pointer_arith_void_type
5678 : diag::ext_gnu_void_ptr)
5679 << 0 /* one pointer */ << Pointer->getSourceRange();
5680}
5681
5682/// \brief Diagnose invalid arithmetic on two function pointers.
5683static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5684 Expr *LHS, Expr *RHS) {
5685 assert(LHS->getType()->isAnyPointerType());
5686 assert(RHS->getType()->isAnyPointerType());
5687 S.Diag(Loc, S.getLangOptions().CPlusPlus
5688 ? diag::err_typecheck_pointer_arith_function_type
5689 : diag::ext_gnu_ptr_func_arith)
5690 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5691 // We only show the second type if it differs from the first.
5692 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5693 RHS->getType())
5694 << RHS->getType()->getPointeeType()
5695 << LHS->getSourceRange() << RHS->getSourceRange();
5696}
5697
5698/// \brief Diagnose invalid arithmetic on a function pointer.
5699static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5700 Expr *Pointer) {
5701 assert(Pointer->getType()->isAnyPointerType());
5702 S.Diag(Loc, S.getLangOptions().CPlusPlus
5703 ? diag::err_typecheck_pointer_arith_function_type
5704 : diag::ext_gnu_ptr_func_arith)
5705 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5706 << 0 /* one pointer, so only one type */
5707 << Pointer->getSourceRange();
5708}
5709
5710/// \brief Check the validity of an arithmetic pointer operand.
5711///
5712/// If the operand has pointer type, this code will check for pointer types
5713/// which are invalid in arithmetic operations. These will be diagnosed
5714/// appropriately, including whether or not the use is supported as an
5715/// extension.
5716///
5717/// \returns True when the operand is valid to use (even if as an extension).
5718static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5719 Expr *Operand) {
5720 if (!Operand->getType()->isAnyPointerType()) return true;
5721
5722 QualType PointeeTy = Operand->getType()->getPointeeType();
5723 if (PointeeTy->isVoidType()) {
5724 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5725 return !S.getLangOptions().CPlusPlus;
5726 }
5727 if (PointeeTy->isFunctionType()) {
5728 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5729 return !S.getLangOptions().CPlusPlus;
5730 }
5731
5732 if ((Operand->getType()->isPointerType() &&
5733 !Operand->getType()->isDependentType()) ||
5734 Operand->getType()->isObjCObjectPointerType()) {
5735 QualType PointeeTy = Operand->getType()->getPointeeType();
5736 if (S.RequireCompleteType(
5737 Loc, PointeeTy,
5738 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5739 << PointeeTy << Operand->getSourceRange()))
5740 return false;
5741 }
5742
5743 return true;
5744}
5745
5746/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5747/// operands.
5748///
5749/// This routine will diagnose any invalid arithmetic on pointer operands much
5750/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5751/// for emitting a single diagnostic even for operations where both LHS and RHS
5752/// are (potentially problematic) pointers.
5753///
5754/// \returns True when the operand is valid to use (even if as an extension).
5755static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5756 Expr *LHS, Expr *RHS) {
5757 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5758 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5759 if (!isLHSPointer && !isRHSPointer) return true;
5760
5761 QualType LHSPointeeTy, RHSPointeeTy;
5762 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5763 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5764
5765 // Check for arithmetic on pointers to incomplete types.
5766 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5767 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5768 if (isLHSVoidPtr || isRHSVoidPtr) {
5769 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5770 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5771 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5772
5773 return !S.getLangOptions().CPlusPlus;
5774 }
5775
5776 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5777 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5778 if (isLHSFuncPtr || isRHSFuncPtr) {
5779 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5780 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5781 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5782
5783 return !S.getLangOptions().CPlusPlus;
5784 }
5785
5786 Expr *Operands[] = { LHS, RHS };
5787 for (unsigned i = 0; i < 2; ++i) {
5788 Expr *Operand = Operands[i];
5789 if ((Operand->getType()->isPointerType() &&
5790 !Operand->getType()->isDependentType()) ||
5791 Operand->getType()->isObjCObjectPointerType()) {
5792 QualType PointeeTy = Operand->getType()->getPointeeType();
5793 if (S.RequireCompleteType(
5794 Loc, PointeeTy,
5795 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5796 << PointeeTy << Operand->getSourceRange()))
5797 return false;
5798 }
5799 }
5800 return true;
5801}
5802
Chris Lattnerfaa54172010-01-12 21:23:57 +00005803QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005804 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5805 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005806 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005807 if (CompLHSTy) *CompLHSTy = compType;
5808 return compType;
5809 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005810
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005811 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005812 if (lex.isInvalid() || rex.isInvalid())
5813 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005814
Steve Naroffe4718892007-04-27 18:30:00 +00005815 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005816 if (lex.get()->getType()->isArithmeticType() &&
5817 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005818 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005819 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005820 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005821
Eli Friedman8e122982008-05-18 18:08:51 +00005822 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005823 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005824 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005825 std::swap(PExp, IExp);
5826
Steve Naroff6b712a72009-07-14 18:25:06 +00005827 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005828 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005829 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5830 return QualType();
5831
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005832 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005833
Chris Lattner12bdebb2009-04-24 23:50:08 +00005834 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005835 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005836 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5837 << PointeeTy << PExp->getSourceRange();
5838 return QualType();
5839 }
Mike Stump11289f42009-09-09 15:08:12 +00005840
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005841 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005842 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005843 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005844 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005845 if (LHSTy->isPromotableIntegerType())
5846 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005847 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005848 *CompLHSTy = LHSTy;
5849 }
Eli Friedman8e122982008-05-18 18:08:51 +00005850 return PExp->getType();
5851 }
5852 }
5853
Chris Lattner326f7572008-11-18 01:30:42 +00005854 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005855}
5856
Chris Lattner2a3569b2008-04-07 05:30:13 +00005857// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005858QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005859 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005860 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005861 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005862 if (CompLHSTy) *CompLHSTy = compType;
5863 return compType;
5864 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005865
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005866 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005867 if (lex.isInvalid() || rex.isInvalid())
5868 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005869
Chris Lattner4d62f422007-12-09 21:53:25 +00005870 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005871
Chris Lattner4d62f422007-12-09 21:53:25 +00005872 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005873 if (lex.get()->getType()->isArithmeticType() &&
5874 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005875 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005876 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005877 }
Mike Stump11289f42009-09-09 15:08:12 +00005878
Chris Lattner4d62f422007-12-09 21:53:25 +00005879 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005880 if (lex.get()->getType()->isAnyPointerType()) {
5881 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005882
Chris Lattner12bdebb2009-04-24 23:50:08 +00005883 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005884 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005885 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005886 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005887 return QualType();
5888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
Chris Lattner4d62f422007-12-09 21:53:25 +00005890 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005891 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005892 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5893 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005894
John Wiegley01296292011-04-08 18:41:53 +00005895 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5896 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005897 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005898
Chris Lattner4d62f422007-12-09 21:53:25 +00005899 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005900 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005901 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005902
Eli Friedman168fe152009-05-16 13:54:38 +00005903 if (getLangOptions().CPlusPlus) {
5904 // Pointee types must be the same: C++ [expr.add]
5905 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5906 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005907 << lex.get()->getType() << rex.get()->getType()
5908 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005909 return QualType();
5910 }
5911 } else {
5912 // Pointee types must be compatible C99 6.5.6p3
5913 if (!Context.typesAreCompatible(
5914 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5915 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5916 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005917 << lex.get()->getType() << rex.get()->getType()
5918 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005919 return QualType();
5920 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005922
Chandler Carruthc9332212011-06-27 08:02:19 +00005923 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5924 lex.get(), rex.get()))
5925 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005926
John Wiegley01296292011-04-08 18:41:53 +00005927 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005928 return Context.getPointerDiffType();
5929 }
5930 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005931
Chris Lattner326f7572008-11-18 01:30:42 +00005932 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005933}
5934
Douglas Gregor0bf31402010-10-08 23:50:27 +00005935static bool isScopedEnumerationType(QualType T) {
5936 if (const EnumType *ET = dyn_cast<EnumType>(T))
5937 return ET->getDecl()->isScoped();
5938 return false;
5939}
5940
John Wiegley01296292011-04-08 18:41:53 +00005941static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005942 SourceLocation Loc, unsigned Opc,
5943 QualType LHSTy) {
5944 llvm::APSInt Right;
5945 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005946 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005947 return;
5948
5949 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005950 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005951 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005952 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005953 return;
5954 }
5955 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005956 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005957 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005958 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005959 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005960 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005961 return;
5962 }
5963 if (Opc != BO_Shl)
5964 return;
5965
5966 // When left shifting an ICE which is signed, we can check for overflow which
5967 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5968 // integers have defined behavior modulo one more than the maximum value
5969 // representable in the result type, so never warn for those.
5970 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005971 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005972 LHSTy->hasUnsignedIntegerRepresentation())
5973 return;
5974 llvm::APInt ResultBits =
5975 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5976 if (LeftBits.uge(ResultBits))
5977 return;
5978 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5979 Result = Result.shl(Right);
5980
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005981 // Print the bit representation of the signed integer as an unsigned
5982 // hexadecimal number.
5983 llvm::SmallString<40> HexResult;
5984 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5985
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005986 // If we are only missing a sign bit, this is less likely to result in actual
5987 // bugs -- if the result is cast back to an unsigned type, it will have the
5988 // expected value. Thus we place this behind a different warning that can be
5989 // turned off separately if needed.
5990 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005991 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5992 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005993 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005994 return;
5995 }
5996
5997 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005998 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005999 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006000}
6001
Chris Lattner2a3569b2008-04-07 05:30:13 +00006002// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00006003QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006004 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006005 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006006 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6007 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006008 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006009
Douglas Gregor0bf31402010-10-08 23:50:27 +00006010 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6011 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006012 if (isScopedEnumerationType(lex.get()->getType()) ||
6013 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006014 return InvalidOperands(Loc, lex, rex);
6015 }
6016
Nate Begemane46ee9a2009-10-25 02:26:48 +00006017 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00006018 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006019 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006020
Chris Lattner5c11c412007-12-12 05:47:28 +00006021 // Shifts don't perform usual arithmetic conversions, they just do integer
6022 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006023
John McCall57cdd882010-12-16 19:28:59 +00006024 // For the LHS, do usual unary conversions, but then reset them away
6025 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006026 ExprResult old_lex = lex;
6027 lex = UsualUnaryConversions(lex.take());
6028 if (lex.isInvalid())
6029 return QualType();
6030 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006031 if (isCompAssign) lex = old_lex;
6032
6033 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006034 rex = UsualUnaryConversions(rex.take());
6035 if (rex.isInvalid())
6036 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006037
Ryan Flynnf53fab82009-08-07 16:20:20 +00006038 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006039 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006040
Chris Lattner5c11c412007-12-12 05:47:28 +00006041 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006042 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006043}
6044
Chandler Carruth17773fc2010-07-10 12:30:03 +00006045static bool IsWithinTemplateSpecialization(Decl *D) {
6046 if (DeclContext *DC = D->getDeclContext()) {
6047 if (isa<ClassTemplateSpecializationDecl>(DC))
6048 return true;
6049 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6050 return FD->isFunctionTemplateSpecialization();
6051 }
6052 return false;
6053}
6054
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006055// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00006056QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006057 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006058 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006059
Chris Lattner9a152e22009-12-05 05:40:13 +00006060 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006061 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006062 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006063
John Wiegley01296292011-04-08 18:41:53 +00006064 QualType lType = lex.get()->getType();
6065 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006066
John Wiegley01296292011-04-08 18:41:53 +00006067 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6068 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006069 QualType LHSStrippedType = LHSStripped->getType();
6070 QualType RHSStrippedType = RHSStripped->getType();
6071
Douglas Gregor1beec452011-03-12 01:48:56 +00006072
6073
Chandler Carruth712563b2011-02-17 08:37:06 +00006074 // Two different enums will raise a warning when compared.
6075 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6076 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6077 if (LHSEnumType->getDecl()->getIdentifier() &&
6078 RHSEnumType->getDecl()->getIdentifier() &&
6079 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6080 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6081 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006082 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006083 }
6084 }
6085 }
6086
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006087 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006088 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006089 !lex.get()->getLocStart().isMacroID() &&
6090 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006091 // For non-floating point types, check for self-comparisons of the form
6092 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6093 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006094 //
6095 // NOTE: Don't warn about comparison expressions resulting from macro
6096 // expansion. Also don't warn about comparisons which are only self
6097 // comparisons within a template specialization. The warnings should catch
6098 // obvious cases in the definition of the template anyways. The idea is to
6099 // warn when the typed comparison operator will always evaluate to the same
6100 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006101 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006102 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006103 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006104 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006105 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006106 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006107 << (Opc == BO_EQ
6108 || Opc == BO_LE
6109 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006110 } else if (lType->isArrayType() && rType->isArrayType() &&
6111 !DRL->getDecl()->getType()->isReferenceType() &&
6112 !DRR->getDecl()->getType()->isReferenceType()) {
6113 // what is it always going to eval to?
6114 char always_evals_to;
6115 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006116 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006117 always_evals_to = 0; // false
6118 break;
John McCalle3027922010-08-25 11:45:40 +00006119 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006120 always_evals_to = 1; // true
6121 break;
6122 default:
6123 // best we can say is 'a constant'
6124 always_evals_to = 2; // e.g. array1 <= array2
6125 break;
6126 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006127 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006128 << 1 // array
6129 << always_evals_to);
6130 }
6131 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006132 }
Mike Stump11289f42009-09-09 15:08:12 +00006133
Chris Lattner222b8bd2009-03-08 19:39:53 +00006134 if (isa<CastExpr>(LHSStripped))
6135 LHSStripped = LHSStripped->IgnoreParenCasts();
6136 if (isa<CastExpr>(RHSStripped))
6137 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006138
Chris Lattner222b8bd2009-03-08 19:39:53 +00006139 // Warn about comparisons against a string constant (unless the other
6140 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006141 Expr *literalString = 0;
6142 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006143 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006144 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006145 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006146 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006147 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006148 } else if ((isa<StringLiteral>(RHSStripped) ||
6149 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006150 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006151 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006152 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006153 literalStringStripped = RHSStripped;
6154 }
6155
6156 if (literalString) {
6157 std::string resultComparison;
6158 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006159 case BO_LT: resultComparison = ") < 0"; break;
6160 case BO_GT: resultComparison = ") > 0"; break;
6161 case BO_LE: resultComparison = ") <= 0"; break;
6162 case BO_GE: resultComparison = ") >= 0"; break;
6163 case BO_EQ: resultComparison = ") == 0"; break;
6164 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006165 default: assert(false && "Invalid comparison operator");
6166 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006167
Ted Kremenek3427fac2011-02-23 01:52:04 +00006168 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006169 PDiag(diag::warn_stringcompare)
6170 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006171 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006172 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006173 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006174
Douglas Gregorec170db2010-06-08 19:50:34 +00006175 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006176 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006177 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006178 if (lex.isInvalid() || rex.isInvalid())
6179 return QualType();
6180 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006181 else {
John Wiegley01296292011-04-08 18:41:53 +00006182 lex = UsualUnaryConversions(lex.take());
6183 if (lex.isInvalid())
6184 return QualType();
6185
6186 rex = UsualUnaryConversions(rex.take());
6187 if (rex.isInvalid())
6188 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006189 }
6190
John Wiegley01296292011-04-08 18:41:53 +00006191 lType = lex.get()->getType();
6192 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006193
Douglas Gregorca63811b2008-11-19 03:25:36 +00006194 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006195 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006196
Chris Lattnerb620c342007-08-26 01:18:55 +00006197 if (isRelational) {
6198 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006199 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006200 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006201 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006202 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006203 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006204
Chris Lattnerb620c342007-08-26 01:18:55 +00006205 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006206 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006208
John Wiegley01296292011-04-08 18:41:53 +00006209 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006210 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006211 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006212 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006213
Douglas Gregorf267edd2010-06-15 21:38:40 +00006214 // All of the following pointer-related warnings are GCC extensions, except
6215 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006216 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006217 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006218 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006219 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006220 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006221
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006222 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006223 if (LCanPointeeTy == RCanPointeeTy)
6224 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006225 if (!isRelational &&
6226 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6227 // Valid unless comparison between non-null pointer and function pointer
6228 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006229 // In a SFINAE context, we treat this as a hard error to maintain
6230 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006231 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6232 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006233 Diag(Loc,
6234 isSFINAEContext()?
6235 diag::err_typecheck_comparison_of_fptr_to_void
6236 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006237 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006238
6239 if (isSFINAEContext())
6240 return QualType();
6241
John Wiegley01296292011-04-08 18:41:53 +00006242 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006243 return ResultTy;
6244 }
6245 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006246
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006247 // C++ [expr.rel]p2:
6248 // [...] Pointer conversions (4.10) and qualification
6249 // conversions (4.4) are performed on pointer operands (or on
6250 // a pointer operand and a null pointer constant) to bring
6251 // them to their composite pointer type. [...]
6252 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006253 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006254 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006255 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006256 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006257 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006258 if (T.isNull()) {
6259 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006260 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006261 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006262 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006263 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006264 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006265 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006266 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006267 }
6268
John Wiegley01296292011-04-08 18:41:53 +00006269 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6270 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006271 return ResultTy;
6272 }
Eli Friedman16c209612009-08-23 00:27:47 +00006273 // C99 6.5.9p2 and C99 6.5.8p2
6274 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6275 RCanPointeeTy.getUnqualifiedType())) {
6276 // Valid unless a relational comparison of function pointers
6277 if (isRelational && LCanPointeeTy->isFunctionType()) {
6278 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006279 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006280 }
6281 } else if (!isRelational &&
6282 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6283 // Valid unless comparison between non-null pointer and function pointer
6284 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6285 && !LHSIsNull && !RHSIsNull) {
6286 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006287 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006288 }
6289 } else {
6290 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006291 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006292 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006293 }
John McCall7684dde2011-03-11 04:25:25 +00006294 if (LCanPointeeTy != RCanPointeeTy) {
6295 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006296 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006297 else
John Wiegley01296292011-04-08 18:41:53 +00006298 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006299 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006300 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006301 }
Mike Stump11289f42009-09-09 15:08:12 +00006302
Sebastian Redl576fd422009-05-10 18:38:11 +00006303 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006304 // Comparison of nullptr_t with itself.
6305 if (lType->isNullPtrType() && rType->isNullPtrType())
6306 return ResultTy;
6307
Mike Stump11289f42009-09-09 15:08:12 +00006308 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006309 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006310 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006311 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006312 (!isRelational &&
6313 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006314 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006315 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006316 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006317 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006318 return ResultTy;
6319 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006320 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006321 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006322 (!isRelational &&
6323 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006324 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006325 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006326 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006327 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006328 return ResultTy;
6329 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006330
6331 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006332 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006333 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6334 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006335 // In addition, pointers to members can be compared, or a pointer to
6336 // member and a null pointer constant. Pointer to member conversions
6337 // (4.11) and qualification conversions (4.4) are performed to bring
6338 // them to a common type. If one operand is a null pointer constant,
6339 // the common type is the type of the other operand. Otherwise, the
6340 // common type is a pointer to member type similar (4.4) to the type
6341 // of one of the operands, with a cv-qualification signature (4.4)
6342 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006343 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006344 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006345 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006346 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006347 if (T.isNull()) {
6348 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006349 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006350 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006351 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006352 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006353 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006354 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006355 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006356 }
Mike Stump11289f42009-09-09 15:08:12 +00006357
John Wiegley01296292011-04-08 18:41:53 +00006358 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6359 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006360 return ResultTy;
6361 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006362
6363 // Handle scoped enumeration types specifically, since they don't promote
6364 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006365 if (lex.get()->getType()->isEnumeralType() &&
6366 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006367 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006368 }
Mike Stump11289f42009-09-09 15:08:12 +00006369
Steve Naroff081c7422008-09-04 15:10:53 +00006370 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006371 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006372 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6373 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006374
Steve Naroff081c7422008-09-04 15:10:53 +00006375 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006376 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006377 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006378 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006379 }
John Wiegley01296292011-04-08 18:41:53 +00006380 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006381 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006382 }
John Wiegley01296292011-04-08 18:41:53 +00006383
Steve Naroffe18f94c2008-09-28 01:11:11 +00006384 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006385 if (!isRelational
6386 && ((lType->isBlockPointerType() && rType->isPointerType())
6387 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006388 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006389 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006390 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006391 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006392 ->getPointeeType()->isVoidType())))
6393 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006394 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006395 }
John McCall7684dde2011-03-11 04:25:25 +00006396 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006397 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006398 else
John Wiegley01296292011-04-08 18:41:53 +00006399 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006400 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006401 }
Steve Naroff081c7422008-09-04 15:10:53 +00006402
John McCall7684dde2011-03-11 04:25:25 +00006403 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6404 const PointerType *LPT = lType->getAs<PointerType>();
6405 const PointerType *RPT = rType->getAs<PointerType>();
6406 if (LPT || RPT) {
6407 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6408 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006409
Steve Naroff753567f2008-11-17 19:49:16 +00006410 if (!LPtrToVoid && !RPtrToVoid &&
6411 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006412 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006413 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006414 }
John McCall7684dde2011-03-11 04:25:25 +00006415 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006416 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006417 else
John Wiegley01296292011-04-08 18:41:53 +00006418 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006419 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006420 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006421 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006422 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006423 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006424 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006425 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006426 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006427 else
John Wiegley01296292011-04-08 18:41:53 +00006428 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006429 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006430 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006431 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006432 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6433 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006434 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006435 bool isError = false;
6436 if ((LHSIsNull && lType->isIntegerType()) ||
6437 (RHSIsNull && rType->isIntegerType())) {
6438 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006439 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006440 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006441 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006442 else if (getLangOptions().CPlusPlus) {
6443 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6444 isError = true;
6445 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006446 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006447
Chris Lattnerd99bd522009-08-23 00:03:44 +00006448 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006449 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006450 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006451 if (isError)
6452 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006453 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006454
6455 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006456 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006457 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006458 else
John Wiegley01296292011-04-08 18:41:53 +00006459 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006460 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006461 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006462 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006463
Steve Naroff4b191572008-09-04 16:56:14 +00006464 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006465 if (!isRelational && RHSIsNull
6466 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006467 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006468 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006469 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006470 if (!isRelational && LHSIsNull
6471 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006472 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006473 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006474 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006475
Chris Lattner326f7572008-11-18 01:30:42 +00006476 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006477}
6478
Nate Begeman191a6b12008-07-14 18:02:46 +00006479/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006480/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006481/// like a scalar comparison, a vector comparison produces a vector of integer
6482/// types.
John Wiegley01296292011-04-08 18:41:53 +00006483QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006484 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006485 bool isRelational) {
6486 // Check to make sure we're operating on vectors of the same type and width,
6487 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006488 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006489 if (vType.isNull())
6490 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
John Wiegley01296292011-04-08 18:41:53 +00006492 QualType lType = lex.get()->getType();
6493 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006494
Anton Yartsev530deb92011-03-27 15:36:07 +00006495 // If AltiVec, the comparison results in a numeric type, i.e.
6496 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006497 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006498 return Context.getLogicalOperationType();
6499
Nate Begeman191a6b12008-07-14 18:02:46 +00006500 // For non-floating point types, check for self-comparisons of the form
6501 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6502 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006503 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006504 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6505 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006506 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006507 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006508 PDiag(diag::warn_comparison_always)
6509 << 0 // self-
6510 << 2 // "a constant"
6511 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006512 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006513
Nate Begeman191a6b12008-07-14 18:02:46 +00006514 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006515 if (!isRelational && lType->hasFloatingRepresentation()) {
6516 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006517 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006518 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006519
Nate Begeman191a6b12008-07-14 18:02:46 +00006520 // Return the type for the comparison, which is the same as vector type for
6521 // integer vectors, or an integer type of identical size and number of
6522 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006523 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006524 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006525
John McCall9dd450b2009-09-21 23:43:11 +00006526 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006527 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006528 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006529 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006530 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006531 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6532
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006534 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006535 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6536}
6537
Steve Naroff218bc2b2007-05-04 21:54:46 +00006538inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006539 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6540 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6541 if (lex.get()->getType()->hasIntegerRepresentation() &&
6542 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006543 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006544
6545 return InvalidOperands(Loc, lex, rex);
6546 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006547
John Wiegley01296292011-04-08 18:41:53 +00006548 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6549 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6550 if (lexResult.isInvalid() || rexResult.isInvalid())
6551 return QualType();
6552 lex = lexResult.take();
6553 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006554
John Wiegley01296292011-04-08 18:41:53 +00006555 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6556 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006557 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006558 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006559}
6560
Steve Naroff218bc2b2007-05-04 21:54:46 +00006561inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006562 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006563
6564 // Diagnose cases where the user write a logical and/or but probably meant a
6565 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6566 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006567 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6568 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006569 // Don't warn in macros or template instantiations.
6570 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006571 // If the RHS can be constant folded, and if it constant folds to something
6572 // that isn't 0 or 1 (which indicate a potential logical operation that
6573 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006574 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006575 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006576 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6577 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6578 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6579 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6580 << rex.get()->getSourceRange()
6581 << (Opc == BO_LAnd ? "&&" : "||")
6582 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006583 }
6584 }
Chris Lattner8406c512010-07-13 19:41:32 +00006585
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006586 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006587 lex = UsualUnaryConversions(lex.take());
6588 if (lex.isInvalid())
6589 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006590
John Wiegley01296292011-04-08 18:41:53 +00006591 rex = UsualUnaryConversions(rex.take());
6592 if (rex.isInvalid())
6593 return QualType();
6594
6595 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006596 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006597
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006598 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006599 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006600
John McCall4a2429a2010-06-04 00:29:51 +00006601 // The following is safe because we only use this method for
6602 // non-overloadable operands.
6603
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006604 // C++ [expr.log.and]p1
6605 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006606 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006607 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6608 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006609 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006610 lex = move(lexRes);
6611
6612 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6613 if (rexRes.isInvalid())
6614 return InvalidOperands(Loc, lex, rex);
6615 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006616
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006617 // C++ [expr.log.and]p2
6618 // C++ [expr.log.or]p2
6619 // The result is a bool.
6620 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006621}
6622
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006623/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6624/// is a read-only property; return true if so. A readonly property expression
6625/// depends on various declarations and thus must be treated specially.
6626///
Mike Stump11289f42009-09-09 15:08:12 +00006627static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006628 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6629 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006630 if (PropExpr->isImplicitProperty()) return false;
6631
6632 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6633 QualType BaseType = PropExpr->isSuperReceiver() ?
6634 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006635 PropExpr->getBase()->getType();
6636
John McCallb7bd14f2010-12-02 01:19:52 +00006637 if (const ObjCObjectPointerType *OPT =
6638 BaseType->getAsObjCInterfacePointerType())
6639 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6640 if (S.isPropertyReadonly(PDecl, IFace))
6641 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006642 }
6643 return false;
6644}
6645
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006646static bool IsConstProperty(Expr *E, Sema &S) {
6647 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6648 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6649 if (PropExpr->isImplicitProperty()) return false;
6650
6651 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6652 QualType T = PDecl->getType();
6653 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006654 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006655 CanQualType CT = S.Context.getCanonicalType(T);
6656 return CT.isConstQualified();
6657 }
6658 return false;
6659}
6660
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006661static bool IsReadonlyMessage(Expr *E, Sema &S) {
6662 if (E->getStmtClass() != Expr::MemberExprClass)
6663 return false;
6664 const MemberExpr *ME = cast<MemberExpr>(E);
6665 NamedDecl *Member = ME->getMemberDecl();
6666 if (isa<FieldDecl>(Member)) {
6667 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6668 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6669 return false;
6670 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6671 }
6672 return false;
6673}
6674
Chris Lattner30bd3272008-11-18 01:22:49 +00006675/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6676/// emit an error and return true. If so, return false.
6677static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006678 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006679 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006680 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006681 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6682 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006683 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6684 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006685 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6686 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006687 if (IsLV == Expr::MLV_Valid)
6688 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006689
Chris Lattner30bd3272008-11-18 01:22:49 +00006690 unsigned Diag = 0;
6691 bool NeedType = false;
6692 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006693 case Expr::MLV_ConstQualified:
6694 Diag = diag::err_typecheck_assign_const;
6695
John McCalld4631322011-06-17 06:42:21 +00006696 // In ARC, use some specialized diagnostics for occasions where we
6697 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006698 if (S.getLangOptions().ObjCAutoRefCount) {
6699 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6700 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6701 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6702
John McCalld4631322011-06-17 06:42:21 +00006703 // Use the normal diagnostic if it's pseudo-__strong but the
6704 // user actually wrote 'const'.
6705 if (var->isARCPseudoStrong() &&
6706 (!var->getTypeSourceInfo() ||
6707 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6708 // There are two pseudo-strong cases:
6709 // - self
John McCall31168b02011-06-15 23:02:42 +00006710 ObjCMethodDecl *method = S.getCurMethodDecl();
6711 if (method && var == method->getSelfDecl())
6712 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006713
6714 // - fast enumeration variables
6715 else
John McCall31168b02011-06-15 23:02:42 +00006716 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006717
John McCall31168b02011-06-15 23:02:42 +00006718 SourceRange Assign;
6719 if (Loc != OrigLoc)
6720 Assign = SourceRange(OrigLoc, OrigLoc);
6721 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6722 // We need to preserve the AST regardless, so migration tool
6723 // can do its job.
6724 return false;
6725 }
6726 }
6727 }
6728
6729 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006731 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6732 NeedType = true;
6733 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006734 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006735 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6736 NeedType = true;
6737 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006738 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006739 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6740 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006741 case Expr::MLV_Valid:
6742 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006743 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006744 case Expr::MLV_MemberFunction:
6745 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006746 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6747 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006748 case Expr::MLV_IncompleteType:
6749 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006750 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006751 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006752 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006753 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006754 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6755 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006756 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006757 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6758 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006759 case Expr::MLV_ReadonlyProperty:
6760 Diag = diag::error_readonly_property_assignment;
6761 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006762 case Expr::MLV_NoSetterProperty:
6763 Diag = diag::error_nosetter_property_assignment;
6764 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006765 case Expr::MLV_InvalidMessageExpression:
6766 Diag = diag::error_readonly_message_assignment;
6767 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006768 case Expr::MLV_SubObjCPropertySetting:
6769 Diag = diag::error_no_subobject_property_setting;
6770 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006771 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006772
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006773 SourceRange Assign;
6774 if (Loc != OrigLoc)
6775 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006776 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006777 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006778 else
Mike Stump11289f42009-09-09 15:08:12 +00006779 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006780 return true;
6781}
6782
6783
6784
6785// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006786QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006787 SourceLocation Loc,
6788 QualType CompoundType) {
6789 // Verify that LHS is a modifiable lvalue, and emit error if not.
6790 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006791 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006792
6793 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006794 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006795 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006796 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006797 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006798 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006799 if (LHS->getObjectKind() == OK_ObjCProperty) {
6800 ExprResult LHSResult = Owned(LHS);
6801 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6802 if (LHSResult.isInvalid())
6803 return QualType();
6804 LHS = LHSResult.take();
6805 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006806 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006807 if (RHS.isInvalid())
6808 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006809 // Special case of NSObject attributes on c-style pointer types.
6810 if (ConvTy == IncompatiblePointer &&
6811 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006812 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006813 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006814 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006815 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006816
John McCall7decc9e2010-11-18 06:31:45 +00006817 if (ConvTy == Compatible &&
6818 getLangOptions().ObjCNonFragileABI &&
6819 LHSType->isObjCObjectType())
6820 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6821 << LHSType;
6822
Chris Lattnerea714382008-08-21 18:04:13 +00006823 // If the RHS is a unary plus or minus, check to see if they = and + are
6824 // right next to each other. If so, the user may have typo'd "x =+ 4"
6825 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006826 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006827 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6828 RHSCheck = ICE->getSubExpr();
6829 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006830 if ((UO->getOpcode() == UO_Plus ||
6831 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006832 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006833 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006834 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6835 // And there is a space or other character before the subexpr of the
6836 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006837 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6838 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006839 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006840 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006841 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006842 }
Chris Lattnerea714382008-08-21 18:04:13 +00006843 }
John McCall31168b02011-06-15 23:02:42 +00006844
6845 if (ConvTy == Compatible) {
6846 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6847 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006848 else if (getLangOptions().ObjCAutoRefCount)
6849 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006850 }
Chris Lattnerea714382008-08-21 18:04:13 +00006851 } else {
6852 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006853 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006854 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006855
Chris Lattner326f7572008-11-18 01:30:42 +00006856 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006857 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006858 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006859
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006860 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006861 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006862 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006863
Steve Naroff98cf3e92007-06-06 18:38:38 +00006864 // C99 6.5.16p3: The type of an assignment expression is the type of the
6865 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006866 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006867 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6868 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006869 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006870 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006871 return (getLangOptions().CPlusPlus
6872 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006873}
6874
Chris Lattner326f7572008-11-18 01:30:42 +00006875// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006876static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006877 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006878 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006879
John McCall3aef3d82011-04-10 19:13:55 +00006880 LHS = S.CheckPlaceholderExpr(LHS.take());
6881 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006882 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006883 return QualType();
6884
John McCall73d36182010-10-12 07:14:40 +00006885 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6886 // operands, but not unary promotions.
6887 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006888
John McCall34376a62010-12-04 03:47:34 +00006889 // So we treat the LHS as a ignored value, and in C++ we allow the
6890 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006891 LHS = S.IgnoredValueConversions(LHS.take());
6892 if (LHS.isInvalid())
6893 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006894
6895 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006896 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6897 if (RHS.isInvalid())
6898 return QualType();
6899 if (!RHS.get()->getType()->isVoidType())
6900 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006901 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006902
John Wiegley01296292011-04-08 18:41:53 +00006903 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006904}
6905
Steve Naroff7a5af782007-07-13 16:58:59 +00006906/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6907/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006908static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6909 ExprValueKind &VK,
6910 SourceLocation OpLoc,
6911 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006912 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006913 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006914
Chris Lattner6b0cf142008-11-21 07:05:48 +00006915 QualType ResType = Op->getType();
6916 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006917
John McCall4bc41ae2010-11-18 19:01:18 +00006918 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006919 // Decrement of bool is not allowed.
6920 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006921 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006922 return QualType();
6923 }
6924 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006925 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006926 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006927 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006928 } else if (ResType->isAnyPointerType()) {
6929 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006930
Chris Lattner6b0cf142008-11-21 07:05:48 +00006931 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006932 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006933 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006934
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006935 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006936 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6937 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006938 << PointeeTy << Op->getSourceRange();
6939 return QualType();
6940 }
Eli Friedman090addd2010-01-03 00:20:48 +00006941 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006942 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006943 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006944 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006945 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006946 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006947 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006948 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6949 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006950 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6951 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006952 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006953 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006954 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006955 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006956 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006957 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006958 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006959 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006960 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006961 // In C++, a prefix increment is the same type as the operand. Otherwise
6962 // (in C or with postfix), the increment is the unqualified type of the
6963 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006964 if (isPrefix && S.getLangOptions().CPlusPlus) {
6965 VK = VK_LValue;
6966 return ResType;
6967 } else {
6968 VK = VK_RValue;
6969 return ResType.getUnqualifiedType();
6970 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006971}
6972
John Wiegley01296292011-04-08 18:41:53 +00006973ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006974 assert(E->getValueKind() == VK_LValue &&
6975 E->getObjectKind() == OK_ObjCProperty);
6976 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6977
Douglas Gregor33823722011-06-11 01:09:30 +00006978 QualType T = E->getType();
6979 QualType ReceiverType;
6980 if (PRE->isObjectReceiver())
6981 ReceiverType = PRE->getBase()->getType();
6982 else if (PRE->isSuperReceiver())
6983 ReceiverType = PRE->getSuperReceiverType();
6984 else
6985 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6986
John McCall34376a62010-12-04 03:47:34 +00006987 ExprValueKind VK = VK_RValue;
6988 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006989 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006990 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006991 T = getMessageSendResultType(ReceiverType, GetterMethod,
6992 PRE->isClassReceiver(),
6993 PRE->isSuperReceiver());
6994 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006995 }
6996 else {
6997 Diag(PRE->getLocation(), diag::err_getter_not_found)
6998 << PRE->getBase()->getType();
6999 }
John McCall34376a62010-12-04 03:47:34 +00007000 }
Douglas Gregor33823722011-06-11 01:09:30 +00007001
7002 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007003 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007004
7005 ExprResult Result = MaybeBindToTemporary(E);
7006 if (!Result.isInvalid())
7007 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007008
7009 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007010}
7011
John Wiegley01296292011-04-08 18:41:53 +00007012void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
7013 assert(LHS.get()->getValueKind() == VK_LValue &&
7014 LHS.get()->getObjectKind() == OK_ObjCProperty);
7015 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007016
John McCall31168b02011-06-15 23:02:42 +00007017 bool Consumed = false;
7018
John Wiegley01296292011-04-08 18:41:53 +00007019 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007020 // If using property-dot syntax notation for assignment, and there is a
7021 // setter, RHS expression is being passed to the setter argument. So,
7022 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007023 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007024 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7025 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007026 Consumed = (getLangOptions().ObjCAutoRefCount &&
7027 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007028
7029 // Otherwise, if the getter returns an l-value, just call that.
7030 } else {
John Wiegley01296292011-04-08 18:41:53 +00007031 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007032 ExprValueKind VK = Expr::getValueKindForType(Result);
7033 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007034 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7035 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007036 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007037 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007038 }
John McCall31168b02011-06-15 23:02:42 +00007039 } else if (getLangOptions().ObjCAutoRefCount) {
7040 const ObjCMethodDecl *setter
7041 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7042 if (setter) {
7043 ObjCMethodDecl::param_iterator P = setter->param_begin();
7044 LHSTy = (*P)->getType();
7045 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7046 }
John McCall34376a62010-12-04 03:47:34 +00007047 }
7048
John McCall31168b02011-06-15 23:02:42 +00007049 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7050 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007051 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007052 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007053 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007054 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007055 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007056 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7057 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7058 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007059 }
7060}
7061
7062
Anders Carlsson806700f2008-02-01 07:15:58 +00007063/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007064/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007065/// where the declaration is needed for type checking. We only need to
7066/// handle cases when the expression references a function designator
7067/// or is an lvalue. Here are some examples:
7068/// - &(x) => x
7069/// - &*****f => f for f a function designator.
7070/// - &s.xx => s
7071/// - &s.zz[1].yy -> s, if zz is an array
7072/// - *(x + 1) -> x, if x is an array
7073/// - &"123"[2] -> 0
7074/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007075static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007076 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007077 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007078 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007079 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007080 // If this is an arrow operator, the address is an offset from
7081 // the base's value, so the object the base refers to is
7082 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007083 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007084 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007085 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007086 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007087 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007088 // FIXME: This code shouldn't be necessary! We should catch the implicit
7089 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007090 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7091 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7092 if (ICE->getSubExpr()->getType()->isArrayType())
7093 return getPrimaryDecl(ICE->getSubExpr());
7094 }
7095 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007096 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007097 case Stmt::UnaryOperatorClass: {
7098 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007099
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007100 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007101 case UO_Real:
7102 case UO_Imag:
7103 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007104 return getPrimaryDecl(UO->getSubExpr());
7105 default:
7106 return 0;
7107 }
7108 }
Steve Naroff47500512007-04-19 23:00:49 +00007109 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007110 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007111 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007112 // If the result of an implicit cast is an l-value, we care about
7113 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007114 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007115 default:
7116 return 0;
7117 }
7118}
7119
7120/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007121/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007122/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007123/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007124/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007125/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007126/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007127static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7128 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007129 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007130 return S.Context.DependentTy;
7131 if (OrigOp->getType() == S.Context.OverloadTy)
7132 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007133 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7134 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007135 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7136 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7137 << OrigOp->getSourceRange();
7138 return QualType();
7139 }
John McCall8d08b9b2010-08-27 09:08:28 +00007140
John McCall2979fe02011-04-12 00:42:48 +00007141 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007142
John McCall8d08b9b2010-08-27 09:08:28 +00007143 // Make sure to ignore parentheses in subsequent checks
7144 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007145
John McCall4bc41ae2010-11-18 19:01:18 +00007146 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007147 // Implement C99-only parts of addressof rules.
7148 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007149 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007150 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7151 // (assuming the deref expression is valid).
7152 return uOp->getSubExpr()->getType();
7153 }
7154 // Technically, there should be a check for array subscript
7155 // expressions here, but the result of one is always an lvalue anyway.
7156 }
John McCallf3a88602011-02-03 08:15:49 +00007157 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007158 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007159
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007160 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007161 bool sfinae = S.isSFINAEContext();
7162 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7163 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007164 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007165 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007166 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007167 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007168 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007169 } else if (lval == Expr::LV_MemberFunction) {
7170 // If it's an instance method, make a member pointer.
7171 // The expression must have exactly the form &A::foo.
7172
7173 // If the underlying expression isn't a decl ref, give up.
7174 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007175 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007176 << OrigOp->getSourceRange();
7177 return QualType();
7178 }
7179 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7180 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7181
7182 // The id-expression was parenthesized.
7183 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007184 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007185 << OrigOp->getSourceRange();
7186
7187 // The method was named without a qualifier.
7188 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007189 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007190 << op->getSourceRange();
7191 }
7192
John McCall4bc41ae2010-11-18 19:01:18 +00007193 return S.Context.getMemberPointerType(op->getType(),
7194 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007195 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007196 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007197 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007198 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007199 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007200 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007201 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007202 return QualType();
7203 }
John McCall086a4642010-11-24 05:12:34 +00007204 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007205 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007206 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007207 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007208 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007209 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007210 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007211 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007212 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007213 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007214 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007215 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007216 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007217 << "property expression" << op->getSourceRange();
7218 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007219 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007220 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007221 // with the register storage-class specifier.
7222 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007223 // in C++ it is not error to take address of a register
7224 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007225 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007226 !S.getLangOptions().CPlusPlus) {
7227 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007228 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007229 return QualType();
7230 }
John McCalld14a8642009-11-21 08:51:07 +00007231 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007232 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007233 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007234 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007235 // Could be a pointer to member, though, if there is an explicit
7236 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007237 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007238 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007239 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007240 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007241 S.Diag(OpLoc,
7242 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007243 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007244 return QualType();
7245 }
Mike Stump11289f42009-09-09 15:08:12 +00007246
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007247 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7248 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007249 return S.Context.getMemberPointerType(op->getType(),
7250 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007251 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007252 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007253 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007254 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007255 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007256
Eli Friedmance7f9002009-05-16 23:27:50 +00007257 if (lval == Expr::LV_IncompleteVoidType) {
7258 // Taking the address of a void variable is technically illegal, but we
7259 // allow it in cases which are otherwise valid.
7260 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007261 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007262 }
7263
Steve Naroff47500512007-04-19 23:00:49 +00007264 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007265 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007266 return S.Context.getObjCObjectPointerType(op->getType());
7267 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007268}
7269
Chris Lattner9156f1b2010-07-05 19:17:26 +00007270/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007271static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7272 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007273 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007274 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007275
John Wiegley01296292011-04-08 18:41:53 +00007276 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7277 if (ConvResult.isInvalid())
7278 return QualType();
7279 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007280 QualType OpTy = Op->getType();
7281 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007282
7283 if (isa<CXXReinterpretCastExpr>(Op)) {
7284 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7285 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7286 Op->getSourceRange());
7287 }
7288
Chris Lattner9156f1b2010-07-05 19:17:26 +00007289 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7290 // is an incomplete type or void. It would be possible to warn about
7291 // dereferencing a void pointer, but it's completely well-defined, and such a
7292 // warning is unlikely to catch any mistakes.
7293 if (const PointerType *PT = OpTy->getAs<PointerType>())
7294 Result = PT->getPointeeType();
7295 else if (const ObjCObjectPointerType *OPT =
7296 OpTy->getAs<ObjCObjectPointerType>())
7297 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007298 else {
John McCall3aef3d82011-04-10 19:13:55 +00007299 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007300 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007301 if (PR.take() != Op)
7302 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007303 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007304
Chris Lattner9156f1b2010-07-05 19:17:26 +00007305 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007306 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007307 << OpTy << Op->getSourceRange();
7308 return QualType();
7309 }
John McCall4bc41ae2010-11-18 19:01:18 +00007310
7311 // Dereferences are usually l-values...
7312 VK = VK_LValue;
7313
7314 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007315 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007316 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007317
7318 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007319}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007320
John McCalle3027922010-08-25 11:45:40 +00007321static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007322 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007323 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007324 switch (Kind) {
7325 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007326 case tok::periodstar: Opc = BO_PtrMemD; break;
7327 case tok::arrowstar: Opc = BO_PtrMemI; break;
7328 case tok::star: Opc = BO_Mul; break;
7329 case tok::slash: Opc = BO_Div; break;
7330 case tok::percent: Opc = BO_Rem; break;
7331 case tok::plus: Opc = BO_Add; break;
7332 case tok::minus: Opc = BO_Sub; break;
7333 case tok::lessless: Opc = BO_Shl; break;
7334 case tok::greatergreater: Opc = BO_Shr; break;
7335 case tok::lessequal: Opc = BO_LE; break;
7336 case tok::less: Opc = BO_LT; break;
7337 case tok::greaterequal: Opc = BO_GE; break;
7338 case tok::greater: Opc = BO_GT; break;
7339 case tok::exclaimequal: Opc = BO_NE; break;
7340 case tok::equalequal: Opc = BO_EQ; break;
7341 case tok::amp: Opc = BO_And; break;
7342 case tok::caret: Opc = BO_Xor; break;
7343 case tok::pipe: Opc = BO_Or; break;
7344 case tok::ampamp: Opc = BO_LAnd; break;
7345 case tok::pipepipe: Opc = BO_LOr; break;
7346 case tok::equal: Opc = BO_Assign; break;
7347 case tok::starequal: Opc = BO_MulAssign; break;
7348 case tok::slashequal: Opc = BO_DivAssign; break;
7349 case tok::percentequal: Opc = BO_RemAssign; break;
7350 case tok::plusequal: Opc = BO_AddAssign; break;
7351 case tok::minusequal: Opc = BO_SubAssign; break;
7352 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7353 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7354 case tok::ampequal: Opc = BO_AndAssign; break;
7355 case tok::caretequal: Opc = BO_XorAssign; break;
7356 case tok::pipeequal: Opc = BO_OrAssign; break;
7357 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007358 }
7359 return Opc;
7360}
7361
John McCalle3027922010-08-25 11:45:40 +00007362static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007363 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007364 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007365 switch (Kind) {
7366 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007367 case tok::plusplus: Opc = UO_PreInc; break;
7368 case tok::minusminus: Opc = UO_PreDec; break;
7369 case tok::amp: Opc = UO_AddrOf; break;
7370 case tok::star: Opc = UO_Deref; break;
7371 case tok::plus: Opc = UO_Plus; break;
7372 case tok::minus: Opc = UO_Minus; break;
7373 case tok::tilde: Opc = UO_Not; break;
7374 case tok::exclaim: Opc = UO_LNot; break;
7375 case tok::kw___real: Opc = UO_Real; break;
7376 case tok::kw___imag: Opc = UO_Imag; break;
7377 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007378 }
7379 return Opc;
7380}
7381
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007382/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7383/// This warning is only emitted for builtin assignment operations. It is also
7384/// suppressed in the event of macro expansions.
7385static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7386 SourceLocation OpLoc) {
7387 if (!S.ActiveTemplateInstantiations.empty())
7388 return;
7389 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7390 return;
7391 lhs = lhs->IgnoreParenImpCasts();
7392 rhs = rhs->IgnoreParenImpCasts();
7393 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7394 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7395 if (!LeftDeclRef || !RightDeclRef ||
7396 LeftDeclRef->getLocation().isMacroID() ||
7397 RightDeclRef->getLocation().isMacroID())
7398 return;
7399 const ValueDecl *LeftDecl =
7400 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7401 const ValueDecl *RightDecl =
7402 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7403 if (LeftDecl != RightDecl)
7404 return;
7405 if (LeftDecl->getType().isVolatileQualified())
7406 return;
7407 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7408 if (RefTy->getPointeeType().isVolatileQualified())
7409 return;
7410
7411 S.Diag(OpLoc, diag::warn_self_assignment)
7412 << LeftDeclRef->getType()
7413 << lhs->getSourceRange() << rhs->getSourceRange();
7414}
7415
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007416/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7417/// operator @p Opc at location @c TokLoc. This routine only supports
7418/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007419ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007420 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007421 Expr *lhsExpr, Expr *rhsExpr) {
7422 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007423 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007424 // The following two variables are used for compound assignment operators
7425 QualType CompLHSTy; // Type of LHS after promotions for computation
7426 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007427 ExprValueKind VK = VK_RValue;
7428 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007429
Douglas Gregor1beec452011-03-12 01:48:56 +00007430 // Check if a 'foo<int>' involved in a binary op, identifies a single
7431 // function unambiguously (i.e. an lvalue ala 13.4)
7432 // But since an assignment can trigger target based overload, exclude it in
7433 // our blind search. i.e:
7434 // template<class T> void f(); template<class T, class U> void f(U);
7435 // f<int> == 0; // resolve f<int> blindly
7436 // void (*p)(int); p = f<int>; // resolve f<int> using target
7437 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007438 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007439 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007440 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007441
John McCall3aef3d82011-04-10 19:13:55 +00007442 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007443 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007444 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007445 }
7446
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007447 // The canonical way to check for a GNU null is with isNullPointerConstant,
7448 // but we use a bit of a hack here for speed; this is a relatively
7449 // hot path, and isNullPointerConstant is slow.
7450 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7451 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007452
7453 // Detect when a NULL constant is used improperly in an expression. These
7454 // are mainly cases where the null pointer is used as an integer instead
7455 // of a pointer.
7456 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007457 // Avoid analyzing cases where the result will either be invalid (and
7458 // diagnosed as such) or entirely valid and not something to warn about.
7459 QualType LeftType = lhs.get()->getType();
7460 QualType RightType = rhs.get()->getType();
7461 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7462 !LeftType->isFunctionType() &&
7463 !RightType->isBlockPointerType() &&
7464 !RightType->isMemberPointerType() &&
7465 !RightType->isFunctionType()) {
7466 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7467 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7468 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7469 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7470 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7471 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7472 // These are the operations that would not make sense with a null pointer
7473 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007474 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007475 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7476 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7477 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7478 Opc == BO_EQ || Opc == BO_NE) {
7479 // These are the operations that would not make sense with a null pointer
7480 // if the other expression the other expression is not a pointer.
7481 if (LeftNull != RightNull &&
7482 !LeftType->isAnyPointerType() &&
7483 !LeftType->canDecayToPointerType() &&
7484 !RightType->isAnyPointerType() &&
7485 !RightType->canDecayToPointerType()) {
7486 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7487 << (LeftNull ? lhs.get()->getSourceRange()
7488 : rhs.get()->getSourceRange());
7489 }
Richard Trieu701fb362011-06-16 21:36:56 +00007490 }
7491 }
7492 }
7493
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007494 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007495 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007496 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007497 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007498 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7499 VK = lhs.get()->getValueKind();
7500 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007501 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007502 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007503 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007504 break;
John McCalle3027922010-08-25 11:45:40 +00007505 case BO_PtrMemD:
7506 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007507 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007508 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007509 break;
John McCalle3027922010-08-25 11:45:40 +00007510 case BO_Mul:
7511 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007512 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007513 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007514 break;
John McCalle3027922010-08-25 11:45:40 +00007515 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007516 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7517 break;
John McCalle3027922010-08-25 11:45:40 +00007518 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007519 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7520 break;
John McCalle3027922010-08-25 11:45:40 +00007521 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007522 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7523 break;
John McCalle3027922010-08-25 11:45:40 +00007524 case BO_Shl:
7525 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007526 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007527 break;
John McCalle3027922010-08-25 11:45:40 +00007528 case BO_LE:
7529 case BO_LT:
7530 case BO_GE:
7531 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007532 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007533 break;
John McCalle3027922010-08-25 11:45:40 +00007534 case BO_EQ:
7535 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007536 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007537 break;
John McCalle3027922010-08-25 11:45:40 +00007538 case BO_And:
7539 case BO_Xor:
7540 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007541 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7542 break;
John McCalle3027922010-08-25 11:45:40 +00007543 case BO_LAnd:
7544 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007545 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007546 break;
John McCalle3027922010-08-25 11:45:40 +00007547 case BO_MulAssign:
7548 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007549 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007550 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007551 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007552 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7553 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007554 break;
John McCalle3027922010-08-25 11:45:40 +00007555 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007556 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7557 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007558 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7559 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007560 break;
John McCalle3027922010-08-25 11:45:40 +00007561 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007562 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007563 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7564 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007565 break;
John McCalle3027922010-08-25 11:45:40 +00007566 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007567 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007568 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7569 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007570 break;
John McCalle3027922010-08-25 11:45:40 +00007571 case BO_ShlAssign:
7572 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007573 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007574 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007575 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7576 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007577 break;
John McCalle3027922010-08-25 11:45:40 +00007578 case BO_AndAssign:
7579 case BO_XorAssign:
7580 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007581 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7582 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007583 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7584 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007585 break;
John McCalle3027922010-08-25 11:45:40 +00007586 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007587 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007588 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7589 VK = rhs.get()->getValueKind();
7590 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007591 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007592 break;
7593 }
John Wiegley01296292011-04-08 18:41:53 +00007594 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007595 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007596 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007597 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7598 ResultTy, VK, OK, OpLoc));
7599 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007600 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007601 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007602 }
John Wiegley01296292011-04-08 18:41:53 +00007603 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7604 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007605 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007606}
7607
Sebastian Redl44615072009-10-27 12:10:02 +00007608/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7609/// operators are mixed in a way that suggests that the programmer forgot that
7610/// comparison operators have higher precedence. The most typical example of
7611/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007612static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007613 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007614 typedef BinaryOperator BinOp;
7615 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7616 rhsopc = static_cast<BinOp::Opcode>(-1);
7617 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007618 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007619 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007620 rhsopc = BO->getOpcode();
7621
7622 // Subs are not binary operators.
7623 if (lhsopc == -1 && rhsopc == -1)
7624 return;
7625
7626 // Bitwise operations are sometimes used as eager logical ops.
7627 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007628 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7629 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007630 return;
7631
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007632 if (BinOp::isComparisonOp(lhsopc)) {
7633 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7634 << SourceRange(lhs->getLocStart(), OpLoc)
7635 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007636 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007637 Self.PDiag(diag::note_precedence_bitwise_silence)
7638 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007639 lhs->getSourceRange());
7640 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007641 Self.PDiag(diag::note_precedence_bitwise_first)
7642 << BinOp::getOpcodeStr(Opc),
7643 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007644 } else if (BinOp::isComparisonOp(rhsopc)) {
7645 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7646 << SourceRange(OpLoc, rhs->getLocEnd())
7647 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007648 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007649 Self.PDiag(diag::note_precedence_bitwise_silence)
7650 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007651 rhs->getSourceRange());
7652 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007653 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007654 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007655 SourceRange(lhs->getLocStart(),
7656 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007657 }
Sebastian Redl43028242009-10-26 15:24:15 +00007658}
7659
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007660/// \brief It accepts a '&' expr that is inside a '|' one.
7661/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7662/// in parentheses.
7663static void
7664EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7665 BinaryOperator *Bop) {
7666 assert(Bop->getOpcode() == BO_And);
7667 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7668 << Bop->getSourceRange() << OpLoc;
7669 SuggestParentheses(Self, Bop->getOperatorLoc(),
7670 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7671 Bop->getSourceRange());
7672}
7673
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007674/// \brief It accepts a '&&' expr that is inside a '||' one.
7675/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7676/// in parentheses.
7677static void
7678EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007679 BinaryOperator *Bop) {
7680 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007681 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7682 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007683 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007684 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007685 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007686}
7687
7688/// \brief Returns true if the given expression can be evaluated as a constant
7689/// 'true'.
7690static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7691 bool Res;
7692 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7693}
7694
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007695/// \brief Returns true if the given expression can be evaluated as a constant
7696/// 'false'.
7697static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7698 bool Res;
7699 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7700}
7701
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007702/// \brief Look for '&&' in the left hand of a '||' expr.
7703static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007704 Expr *OrLHS, Expr *OrRHS) {
7705 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007706 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007707 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7708 if (EvaluatesAsFalse(S, OrRHS))
7709 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007710 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7711 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7712 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7713 } else if (Bop->getOpcode() == BO_LOr) {
7714 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7715 // If it's "a || b && 1 || c" we didn't warn earlier for
7716 // "a || b && 1", but warn now.
7717 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7718 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7719 }
7720 }
7721 }
7722}
7723
7724/// \brief Look for '&&' in the right hand of a '||' expr.
7725static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007726 Expr *OrLHS, Expr *OrRHS) {
7727 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007728 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007729 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7730 if (EvaluatesAsFalse(S, OrLHS))
7731 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007732 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7733 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7734 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007735 }
7736 }
7737}
7738
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007739/// \brief Look for '&' in the left or right hand of a '|' expr.
7740static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7741 Expr *OrArg) {
7742 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7743 if (Bop->getOpcode() == BO_And)
7744 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7745 }
7746}
7747
Sebastian Redl43028242009-10-26 15:24:15 +00007748/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007749/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007750static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007751 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007752 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007753 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007754 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7755
7756 // Diagnose "arg1 & arg2 | arg3"
7757 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7758 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7759 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7760 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007761
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007762 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7763 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007764 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007765 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7766 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007767 }
Sebastian Redl43028242009-10-26 15:24:15 +00007768}
7769
Steve Naroff218bc2b2007-05-04 21:54:46 +00007770// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007771ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007772 tok::TokenKind Kind,
7773 Expr *lhs, Expr *rhs) {
7774 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007775 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7776 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007777
Sebastian Redl43028242009-10-26 15:24:15 +00007778 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7779 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7780
Douglas Gregor5287f092009-11-05 00:51:44 +00007781 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7782}
7783
John McCalldadc5752010-08-24 06:29:42 +00007784ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007785 BinaryOperatorKind Opc,
7786 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007787 if (getLangOptions().CPlusPlus) {
7788 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007789
John McCall622114c2010-12-06 05:26:58 +00007790 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7791 UseBuiltinOperator = false;
7792 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7793 UseBuiltinOperator = true;
7794 } else {
7795 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7796 !rhs->getType()->isOverloadableType();
7797 }
7798
7799 if (!UseBuiltinOperator) {
7800 // Find all of the overloaded operators visible from this
7801 // point. We perform both an operator-name lookup from the local
7802 // scope and an argument-dependent lookup based on the types of
7803 // the arguments.
7804 UnresolvedSet<16> Functions;
7805 OverloadedOperatorKind OverOp
7806 = BinaryOperator::getOverloadedOperator(Opc);
7807 if (S && OverOp != OO_None)
7808 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7809 Functions);
7810
7811 // Build the (potentially-overloaded, potentially-dependent)
7812 // binary operation.
7813 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7814 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007815 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007816
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007817 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007818 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007819}
7820
John McCalldadc5752010-08-24 06:29:42 +00007821ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007822 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007823 Expr *InputExpr) {
7824 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007825 ExprValueKind VK = VK_RValue;
7826 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007827 QualType resultType;
7828 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007829 case UO_PreInc:
7830 case UO_PreDec:
7831 case UO_PostInc:
7832 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007833 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007834 Opc == UO_PreInc ||
7835 Opc == UO_PostInc,
7836 Opc == UO_PreInc ||
7837 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007838 break;
John McCalle3027922010-08-25 11:45:40 +00007839 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007840 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007841 break;
John McCall31996342011-04-07 08:22:57 +00007842 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007843 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007844 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007845 Input = move(resolved);
7846 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7847 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007848 break;
John McCall31996342011-04-07 08:22:57 +00007849 }
John McCalle3027922010-08-25 11:45:40 +00007850 case UO_Plus:
7851 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007852 Input = UsualUnaryConversions(Input.take());
7853 if (Input.isInvalid()) return ExprError();
7854 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007855 if (resultType->isDependentType())
7856 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007857 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7858 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007859 break;
7860 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7861 resultType->isEnumeralType())
7862 break;
7863 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007864 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007865 resultType->isPointerType())
7866 break;
John McCall36226622010-10-12 02:09:17 +00007867 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007868 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007869 if (Input.isInvalid()) return ExprError();
7870 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007871 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007872
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007873 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007874 << resultType << Input.get()->getSourceRange());
7875
John McCalle3027922010-08-25 11:45:40 +00007876 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007877 Input = UsualUnaryConversions(Input.take());
7878 if (Input.isInvalid()) return ExprError();
7879 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007880 if (resultType->isDependentType())
7881 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007882 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7883 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7884 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007885 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007886 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007887 else if (resultType->hasIntegerRepresentation())
7888 break;
7889 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007890 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007891 if (Input.isInvalid()) return ExprError();
7892 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007893 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007894 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007895 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007896 }
Steve Naroff35d85152007-05-07 00:24:15 +00007897 break;
John Wiegley01296292011-04-08 18:41:53 +00007898
John McCalle3027922010-08-25 11:45:40 +00007899 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007900 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007901 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7902 if (Input.isInvalid()) return ExprError();
7903 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007904 if (resultType->isDependentType())
7905 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007906 if (resultType->isScalarType()) {
7907 // C99 6.5.3.3p1: ok, fallthrough;
7908 if (Context.getLangOptions().CPlusPlus) {
7909 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7910 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007911 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7912 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007913 }
John McCall36226622010-10-12 02:09:17 +00007914 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007915 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007916 if (Input.isInvalid()) return ExprError();
7917 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007918 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007919 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007920 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007921 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007922
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007923 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007924 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007925 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007926 break;
John McCalle3027922010-08-25 11:45:40 +00007927 case UO_Real:
7928 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007929 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007930 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007931 if (Input.isInvalid()) return ExprError();
7932 if (Input.get()->getValueKind() != VK_RValue &&
7933 Input.get()->getObjectKind() == OK_Ordinary)
7934 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007935 break;
John McCalle3027922010-08-25 11:45:40 +00007936 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007937 resultType = Input.get()->getType();
7938 VK = Input.get()->getValueKind();
7939 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007940 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007941 }
John Wiegley01296292011-04-08 18:41:53 +00007942 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007943 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007944
John Wiegley01296292011-04-08 18:41:53 +00007945 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007946 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007947}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007948
John McCalldadc5752010-08-24 06:29:42 +00007949ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007950 UnaryOperatorKind Opc,
7951 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007952 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007953 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007954 // Find all of the overloaded operators visible from this
7955 // point. We perform both an operator-name lookup from the local
7956 // scope and an argument-dependent lookup based on the types of
7957 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007958 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007959 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007960 if (S && OverOp != OO_None)
7961 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7962 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007963
John McCallb268a282010-08-23 23:25:46 +00007964 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007965 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007966
John McCallb268a282010-08-23 23:25:46 +00007967 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007968}
7969
Douglas Gregor5287f092009-11-05 00:51:44 +00007970// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007971ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007972 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007973 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007974}
7975
Steve Naroff66356bd2007-09-16 14:56:35 +00007976/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007977ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007978 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007979 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007980 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007981 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007982 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007983}
7984
John McCall31168b02011-06-15 23:02:42 +00007985/// Given the last statement in a statement-expression, check whether
7986/// the result is a producing expression (like a call to an
7987/// ns_returns_retained function) and, if so, rebuild it to hoist the
7988/// release out of the full-expression. Otherwise, return null.
7989/// Cannot fail.
7990static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7991 // Should always be wrapped with one of these.
7992 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7993 if (!cleanups) return 0;
7994
7995 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7996 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7997 return 0;
7998
7999 // Splice out the cast. This shouldn't modify any interesting
8000 // features of the statement.
8001 Expr *producer = cast->getSubExpr();
8002 assert(producer->getType() == cast->getType());
8003 assert(producer->getValueKind() == cast->getValueKind());
8004 cleanups->setSubExpr(producer);
8005 return cleanups;
8006}
8007
John McCalldadc5752010-08-24 06:29:42 +00008008ExprResult
John McCallb268a282010-08-23 23:25:46 +00008009Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008010 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008011 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8012 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8013
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008014 bool isFileScope
8015 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008016 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008017 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008018
Chris Lattner366727f2007-07-24 16:58:17 +00008019 // FIXME: there are a variety of strange constraints to enforce here, for
8020 // example, it is not possible to goto into a stmt expression apparently.
8021 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008022
Chris Lattner366727f2007-07-24 16:58:17 +00008023 // If there are sub stmts in the compound stmt, take the type of the last one
8024 // as the type of the stmtexpr.
8025 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008026 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008027 if (!Compound->body_empty()) {
8028 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008029 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008030 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008031 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8032 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008033 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008034 }
John McCall31168b02011-06-15 23:02:42 +00008035
John Wiegley01296292011-04-08 18:41:53 +00008036 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008037 // Do function/array conversion on the last expression, but not
8038 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008039 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8040 if (LastExpr.isInvalid())
8041 return ExprError();
8042 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008043
John Wiegley01296292011-04-08 18:41:53 +00008044 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008045 // In ARC, if the final expression ends in a consume, splice
8046 // the consume out and bind it later. In the alternate case
8047 // (when dealing with a retainable type), the result
8048 // initialization will create a produce. In both cases the
8049 // result will be +1, and we'll need to balance that out with
8050 // a bind.
8051 if (Expr *rebuiltLastStmt
8052 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8053 LastExpr = rebuiltLastStmt;
8054 } else {
8055 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008056 InitializedEntity::InitializeResult(LPLoc,
8057 Ty,
8058 false),
8059 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008060 LastExpr);
8061 }
8062
John Wiegley01296292011-04-08 18:41:53 +00008063 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008064 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008065 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008066 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008067 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008068 else
John Wiegley01296292011-04-08 18:41:53 +00008069 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008070 StmtExprMayBindToTemp = true;
8071 }
8072 }
8073 }
Chris Lattner944d3062008-07-26 19:51:01 +00008074 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008075
Eli Friedmanba961a92009-03-23 00:24:07 +00008076 // FIXME: Check that expression type is complete/non-abstract; statement
8077 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008078 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8079 if (StmtExprMayBindToTemp)
8080 return MaybeBindToTemporary(ResStmtExpr);
8081 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008082}
Steve Naroff78864672007-08-01 22:05:33 +00008083
John McCalldadc5752010-08-24 06:29:42 +00008084ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008085 TypeSourceInfo *TInfo,
8086 OffsetOfComponent *CompPtr,
8087 unsigned NumComponents,
8088 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008089 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008090 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008091 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008092
Chris Lattnerf17bd422007-08-30 17:45:32 +00008093 // We must have at least one component that refers to the type, and the first
8094 // one is known to be a field designator. Verify that the ArgTy represents
8095 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008096 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008097 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8098 << ArgTy << TypeRange);
8099
8100 // Type must be complete per C99 7.17p3 because a declaring a variable
8101 // with an incomplete type would be ill-formed.
8102 if (!Dependent
8103 && RequireCompleteType(BuiltinLoc, ArgTy,
8104 PDiag(diag::err_offsetof_incomplete_type)
8105 << TypeRange))
8106 return ExprError();
8107
Chris Lattner78502cf2007-08-31 21:49:13 +00008108 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8109 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008110 // FIXME: This diagnostic isn't actually visible because the location is in
8111 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008112 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008113 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8114 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008115
8116 bool DidWarnAboutNonPOD = false;
8117 QualType CurrentType = ArgTy;
8118 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008119 SmallVector<OffsetOfNode, 4> Comps;
8120 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008121 for (unsigned i = 0; i != NumComponents; ++i) {
8122 const OffsetOfComponent &OC = CompPtr[i];
8123 if (OC.isBrackets) {
8124 // Offset of an array sub-field. TODO: Should we allow vector elements?
8125 if (!CurrentType->isDependentType()) {
8126 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8127 if(!AT)
8128 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8129 << CurrentType);
8130 CurrentType = AT->getElementType();
8131 } else
8132 CurrentType = Context.DependentTy;
8133
8134 // The expression must be an integral expression.
8135 // FIXME: An integral constant expression?
8136 Expr *Idx = static_cast<Expr*>(OC.U.E);
8137 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8138 !Idx->getType()->isIntegerType())
8139 return ExprError(Diag(Idx->getLocStart(),
8140 diag::err_typecheck_subscript_not_integer)
8141 << Idx->getSourceRange());
8142
8143 // Record this array index.
8144 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8145 Exprs.push_back(Idx);
8146 continue;
8147 }
8148
8149 // Offset of a field.
8150 if (CurrentType->isDependentType()) {
8151 // We have the offset of a field, but we can't look into the dependent
8152 // type. Just record the identifier of the field.
8153 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8154 CurrentType = Context.DependentTy;
8155 continue;
8156 }
8157
8158 // We need to have a complete type to look into.
8159 if (RequireCompleteType(OC.LocStart, CurrentType,
8160 diag::err_offsetof_incomplete_type))
8161 return ExprError();
8162
8163 // Look for the designated field.
8164 const RecordType *RC = CurrentType->getAs<RecordType>();
8165 if (!RC)
8166 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8167 << CurrentType);
8168 RecordDecl *RD = RC->getDecl();
8169
8170 // C++ [lib.support.types]p5:
8171 // The macro offsetof accepts a restricted set of type arguments in this
8172 // International Standard. type shall be a POD structure or a POD union
8173 // (clause 9).
8174 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8175 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008176 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008177 PDiag(diag::warn_offsetof_non_pod_type)
8178 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8179 << CurrentType))
8180 DidWarnAboutNonPOD = true;
8181 }
8182
8183 // Look for the field.
8184 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8185 LookupQualifiedName(R, RD);
8186 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008187 IndirectFieldDecl *IndirectMemberDecl = 0;
8188 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008189 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008190 MemberDecl = IndirectMemberDecl->getAnonField();
8191 }
8192
Douglas Gregor882211c2010-04-28 22:16:22 +00008193 if (!MemberDecl)
8194 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8195 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8196 OC.LocEnd));
8197
Douglas Gregor10982ea2010-04-28 22:36:06 +00008198 // C99 7.17p3:
8199 // (If the specified member is a bit-field, the behavior is undefined.)
8200 //
8201 // We diagnose this as an error.
8202 if (MemberDecl->getBitWidth()) {
8203 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8204 << MemberDecl->getDeclName()
8205 << SourceRange(BuiltinLoc, RParenLoc);
8206 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8207 return ExprError();
8208 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008209
8210 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008211 if (IndirectMemberDecl)
8212 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008213
Douglas Gregord1702062010-04-29 00:18:15 +00008214 // If the member was found in a base class, introduce OffsetOfNodes for
8215 // the base class indirections.
8216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8217 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008218 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008219 CXXBasePath &Path = Paths.front();
8220 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8221 B != BEnd; ++B)
8222 Comps.push_back(OffsetOfNode(B->Base));
8223 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008224
Francois Pichet783dd6e2010-11-21 06:08:52 +00008225 if (IndirectMemberDecl) {
8226 for (IndirectFieldDecl::chain_iterator FI =
8227 IndirectMemberDecl->chain_begin(),
8228 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8229 assert(isa<FieldDecl>(*FI));
8230 Comps.push_back(OffsetOfNode(OC.LocStart,
8231 cast<FieldDecl>(*FI), OC.LocEnd));
8232 }
8233 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008234 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008235
Douglas Gregor882211c2010-04-28 22:16:22 +00008236 CurrentType = MemberDecl->getType().getNonReferenceType();
8237 }
8238
8239 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8240 TInfo, Comps.data(), Comps.size(),
8241 Exprs.data(), Exprs.size(), RParenLoc));
8242}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008243
John McCalldadc5752010-08-24 06:29:42 +00008244ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008245 SourceLocation BuiltinLoc,
8246 SourceLocation TypeLoc,
8247 ParsedType argty,
8248 OffsetOfComponent *CompPtr,
8249 unsigned NumComponents,
8250 SourceLocation RPLoc) {
8251
Douglas Gregor882211c2010-04-28 22:16:22 +00008252 TypeSourceInfo *ArgTInfo;
8253 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8254 if (ArgTy.isNull())
8255 return ExprError();
8256
Eli Friedman06dcfd92010-08-05 10:15:45 +00008257 if (!ArgTInfo)
8258 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8259
8260 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8261 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008262}
8263
8264
John McCalldadc5752010-08-24 06:29:42 +00008265ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008266 Expr *CondExpr,
8267 Expr *LHSExpr, Expr *RHSExpr,
8268 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008269 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8270
John McCall7decc9e2010-11-18 06:31:45 +00008271 ExprValueKind VK = VK_RValue;
8272 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008273 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008274 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008275 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008276 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008277 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008278 } else {
8279 // The conditional expression is required to be a constant expression.
8280 llvm::APSInt condEval(32);
8281 SourceLocation ExpLoc;
8282 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008283 return ExprError(Diag(ExpLoc,
8284 diag::err_typecheck_choose_expr_requires_constant)
8285 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008286
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008287 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008288 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8289
8290 resType = ActiveExpr->getType();
8291 ValueDependent = ActiveExpr->isValueDependent();
8292 VK = ActiveExpr->getValueKind();
8293 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008294 }
8295
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008296 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008297 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008298 resType->isDependentType(),
8299 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008300}
8301
Steve Naroffc540d662008-09-03 18:15:37 +00008302//===----------------------------------------------------------------------===//
8303// Clang Extensions.
8304//===----------------------------------------------------------------------===//
8305
8306/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008307void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008308 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8309 PushBlockScope(BlockScope, Block);
8310 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008311 if (BlockScope)
8312 PushDeclContext(BlockScope, Block);
8313 else
8314 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008315}
8316
Mike Stump82f071f2009-02-04 22:31:32 +00008317void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008318 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008319 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008320 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008321
John McCall8cb7bdf2010-06-04 23:28:52 +00008322 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008323 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008324
John McCall3882ace2011-01-05 12:14:39 +00008325 // GetTypeForDeclarator always produces a function type for a block
8326 // literal signature. Furthermore, it is always a FunctionProtoType
8327 // unless the function was written with a typedef.
8328 assert(T->isFunctionType() &&
8329 "GetTypeForDeclarator made a non-function block signature");
8330
8331 // Look for an explicit signature in that function type.
8332 FunctionProtoTypeLoc ExplicitSignature;
8333
8334 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8335 if (isa<FunctionProtoTypeLoc>(tmp)) {
8336 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8337
8338 // Check whether that explicit signature was synthesized by
8339 // GetTypeForDeclarator. If so, don't save that as part of the
8340 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008341 if (ExplicitSignature.getLocalRangeBegin() ==
8342 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008343 // This would be much cheaper if we stored TypeLocs instead of
8344 // TypeSourceInfos.
8345 TypeLoc Result = ExplicitSignature.getResultLoc();
8346 unsigned Size = Result.getFullDataSize();
8347 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8348 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8349
8350 ExplicitSignature = FunctionProtoTypeLoc();
8351 }
John McCalla3ccba02010-06-04 11:21:44 +00008352 }
Mike Stump11289f42009-09-09 15:08:12 +00008353
John McCall3882ace2011-01-05 12:14:39 +00008354 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8355 CurBlock->FunctionType = T;
8356
8357 const FunctionType *Fn = T->getAs<FunctionType>();
8358 QualType RetTy = Fn->getResultType();
8359 bool isVariadic =
8360 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8361
John McCall8e346702010-06-04 19:02:56 +00008362 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008363
John McCalla3ccba02010-06-04 11:21:44 +00008364 // Don't allow returning a objc interface by value.
8365 if (RetTy->isObjCObjectType()) {
8366 Diag(ParamInfo.getSourceRange().getBegin(),
8367 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8368 return;
8369 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008370
John McCalla3ccba02010-06-04 11:21:44 +00008371 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008372 // return type. TODO: what should we do with declarators like:
8373 // ^ * { ... }
8374 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008375 if (RetTy != Context.DependentTy)
8376 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008377
John McCalla3ccba02010-06-04 11:21:44 +00008378 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008379 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008380 if (ExplicitSignature) {
8381 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8382 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008383 if (Param->getIdentifier() == 0 &&
8384 !Param->isImplicit() &&
8385 !Param->isInvalidDecl() &&
8386 !getLangOptions().CPlusPlus)
8387 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008388 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008389 }
John McCalla3ccba02010-06-04 11:21:44 +00008390
8391 // Fake up parameter variables if we have a typedef, like
8392 // ^ fntype { ... }
8393 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8394 for (FunctionProtoType::arg_type_iterator
8395 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8396 ParmVarDecl *Param =
8397 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8398 ParamInfo.getSourceRange().getBegin(),
8399 *I);
John McCall8e346702010-06-04 19:02:56 +00008400 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008401 }
Steve Naroffc540d662008-09-03 18:15:37 +00008402 }
John McCalla3ccba02010-06-04 11:21:44 +00008403
John McCall8e346702010-06-04 19:02:56 +00008404 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008405 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008406 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008407 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8408 CurBlock->TheDecl->param_end(),
8409 /*CheckParameterNames=*/false);
8410 }
8411
John McCalla3ccba02010-06-04 11:21:44 +00008412 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008413 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008414
John McCall8e346702010-06-04 19:02:56 +00008415 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008416 Diag(ParamInfo.getAttributes()->getLoc(),
8417 diag::warn_attribute_sentinel_not_variadic) << 1;
8418 // FIXME: remove the attribute.
8419 }
8420
8421 // Put the parameter variables in scope. We can bail out immediately
8422 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008423 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008424 return;
8425
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008426 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008427 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8428 (*AI)->setOwningFunction(CurBlock->TheDecl);
8429
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008430 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008431 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008432 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008433
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008434 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008435 }
John McCallf7b2fb52010-01-22 00:28:27 +00008436 }
Steve Naroffc540d662008-09-03 18:15:37 +00008437}
8438
8439/// ActOnBlockError - If there is an error parsing a block, this callback
8440/// is invoked to pop the information about the block from the action impl.
8441void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008442 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008443 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008444 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008445}
8446
8447/// ActOnBlockStmtExpr - This is called when the body of a block statement
8448/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008449ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008450 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008451 // If blocks are disabled, emit an error.
8452 if (!LangOpts.Blocks)
8453 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008454
Douglas Gregor9a28e842010-03-01 23:15:13 +00008455 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008456
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008457 PopDeclContext();
8458
Steve Naroffc540d662008-09-03 18:15:37 +00008459 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008460 if (!BSI->ReturnType.isNull())
8461 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008462
Mike Stump3bf1ab42009-07-28 22:04:01 +00008463 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008464 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008465
John McCallc63de662011-02-02 13:00:07 +00008466 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008467 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8468 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008469
John McCall8e346702010-06-04 19:02:56 +00008470 // If the user wrote a function type in some form, try to use that.
8471 if (!BSI->FunctionType.isNull()) {
8472 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8473
8474 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8475 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8476
8477 // Turn protoless block types into nullary block types.
8478 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008479 FunctionProtoType::ExtProtoInfo EPI;
8480 EPI.ExtInfo = Ext;
8481 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008482
8483 // Otherwise, if we don't need to change anything about the function type,
8484 // preserve its sugar structure.
8485 } else if (FTy->getResultType() == RetTy &&
8486 (!NoReturn || FTy->getNoReturnAttr())) {
8487 BlockTy = BSI->FunctionType;
8488
8489 // Otherwise, make the minimal modifications to the function type.
8490 } else {
8491 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008492 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8493 EPI.TypeQuals = 0; // FIXME: silently?
8494 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008495 BlockTy = Context.getFunctionType(RetTy,
8496 FPT->arg_type_begin(),
8497 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008498 EPI);
John McCall8e346702010-06-04 19:02:56 +00008499 }
8500
8501 // If we don't have a function type, just build one from nothing.
8502 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008503 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008504 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008505 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008506 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008507
John McCall8e346702010-06-04 19:02:56 +00008508 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8509 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008510 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008511
Chris Lattner45542ea2009-04-19 05:28:12 +00008512 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008513 if (getCurFunction()->NeedsScopeChecking() &&
8514 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008515 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008516
Chris Lattner60f84492011-02-17 23:58:47 +00008517 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008518
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008519 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8520 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8521 const VarDecl *variable = ci->getVariable();
8522 QualType T = variable->getType();
8523 QualType::DestructionKind destructKind = T.isDestructedType();
8524 if (destructKind != QualType::DK_none)
8525 getCurFunction()->setHasBranchProtectedScope();
8526 }
8527
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008528 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8529 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8530 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8531
Douglas Gregor9a28e842010-03-01 23:15:13 +00008532 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008533}
8534
John McCalldadc5752010-08-24 06:29:42 +00008535ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008536 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008537 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008538 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008539 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008540 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008541}
8542
John McCalldadc5752010-08-24 06:29:42 +00008543ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008544 Expr *E, TypeSourceInfo *TInfo,
8545 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008546 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008547
Eli Friedman121ba0c2008-08-09 23:32:40 +00008548 // Get the va_list type
8549 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008550 if (VaListType->isArrayType()) {
8551 // Deal with implicit array decay; for example, on x86-64,
8552 // va_list is an array, but it's supposed to decay to
8553 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008554 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008555 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008556 ExprResult Result = UsualUnaryConversions(E);
8557 if (Result.isInvalid())
8558 return ExprError();
8559 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008560 } else {
8561 // Otherwise, the va_list argument must be an l-value because
8562 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008563 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008564 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008565 return ExprError();
8566 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008567
Douglas Gregorad3150c2009-05-19 23:10:31 +00008568 if (!E->isTypeDependent() &&
8569 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008570 return ExprError(Diag(E->getLocStart(),
8571 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008572 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008573 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008574
David Majnemerc75d1a12011-06-14 05:17:32 +00008575 if (!TInfo->getType()->isDependentType()) {
8576 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8577 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8578 << TInfo->getTypeLoc().getSourceRange()))
8579 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008580
David Majnemerc75d1a12011-06-14 05:17:32 +00008581 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8582 TInfo->getType(),
8583 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8584 << TInfo->getTypeLoc().getSourceRange()))
8585 return ExprError();
8586
John McCall31168b02011-06-15 23:02:42 +00008587 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00008588 Diag(TInfo->getTypeLoc().getBeginLoc(),
8589 diag::warn_second_parameter_to_va_arg_not_pod)
8590 << TInfo->getType()
8591 << TInfo->getTypeLoc().getSourceRange();
Eli Friedman6290ae42011-07-11 21:45:59 +00008592
8593 // Check for va_arg where arguments of the given type will be promoted
8594 // (i.e. this va_arg is guaranteed to have undefined behavior).
8595 QualType PromoteType;
8596 if (TInfo->getType()->isPromotableIntegerType()) {
8597 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8598 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8599 PromoteType = QualType();
8600 }
8601 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8602 PromoteType = Context.DoubleTy;
8603 if (!PromoteType.isNull())
8604 Diag(TInfo->getTypeLoc().getBeginLoc(),
8605 diag::warn_second_parameter_to_va_arg_never_compatible)
8606 << TInfo->getType()
8607 << PromoteType
8608 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008609 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008610
Abramo Bagnara27db2392010-08-10 10:06:15 +00008611 QualType T = TInfo->getType().getNonLValueExprType(Context);
8612 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008613}
8614
John McCalldadc5752010-08-24 06:29:42 +00008615ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008616 // The type of __null will be int or long, depending on the size of
8617 // pointers on the target.
8618 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008619 unsigned pw = Context.Target.getPointerWidth(0);
8620 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008621 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008622 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008623 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008624 else if (pw == Context.Target.getLongLongWidth())
8625 Ty = Context.LongLongTy;
8626 else {
8627 assert(!"I don't know size of pointer!");
8628 Ty = Context.IntTy;
8629 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008630
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008631 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008632}
8633
Alexis Huntc46382e2010-04-28 23:02:27 +00008634static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008635 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008636 if (!SemaRef.getLangOptions().ObjC1)
8637 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008638
Anders Carlssonace5d072009-11-10 04:46:30 +00008639 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8640 if (!PT)
8641 return;
8642
8643 // Check if the destination is of type 'id'.
8644 if (!PT->isObjCIdType()) {
8645 // Check if the destination is the 'NSString' interface.
8646 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8647 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8648 return;
8649 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008650
Anders Carlssonace5d072009-11-10 04:46:30 +00008651 // Strip off any parens and casts.
8652 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008653 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008654 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008655
Douglas Gregora771f462010-03-31 17:46:05 +00008656 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008657}
8658
Chris Lattner9bad62c2008-01-04 18:04:52 +00008659bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8660 SourceLocation Loc,
8661 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008662 Expr *SrcExpr, AssignmentAction Action,
8663 bool *Complained) {
8664 if (Complained)
8665 *Complained = false;
8666
Chris Lattner9bad62c2008-01-04 18:04:52 +00008667 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008668 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008669 bool isInvalid = false;
8670 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008671 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008672 ConversionFixItGenerator ConvHints;
8673 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008674
Chris Lattner9bad62c2008-01-04 18:04:52 +00008675 switch (ConvTy) {
8676 default: assert(0 && "Unknown conversion type");
8677 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008678 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008679 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008680 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8681 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008682 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008683 case IntToPointer:
8684 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008685 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8686 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008687 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008688 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008689 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008690 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008691 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8692 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008693 if (Hint.isNull() && !CheckInferredResultType) {
8694 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8695 }
8696 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008697 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008698 case IncompatiblePointerSign:
8699 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8700 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008701 case FunctionVoidPointer:
8702 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8703 break;
John McCall4fff8f62011-02-01 00:10:29 +00008704 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008705 // Perform array-to-pointer decay if necessary.
8706 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8707
John McCall4fff8f62011-02-01 00:10:29 +00008708 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8709 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8710 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8711 DiagKind = diag::err_typecheck_incompatible_address_space;
8712 break;
John McCall31168b02011-06-15 23:02:42 +00008713
8714
8715 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008716 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008717 break;
John McCall4fff8f62011-02-01 00:10:29 +00008718 }
8719
8720 llvm_unreachable("unknown error case for discarding qualifiers!");
8721 // fallthrough
8722 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008723 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008724 // If the qualifiers lost were because we were applying the
8725 // (deprecated) C++ conversion from a string literal to a char*
8726 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8727 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008728 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008729 // bit of refactoring (so that the second argument is an
8730 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008731 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008732 // C++ semantics.
8733 if (getLangOptions().CPlusPlus &&
8734 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8735 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008736 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8737 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008738 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008739 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008740 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008741 case IntToBlockPointer:
8742 DiagKind = diag::err_int_to_block_pointer;
8743 break;
8744 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008745 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008746 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008747 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008748 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008749 // it can give a more specific diagnostic.
8750 DiagKind = diag::warn_incompatible_qualified_id;
8751 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008752 case IncompatibleVectors:
8753 DiagKind = diag::warn_incompatible_vectors;
8754 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008755 case IncompatibleObjCWeakRef:
8756 DiagKind = diag::err_arc_weak_unavailable_assign;
8757 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008758 case Incompatible:
8759 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008760 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8761 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008762 isInvalid = true;
8763 break;
8764 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008765
Douglas Gregorc68e1402010-04-09 00:35:39 +00008766 QualType FirstType, SecondType;
8767 switch (Action) {
8768 case AA_Assigning:
8769 case AA_Initializing:
8770 // The destination type comes first.
8771 FirstType = DstType;
8772 SecondType = SrcType;
8773 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008774
Douglas Gregorc68e1402010-04-09 00:35:39 +00008775 case AA_Returning:
8776 case AA_Passing:
8777 case AA_Converting:
8778 case AA_Sending:
8779 case AA_Casting:
8780 // The source type comes first.
8781 FirstType = SrcType;
8782 SecondType = DstType;
8783 break;
8784 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008785
Anna Zaks3b402712011-07-28 19:51:27 +00008786 PartialDiagnostic FDiag = PDiag(DiagKind);
8787 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8788
8789 // If we can fix the conversion, suggest the FixIts.
8790 assert(ConvHints.isNull() || Hint.isNull());
8791 if (!ConvHints.isNull()) {
8792 for (llvm::SmallVector<FixItHint, 1>::iterator
8793 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8794 HI != HE; ++HI)
8795 FDiag << *HI;
8796 } else {
8797 FDiag << Hint;
8798 }
8799 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8800
8801 Diag(Loc, FDiag);
8802
Douglas Gregor33823722011-06-11 01:09:30 +00008803 if (CheckInferredResultType)
8804 EmitRelatedResultTypeNote(SrcExpr);
8805
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008806 if (Complained)
8807 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008808 return isInvalid;
8809}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008810
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008811bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008812 llvm::APSInt ICEResult;
8813 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8814 if (Result)
8815 *Result = ICEResult;
8816 return false;
8817 }
8818
Anders Carlssone54e8a12008-11-30 19:50:32 +00008819 Expr::EvalResult EvalResult;
8820
Mike Stump4e1f26a2009-02-19 03:04:26 +00008821 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008822 EvalResult.HasSideEffects) {
8823 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8824
8825 if (EvalResult.Diag) {
8826 // We only show the note if it's not the usual "invalid subexpression"
8827 // or if it's actually in a subexpression.
8828 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8829 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8830 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8831 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008832
Anders Carlssone54e8a12008-11-30 19:50:32 +00008833 return true;
8834 }
8835
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008836 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8837 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008838
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008839 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008840 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8841 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008842 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008843
Anders Carlssone54e8a12008-11-30 19:50:32 +00008844 if (Result)
8845 *Result = EvalResult.Val.getInt();
8846 return false;
8847}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008848
Douglas Gregorff790f12009-11-26 00:44:06 +00008849void
Mike Stump11289f42009-09-09 15:08:12 +00008850Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008851 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008852 ExpressionEvaluationContextRecord(NewContext,
8853 ExprTemporaries.size(),
8854 ExprNeedsCleanups));
8855 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008856}
8857
Mike Stump11289f42009-09-09 15:08:12 +00008858void
Douglas Gregorff790f12009-11-26 00:44:06 +00008859Sema::PopExpressionEvaluationContext() {
8860 // Pop the current expression evaluation context off the stack.
8861 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8862 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008863
Douglas Gregorfab31f42009-12-12 07:57:52 +00008864 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8865 if (Rec.PotentiallyReferenced) {
8866 // Mark any remaining declarations in the current position of the stack
8867 // as "referenced". If they were not meant to be referenced, semantic
8868 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008869 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008870 I = Rec.PotentiallyReferenced->begin(),
8871 IEnd = Rec.PotentiallyReferenced->end();
8872 I != IEnd; ++I)
8873 MarkDeclarationReferenced(I->first, I->second);
8874 }
8875
8876 if (Rec.PotentiallyDiagnosed) {
8877 // Emit any pending diagnostics.
8878 for (PotentiallyEmittedDiagnostics::iterator
8879 I = Rec.PotentiallyDiagnosed->begin(),
8880 IEnd = Rec.PotentiallyDiagnosed->end();
8881 I != IEnd; ++I)
8882 Diag(I->first, I->second);
8883 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008884 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008885
8886 // When are coming out of an unevaluated context, clear out any
8887 // temporaries that we may have created as part of the evaluation of
8888 // the expression in that context: they aren't relevant because they
8889 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008890 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008891 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8892 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008893 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8894
8895 // Otherwise, merge the contexts together.
8896 } else {
8897 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8898 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008899
8900 // Destroy the popped expression evaluation record.
8901 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008902}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008903
John McCall31168b02011-06-15 23:02:42 +00008904void Sema::DiscardCleanupsInEvaluationContext() {
8905 ExprTemporaries.erase(
8906 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8907 ExprTemporaries.end());
8908 ExprNeedsCleanups = false;
8909}
8910
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008911/// \brief Note that the given declaration was referenced in the source code.
8912///
8913/// This routine should be invoke whenever a given declaration is referenced
8914/// in the source code, and where that reference occurred. If this declaration
8915/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8916/// C99 6.9p3), then the declaration will be marked as used.
8917///
8918/// \param Loc the location where the declaration was referenced.
8919///
8920/// \param D the declaration that has been referenced by the source code.
8921void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8922 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008923
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008924 D->setReferenced();
8925
Douglas Gregorebada0772010-06-17 23:14:26 +00008926 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008927 return;
Mike Stump11289f42009-09-09 15:08:12 +00008928
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008929 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8930 // template or not. The reason for this is that unevaluated expressions
8931 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8932 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008933 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008934 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008935 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008936 return;
8937 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008938
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008939 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8940 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008941
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008942 // Do not mark anything as "used" within a dependent context; wait for
8943 // an instantiation.
8944 if (CurContext->isDependentContext())
8945 return;
Mike Stump11289f42009-09-09 15:08:12 +00008946
Douglas Gregorff790f12009-11-26 00:44:06 +00008947 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008948 case Unevaluated:
8949 // We are in an expression that is not potentially evaluated; do nothing.
8950 return;
Mike Stump11289f42009-09-09 15:08:12 +00008951
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008952 case PotentiallyEvaluated:
8953 // We are in a potentially-evaluated expression, so this declaration is
8954 // "used"; handle this below.
8955 break;
Mike Stump11289f42009-09-09 15:08:12 +00008956
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008957 case PotentiallyPotentiallyEvaluated:
8958 // We are in an expression that may be potentially evaluated; queue this
8959 // declaration reference until we know whether the expression is
8960 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008961 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008962 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008963
8964 case PotentiallyEvaluatedIfUsed:
8965 // Referenced declarations will only be used if the construct in the
8966 // containing expression is used.
8967 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008968 }
Mike Stump11289f42009-09-09 15:08:12 +00008969
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008970 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008971 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008972 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8973 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008974 return;
8975 if (!Constructor->isUsed(false))
8976 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008977 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008978 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008979 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00008980 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008981 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008982
Douglas Gregor88d292c2010-05-13 16:44:06 +00008983 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008984 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00008985 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008986 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008987 if (Destructor->isVirtual())
8988 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008989 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00008990 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008991 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008992 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008993 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008994 } else if (MethodDecl->isVirtual())
8995 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008996 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008997 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00008998 // Recursive functions should be marked when used from another function.
8999 if (CurContext == Function) return;
9000
Mike Stump11289f42009-09-09 15:08:12 +00009001 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009002 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009003 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009004 bool AlreadyInstantiated = false;
9005 if (FunctionTemplateSpecializationInfo *SpecInfo
9006 = Function->getTemplateSpecializationInfo()) {
9007 if (SpecInfo->getPointOfInstantiation().isInvalid())
9008 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009009 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009010 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009011 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009012 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009013 = Function->getMemberSpecializationInfo()) {
9014 if (MSInfo->getPointOfInstantiation().isInvalid())
9015 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009016 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009017 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009018 AlreadyInstantiated = true;
9019 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009020
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009021 if (!AlreadyInstantiated) {
9022 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9023 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9024 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9025 Loc));
9026 else
Chandler Carruth54080172010-08-25 08:44:16 +00009027 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009028 }
John McCall83779672011-02-19 02:53:41 +00009029 } else {
9030 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009031 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9032 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009033 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009034 MarkDeclarationReferenced(Loc, *i);
9035 }
John McCall83779672011-02-19 02:53:41 +00009036 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009037
John McCall83779672011-02-19 02:53:41 +00009038 // Keep track of used but undefined functions.
9039 if (!Function->isPure() && !Function->hasBody() &&
9040 Function->getLinkage() != ExternalLinkage) {
9041 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9042 if (old.isInvalid()) old = Loc;
9043 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009044
John McCall83779672011-02-19 02:53:41 +00009045 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009046 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009047 }
Mike Stump11289f42009-09-09 15:08:12 +00009048
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009049 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009050 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009051 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009052 Var->getInstantiatedFromStaticDataMember()) {
9053 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9054 assert(MSInfo && "Missing member specialization information?");
9055 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9056 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9057 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009058 // This is a modification of an existing AST node. Notify listeners.
9059 if (ASTMutationListener *L = getASTMutationListener())
9060 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009061 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009062 }
9063 }
Mike Stump11289f42009-09-09 15:08:12 +00009064
John McCall15dd4042011-02-21 19:25:48 +00009065 // Keep track of used but undefined variables. We make a hole in
9066 // the warning for static const data members with in-line
9067 // initializers.
John McCall83779672011-02-19 02:53:41 +00009068 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009069 && Var->getLinkage() != ExternalLinkage
9070 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009071 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9072 if (old.isInvalid()) old = Loc;
9073 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009074
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009075 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009076 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009077 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009078}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009079
Douglas Gregor5597ab42010-05-07 23:12:07 +00009080namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009081 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009082 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009083 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009084 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9085 Sema &S;
9086 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009087
Douglas Gregor5597ab42010-05-07 23:12:07 +00009088 public:
9089 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009090
Douglas Gregor5597ab42010-05-07 23:12:07 +00009091 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009092
9093 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9094 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009095 };
9096}
9097
Chandler Carruthaf80f662010-06-09 08:17:30 +00009098bool MarkReferencedDecls::TraverseTemplateArgument(
9099 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009100 if (Arg.getKind() == TemplateArgument::Declaration) {
9101 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9102 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009103
9104 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009105}
9106
Chandler Carruthaf80f662010-06-09 08:17:30 +00009107bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009108 if (ClassTemplateSpecializationDecl *Spec
9109 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9110 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009111 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009112 }
9113
Chandler Carruthc65667c2010-06-10 10:31:57 +00009114 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009115}
9116
9117void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9118 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009119 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009120}
9121
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009122namespace {
9123 /// \brief Helper class that marks all of the declarations referenced by
9124 /// potentially-evaluated subexpressions as "referenced".
9125 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9126 Sema &S;
9127
9128 public:
9129 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9130
9131 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9132
9133 void VisitDeclRefExpr(DeclRefExpr *E) {
9134 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9135 }
9136
9137 void VisitMemberExpr(MemberExpr *E) {
9138 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009139 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009140 }
9141
9142 void VisitCXXNewExpr(CXXNewExpr *E) {
9143 if (E->getConstructor())
9144 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9145 if (E->getOperatorNew())
9146 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9147 if (E->getOperatorDelete())
9148 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009149 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009150 }
9151
9152 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9153 if (E->getOperatorDelete())
9154 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009155 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9156 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9157 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9158 S.MarkDeclarationReferenced(E->getLocStart(),
9159 S.LookupDestructor(Record));
9160 }
9161
Douglas Gregor32b3de52010-09-11 23:32:50 +00009162 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009163 }
9164
9165 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9166 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009167 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009168 }
9169
9170 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9171 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9172 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009173
9174 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9175 Visit(E->getExpr());
9176 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009177 };
9178}
9179
9180/// \brief Mark any declarations that appear within this expression or any
9181/// potentially-evaluated subexpressions as "referenced".
9182void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9183 EvaluatedExprMarker(*this).Visit(E);
9184}
9185
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009186/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9187/// of the program being compiled.
9188///
9189/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009190/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009191/// possibility that the code will actually be executable. Code in sizeof()
9192/// expressions, code used only during overload resolution, etc., are not
9193/// potentially evaluated. This routine will suppress such diagnostics or,
9194/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009195/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009196/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009197///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009198/// This routine should be used for all diagnostics that describe the run-time
9199/// behavior of a program, such as passing a non-POD value through an ellipsis.
9200/// Failure to do so will likely result in spurious diagnostics or failures
9201/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009202bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009203 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009204 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009205 case Unevaluated:
9206 // The argument will never be evaluated, so don't complain.
9207 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009208
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009209 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009210 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009211 if (stmt && getCurFunctionOrMethodDecl()) {
9212 FunctionScopes.back()->PossiblyUnreachableDiags.
9213 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9214 }
9215 else
9216 Diag(Loc, PD);
9217
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009218 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009219
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009220 case PotentiallyPotentiallyEvaluated:
9221 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9222 break;
9223 }
9224
9225 return false;
9226}
9227
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009228bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9229 CallExpr *CE, FunctionDecl *FD) {
9230 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9231 return false;
9232
9233 PartialDiagnostic Note =
9234 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9235 << FD->getDeclName() : PDiag();
9236 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009237
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009238 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009239 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009240 PDiag(diag::err_call_function_incomplete_return)
9241 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009242 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009243 << CE->getSourceRange(),
9244 std::make_pair(NoteLoc, Note)))
9245 return true;
9246
9247 return false;
9248}
9249
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009250// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009251// will prevent this condition from triggering, which is what we want.
9252void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9253 SourceLocation Loc;
9254
John McCall0506e4a2009-11-11 02:41:58 +00009255 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009256 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009257
John McCalld5707ab2009-10-12 21:59:07 +00009258 if (isa<BinaryOperator>(E)) {
9259 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009260 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009261 return;
9262
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009263 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9264
John McCallb0e419e2009-11-12 00:06:05 +00009265 // Greylist some idioms by putting them into a warning subcategory.
9266 if (ObjCMessageExpr *ME
9267 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9268 Selector Sel = ME->getSelector();
9269
John McCallb0e419e2009-11-12 00:06:05 +00009270 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009271 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009272 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9273
9274 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009275 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009276 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9277 }
John McCall0506e4a2009-11-11 02:41:58 +00009278
John McCalld5707ab2009-10-12 21:59:07 +00009279 Loc = Op->getOperatorLoc();
9280 } else if (isa<CXXOperatorCallExpr>(E)) {
9281 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009282 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009283 return;
9284
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009285 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009286 Loc = Op->getOperatorLoc();
9287 } else {
9288 // Not an assignment.
9289 return;
9290 }
9291
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009292 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009293
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009294 SourceLocation Open = E->getSourceRange().getBegin();
9295 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9296 Diag(Loc, diag::note_condition_assign_silence)
9297 << FixItHint::CreateInsertion(Open, "(")
9298 << FixItHint::CreateInsertion(Close, ")");
9299
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009300 if (IsOrAssign)
9301 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9302 << FixItHint::CreateReplacement(Loc, "!=");
9303 else
9304 Diag(Loc, diag::note_condition_assign_to_comparison)
9305 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009306}
9307
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009308/// \brief Redundant parentheses over an equality comparison can indicate
9309/// that the user intended an assignment used as condition.
9310void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009311 // Don't warn if the parens came from a macro.
9312 SourceLocation parenLoc = parenE->getLocStart();
9313 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9314 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009315 // Don't warn for dependent expressions.
9316 if (parenE->isTypeDependent())
9317 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009318
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009319 Expr *E = parenE->IgnoreParens();
9320
9321 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009322 if (opE->getOpcode() == BO_EQ &&
9323 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9324 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009325 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009326
Ted Kremenekae022092011-02-02 02:20:30 +00009327 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009328 Diag(Loc, diag::note_equality_comparison_silence)
9329 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9330 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009331 Diag(Loc, diag::note_equality_comparison_to_assign)
9332 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009333 }
9334}
9335
John Wiegley01296292011-04-08 18:41:53 +00009336ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009337 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009338 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9339 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009340
John McCall0009fcc2011-04-26 20:42:42 +00009341 ExprResult result = CheckPlaceholderExpr(E);
9342 if (result.isInvalid()) return ExprError();
9343 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009344
John McCall0009fcc2011-04-26 20:42:42 +00009345 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009346 if (getLangOptions().CPlusPlus)
9347 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9348
John Wiegley01296292011-04-08 18:41:53 +00009349 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9350 if (ERes.isInvalid())
9351 return ExprError();
9352 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009353
9354 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009355 if (!T->isScalarType()) { // C99 6.8.4.1p1
9356 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9357 << T << E->getSourceRange();
9358 return ExprError();
9359 }
John McCalld5707ab2009-10-12 21:59:07 +00009360 }
9361
John Wiegley01296292011-04-08 18:41:53 +00009362 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009363}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009364
John McCalldadc5752010-08-24 06:29:42 +00009365ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9366 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009367 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009368 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009369
9370 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009371}
John McCall36e7fe32010-10-12 00:20:44 +00009372
John McCall31996342011-04-07 08:22:57 +00009373namespace {
John McCall2979fe02011-04-12 00:42:48 +00009374 /// A visitor for rebuilding a call to an __unknown_any expression
9375 /// to have an appropriate type.
9376 struct RebuildUnknownAnyFunction
9377 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9378
9379 Sema &S;
9380
9381 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9382
9383 ExprResult VisitStmt(Stmt *S) {
9384 llvm_unreachable("unexpected statement!");
9385 return ExprError();
9386 }
9387
9388 ExprResult VisitExpr(Expr *expr) {
9389 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9390 << expr->getSourceRange();
9391 return ExprError();
9392 }
9393
9394 /// Rebuild an expression which simply semantically wraps another
9395 /// expression which it shares the type and value kind of.
9396 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9397 ExprResult subResult = Visit(expr->getSubExpr());
9398 if (subResult.isInvalid()) return ExprError();
9399
9400 Expr *subExpr = subResult.take();
9401 expr->setSubExpr(subExpr);
9402 expr->setType(subExpr->getType());
9403 expr->setValueKind(subExpr->getValueKind());
9404 assert(expr->getObjectKind() == OK_Ordinary);
9405 return expr;
9406 }
9407
9408 ExprResult VisitParenExpr(ParenExpr *paren) {
9409 return rebuildSugarExpr(paren);
9410 }
9411
9412 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9413 return rebuildSugarExpr(op);
9414 }
9415
9416 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9417 ExprResult subResult = Visit(op->getSubExpr());
9418 if (subResult.isInvalid()) return ExprError();
9419
9420 Expr *subExpr = subResult.take();
9421 op->setSubExpr(subExpr);
9422 op->setType(S.Context.getPointerType(subExpr->getType()));
9423 assert(op->getValueKind() == VK_RValue);
9424 assert(op->getObjectKind() == OK_Ordinary);
9425 return op;
9426 }
9427
9428 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9429 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9430
9431 expr->setType(decl->getType());
9432
9433 assert(expr->getValueKind() == VK_RValue);
9434 if (S.getLangOptions().CPlusPlus &&
9435 !(isa<CXXMethodDecl>(decl) &&
9436 cast<CXXMethodDecl>(decl)->isInstance()))
9437 expr->setValueKind(VK_LValue);
9438
9439 return expr;
9440 }
9441
9442 ExprResult VisitMemberExpr(MemberExpr *mem) {
9443 return resolveDecl(mem, mem->getMemberDecl());
9444 }
9445
9446 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9447 return resolveDecl(ref, ref->getDecl());
9448 }
9449 };
9450}
9451
9452/// Given a function expression of unknown-any type, try to rebuild it
9453/// to have a function type.
9454static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9455 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9456 if (result.isInvalid()) return ExprError();
9457 return S.DefaultFunctionArrayConversion(result.take());
9458}
9459
9460namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009461 /// A visitor for rebuilding an expression of type __unknown_anytype
9462 /// into one which resolves the type directly on the referring
9463 /// expression. Strict preservation of the original source
9464 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009465 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009466 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009467
9468 Sema &S;
9469
9470 /// The current destination type.
9471 QualType DestType;
9472
9473 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9474 : S(S), DestType(castType) {}
9475
John McCall39439732011-04-09 22:50:59 +00009476 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009477 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009478 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009479 }
9480
John McCall2d2e8702011-04-11 07:02:50 +00009481 ExprResult VisitExpr(Expr *expr) {
9482 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9483 << expr->getSourceRange();
9484 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009485 }
9486
John McCall2d2e8702011-04-11 07:02:50 +00009487 ExprResult VisitCallExpr(CallExpr *call);
9488 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9489
John McCall39439732011-04-09 22:50:59 +00009490 /// Rebuild an expression which simply semantically wraps another
9491 /// expression which it shares the type and value kind of.
9492 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9493 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009494 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009495 Expr *subExpr = subResult.take();
9496 expr->setSubExpr(subExpr);
9497 expr->setType(subExpr->getType());
9498 expr->setValueKind(subExpr->getValueKind());
9499 assert(expr->getObjectKind() == OK_Ordinary);
9500 return expr;
9501 }
John McCall31996342011-04-07 08:22:57 +00009502
John McCall39439732011-04-09 22:50:59 +00009503 ExprResult VisitParenExpr(ParenExpr *paren) {
9504 return rebuildSugarExpr(paren);
9505 }
9506
9507 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9508 return rebuildSugarExpr(op);
9509 }
9510
John McCall2979fe02011-04-12 00:42:48 +00009511 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9512 const PointerType *ptr = DestType->getAs<PointerType>();
9513 if (!ptr) {
9514 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9515 << op->getSourceRange();
9516 return ExprError();
9517 }
9518 assert(op->getValueKind() == VK_RValue);
9519 assert(op->getObjectKind() == OK_Ordinary);
9520 op->setType(DestType);
9521
9522 // Build the sub-expression as if it were an object of the pointee type.
9523 DestType = ptr->getPointeeType();
9524 ExprResult subResult = Visit(op->getSubExpr());
9525 if (subResult.isInvalid()) return ExprError();
9526 op->setSubExpr(subResult.take());
9527 return op;
9528 }
9529
John McCall2d2e8702011-04-11 07:02:50 +00009530 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009531
John McCall2979fe02011-04-12 00:42:48 +00009532 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009533
John McCall2979fe02011-04-12 00:42:48 +00009534 ExprResult VisitMemberExpr(MemberExpr *mem) {
9535 return resolveDecl(mem, mem->getMemberDecl());
9536 }
John McCall39439732011-04-09 22:50:59 +00009537
9538 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009539 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009540 }
9541 };
9542}
9543
John McCall2d2e8702011-04-11 07:02:50 +00009544/// Rebuilds a call expression which yielded __unknown_anytype.
9545ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9546 Expr *callee = call->getCallee();
9547
9548 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009549 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009550 FK_FunctionPointer,
9551 FK_BlockPointer
9552 };
9553
9554 FnKind kind;
9555 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009556 if (type == S.Context.BoundMemberTy) {
9557 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9558 kind = FK_MemberFunction;
9559 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009560 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9561 type = ptr->getPointeeType();
9562 kind = FK_FunctionPointer;
9563 } else {
9564 type = type->castAs<BlockPointerType>()->getPointeeType();
9565 kind = FK_BlockPointer;
9566 }
9567 const FunctionType *fnType = type->castAs<FunctionType>();
9568
9569 // Verify that this is a legal result type of a function.
9570 if (DestType->isArrayType() || DestType->isFunctionType()) {
9571 unsigned diagID = diag::err_func_returning_array_function;
9572 if (kind == FK_BlockPointer)
9573 diagID = diag::err_block_returning_array_function;
9574
9575 S.Diag(call->getExprLoc(), diagID)
9576 << DestType->isFunctionType() << DestType;
9577 return ExprError();
9578 }
9579
9580 // Otherwise, go ahead and set DestType as the call's result.
9581 call->setType(DestType.getNonLValueExprType(S.Context));
9582 call->setValueKind(Expr::getValueKindForType(DestType));
9583 assert(call->getObjectKind() == OK_Ordinary);
9584
9585 // Rebuild the function type, replacing the result type with DestType.
9586 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9587 DestType = S.Context.getFunctionType(DestType,
9588 proto->arg_type_begin(),
9589 proto->getNumArgs(),
9590 proto->getExtProtoInfo());
9591 else
9592 DestType = S.Context.getFunctionNoProtoType(DestType,
9593 fnType->getExtInfo());
9594
9595 // Rebuild the appropriate pointer-to-function type.
9596 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009597 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009598 // Nothing to do.
9599 break;
9600
9601 case FK_FunctionPointer:
9602 DestType = S.Context.getPointerType(DestType);
9603 break;
9604
9605 case FK_BlockPointer:
9606 DestType = S.Context.getBlockPointerType(DestType);
9607 break;
9608 }
9609
9610 // Finally, we can recurse.
9611 ExprResult calleeResult = Visit(callee);
9612 if (!calleeResult.isUsable()) return ExprError();
9613 call->setCallee(calleeResult.take());
9614
9615 // Bind a temporary if necessary.
9616 return S.MaybeBindToTemporary(call);
9617}
9618
9619ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009620 // Verify that this is a legal result type of a call.
9621 if (DestType->isArrayType() || DestType->isFunctionType()) {
9622 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9623 << DestType->isFunctionType() << DestType;
9624 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009625 }
9626
John McCall3f4138c2011-07-13 17:56:40 +00009627 // Rewrite the method result type if available.
9628 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9629 assert(method->getResultType() == S.Context.UnknownAnyTy);
9630 method->setResultType(DestType);
9631 }
John McCall2979fe02011-04-12 00:42:48 +00009632
John McCall2d2e8702011-04-11 07:02:50 +00009633 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009634 msg->setType(DestType.getNonReferenceType());
9635 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009636
John McCall2979fe02011-04-12 00:42:48 +00009637 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009638}
9639
9640ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009641 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009642 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009643 assert(ice->getValueKind() == VK_RValue);
9644 assert(ice->getObjectKind() == OK_Ordinary);
9645
John McCall2979fe02011-04-12 00:42:48 +00009646 ice->setType(DestType);
9647
John McCall2d2e8702011-04-11 07:02:50 +00009648 // Rebuild the sub-expression as the pointee (function) type.
9649 DestType = DestType->castAs<PointerType>()->getPointeeType();
9650
9651 ExprResult result = Visit(ice->getSubExpr());
9652 if (!result.isUsable()) return ExprError();
9653
9654 ice->setSubExpr(result.take());
9655 return S.Owned(ice);
9656}
9657
John McCall2979fe02011-04-12 00:42:48 +00009658ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009659 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009660 QualType type = DestType;
9661
9662 // We know how to make this work for certain kinds of decls:
9663
9664 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009665 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009666 // This is true because FunctionDecls must always have function
9667 // type, so we can't be resolving the entire thing at once.
9668 assert(type->isFunctionType());
9669
John McCall4adb38c2011-04-27 00:36:17 +00009670 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9671 if (method->isInstance()) {
9672 valueKind = VK_RValue;
9673 type = S.Context.BoundMemberTy;
9674 }
9675
John McCall2d2e8702011-04-11 07:02:50 +00009676 // Function references aren't l-values in C.
9677 if (!S.getLangOptions().CPlusPlus)
9678 valueKind = VK_RValue;
9679
9680 // - variables
9681 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009682 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9683 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009684 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009685 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9686 << decl << expr->getSourceRange();
9687 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009688 }
9689
9690 // - nothing else
9691 } else {
9692 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9693 << decl << expr->getSourceRange();
9694 return ExprError();
9695 }
9696
John McCall2979fe02011-04-12 00:42:48 +00009697 decl->setType(DestType);
9698 expr->setType(type);
9699 expr->setValueKind(valueKind);
9700 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009701}
9702
John McCall31996342011-04-07 08:22:57 +00009703/// Check a cast of an unknown-any type. We intentionally only
9704/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009705ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9706 Expr *castExpr, CastKind &castKind,
9707 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009708 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009709 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9710 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009711
John McCall39439732011-04-09 22:50:59 +00009712 castExpr = result.take();
9713 VK = castExpr->getValueKind();
9714 castKind = CK_NoOp;
9715
9716 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009717}
9718
9719static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9720 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009721 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009722 while (true) {
9723 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009724 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009725 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009726 diagID = diag::err_uncasted_call_of_unknown_any;
9727 } else {
John McCall31996342011-04-07 08:22:57 +00009728 break;
John McCall2d2e8702011-04-11 07:02:50 +00009729 }
John McCall31996342011-04-07 08:22:57 +00009730 }
9731
John McCall2d2e8702011-04-11 07:02:50 +00009732 SourceLocation loc;
9733 NamedDecl *d;
9734 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9735 loc = ref->getLocation();
9736 d = ref->getDecl();
9737 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9738 loc = mem->getMemberLoc();
9739 d = mem->getMemberDecl();
9740 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9741 diagID = diag::err_uncasted_call_of_unknown_any;
9742 loc = msg->getSelectorLoc();
9743 d = msg->getMethodDecl();
9744 assert(d && "unknown method returning __unknown_any?");
9745 } else {
9746 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9747 << e->getSourceRange();
9748 return ExprError();
9749 }
9750
9751 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009752
9753 // Never recoverable.
9754 return ExprError();
9755}
9756
John McCall36e7fe32010-10-12 00:20:44 +00009757/// Check for operands with placeholder types and complain if found.
9758/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009759ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009760 // Placeholder types are always *exactly* the appropriate builtin type.
9761 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009762
John McCall31996342011-04-07 08:22:57 +00009763 // Overloaded expressions.
9764 if (type == Context.OverloadTy)
9765 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009766 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009767 QualType(),
9768 diag::err_ovl_unresolvable);
9769
John McCall0009fcc2011-04-26 20:42:42 +00009770 // Bound member functions.
9771 if (type == Context.BoundMemberTy) {
9772 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9773 << E->getSourceRange();
9774 return ExprError();
9775 }
9776
John McCall31996342011-04-07 08:22:57 +00009777 // Expressions of unknown type.
9778 if (type == Context.UnknownAnyTy)
9779 return diagnoseUnknownAnyExpr(*this, E);
9780
9781 assert(!type->isPlaceholderType());
9782 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009783}
Richard Trieu2c850c02011-04-21 21:44:26 +00009784
9785bool Sema::CheckCaseExpression(Expr *expr) {
9786 if (expr->isTypeDependent())
9787 return true;
9788 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9789 return expr->getType()->isIntegralOrEnumerationType();
9790 return false;
9791}