blob: dedf7b0d7784052532346c0f2702b536f87555d6 [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"
John McCallde6836a2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000042
David Chisnall9f57c292009-08-17 16:35:33 +000043
Douglas Gregor171c45a2009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor171c45a2009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000058///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000064 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000065 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000068 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith30482bc2011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000084 }
85
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000090 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 return true;
92 }
Douglas Gregorde681d42009-02-24 04:26:15 +000093 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000094
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000107 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
108 if (Message.empty()) {
109 if (!UnknownObjCClass)
110 Diag(Loc, diag::err_unavailable) << D->getDeclName();
111 else
112 Diag(Loc, diag::warn_unavailable_fwdclass_message)
113 << D->getDeclName();
114 }
115 else
116 Diag(Loc, diag::err_unavailable_message)
117 << D->getDeclName() << Message;
118 Diag(D->getLocation(), diag::note_unavailable_here)
119 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000120 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 break;
122 }
123
Anders Carlsson73067a02010-10-22 23:37:08 +0000124 // Warn if this is used but marked unused.
125 if (D->hasAttr<UnusedAttr>())
126 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
127
Douglas Gregor171c45a2009-02-18 21:56:37 +0000128 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000129}
130
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000131/// \brief Retrieve the message suffix that should be added to a
132/// diagnostic complaining about the given function being deleted or
133/// unavailable.
134std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
135 // FIXME: C++0x implicitly-deleted special member functions could be
136 // detected here so that we could improve diagnostics to say, e.g.,
137 // "base class 'A' had a deleted copy constructor".
138 if (FD->isDeleted())
139 return std::string();
140
141 std::string Message;
142 if (FD->getAvailability(&Message))
143 return ": " + Message;
144
145 return std::string();
146}
147
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000148/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000149/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000150/// attribute. It warns if call does not have the sentinel argument.
151///
152void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000153 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000154 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000155 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000157
158 // FIXME: In C++0x, if any of the arguments are parameter pack
159 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000160 int sentinelPos = attr->getSentinel();
161 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000162
Mike Stump87c57ac2009-05-16 07:39:55 +0000163 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
164 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000165 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000166 bool warnNotEnoughArgs = false;
167 int isMethod = 0;
168 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
169 // skip over named parameters.
170 ObjCMethodDecl::param_iterator P, E = MD->param_end();
171 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (P != E || i >= NumArgs);
178 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000179 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000180 // skip over named parameters.
181 ObjCMethodDecl::param_iterator P, E = FD->param_end();
182 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
183 if (nullPos)
184 --nullPos;
185 else
186 ++i;
187 }
188 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000189 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000190 // block or function pointer call.
191 QualType Ty = V->getType();
192 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000193 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000194 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
195 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000196 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
197 unsigned NumArgsInProto = Proto->getNumArgs();
198 unsigned k;
199 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
200 if (nullPos)
201 --nullPos;
202 else
203 ++i;
204 }
205 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
206 }
207 if (Ty->isBlockPointerType())
208 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000209 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000210 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000211 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 return;
213
214 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000215 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000216 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000217 return;
218 }
219 int sentinel = i;
220 while (sentinelPos > 0 && i < NumArgs-1) {
221 --sentinelPos;
222 ++i;
223 }
224 if (sentinelPos > 0) {
225 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000226 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000227 return;
228 }
229 while (i < NumArgs-1) {
230 ++i;
231 ++sentinel;
232 }
233 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000234 if (!sentinelExpr) return;
235 if (sentinelExpr->isTypeDependent()) return;
236 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000237
238 // nullptr_t is always treated as null.
239 if (sentinelExpr->getType()->isNullPtrType()) return;
240
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000241 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000242 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
243 Expr::NPC_ValueDependentIsNull))
244 return;
245
246 // Unfortunately, __null has type 'int'.
247 if (isa<GNUNullExpr>(sentinelExpr)) return;
248
249 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
250 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000251}
252
Douglas Gregor87f95b02009-02-26 21:00:50 +0000253SourceRange Sema::getExprRange(ExprTy *E) const {
254 Expr *Ex = (Expr *)E;
255 return Ex? Ex->getSourceRange() : SourceRange();
256}
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258//===----------------------------------------------------------------------===//
259// Standard Promotions and Conversions
260//===----------------------------------------------------------------------===//
261
Chris Lattner513165e2008-07-25 21:10:04 +0000262/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000263ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000264 QualType Ty = E->getType();
265 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
266
Chris Lattner513165e2008-07-25 21:10:04 +0000267 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000268 E = ImpCastExprToType(E, Context.getPointerType(Ty),
269 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000270 else if (Ty->isArrayType()) {
271 // In C90 mode, arrays only promote to pointers if the array expression is
272 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
273 // type 'array of type' is converted to an expression that has type 'pointer
274 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
275 // that has type 'array of type' ...". The relevant change is "an lvalue"
276 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000277 //
278 // C++ 4.2p1:
279 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
280 // T" can be converted to an rvalue of type "pointer to T".
281 //
John McCall086a4642010-11-24 05:12:34 +0000282 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000283 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
284 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000285 }
John Wiegley01296292011-04-08 18:41:53 +0000286 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000287}
288
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000289static void CheckForNullPointerDereference(Sema &S, Expr *E) {
290 // Check to see if we are dereferencing a null pointer. If so,
291 // and if not volatile-qualified, this is undefined behavior that the
292 // optimizer will delete, so warn about it. People sometimes try to use this
293 // to get a deterministic trap and are surprised by clang's behavior. This
294 // only handles the pattern "*null", which is a very syntactic check.
295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
296 if (UO->getOpcode() == UO_Deref &&
297 UO->getSubExpr()->IgnoreParenCasts()->
298 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
299 !UO->getType().isVolatileQualified()) {
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::warn_indirection_through_null)
302 << UO->getSubExpr()->getSourceRange());
303 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
304 S.PDiag(diag::note_indirection_through_null));
305 }
306}
307
John Wiegley01296292011-04-08 18:41:53 +0000308ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000309 // C++ [conv.lval]p1:
310 // A glvalue of a non-function, non-array type T can be
311 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000312 if (!E->isGLValue()) return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000313 QualType T = E->getType();
314 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000315
John McCall27584242010-12-06 20:48:59 +0000316 // Create a load out of an ObjCProperty l-value, if necessary.
317 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000318 ExprResult Res = ConvertPropertyForRValue(E);
319 if (Res.isInvalid())
320 return Owned(E);
321 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000322 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000323 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000324 }
John McCall27584242010-12-06 20:48:59 +0000325
326 // We don't want to throw lvalue-to-rvalue casts on top of
327 // expressions of certain types in C++.
328 if (getLangOptions().CPlusPlus &&
329 (E->getType() == Context.OverloadTy ||
330 T->isDependentType() ||
331 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000332 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000333
334 // The C standard is actually really unclear on this point, and
335 // DR106 tells us what the result should be but not why. It's
336 // generally best to say that void types just doesn't undergo
337 // lvalue-to-rvalue at all. Note that expressions of unqualified
338 // 'void' type are never l-values, but qualified void can be.
339 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000340 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000341
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000342 CheckForNullPointerDereference(*this, E);
343
John McCall27584242010-12-06 20:48:59 +0000344 // C++ [conv.lval]p1:
345 // [...] If T is a non-class type, the type of the prvalue is the
346 // cv-unqualified version of T. Otherwise, the type of the
347 // rvalue is T.
348 //
349 // C99 6.3.2.1p2:
350 // If the lvalue has qualified type, the value has the unqualified
351 // version of the type of the lvalue; otherwise, the value has the
352 // type of the lvalue.
353 if (T.hasQualifiers())
354 T = T.getUnqualifiedType();
355
Ted Kremenekdf26df72011-03-01 18:41:00 +0000356 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000357
John Wiegley01296292011-04-08 18:41:53 +0000358 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
359 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000360}
361
John Wiegley01296292011-04-08 18:41:53 +0000362ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
363 ExprResult Res = DefaultFunctionArrayConversion(E);
364 if (Res.isInvalid())
365 return ExprError();
366 Res = DefaultLvalueConversion(Res.take());
367 if (Res.isInvalid())
368 return ExprError();
369 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000370}
371
372
Chris Lattner513165e2008-07-25 21:10:04 +0000373/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000374/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000375/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000376/// apply if the array is an argument to the sizeof or address (&) operators.
377/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000378ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000379 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000380 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
381 if (Res.isInvalid())
382 return Owned(E);
383 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000384
385 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000386 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000387
388 // Try to perform integral promotions if the object has a theoretically
389 // promotable type.
390 if (Ty->isIntegralOrUnscopedEnumerationType()) {
391 // C99 6.3.1.1p2:
392 //
393 // The following may be used in an expression wherever an int or
394 // unsigned int may be used:
395 // - an object or expression with an integer type whose integer
396 // conversion rank is less than or equal to the rank of int
397 // and unsigned int.
398 // - A bit-field of type _Bool, int, signed int, or unsigned int.
399 //
400 // If an int can represent all values of the original type, the
401 // value is converted to an int; otherwise, it is converted to an
402 // unsigned int. These are called the integer promotions. All
403 // other types are unchanged by the integer promotions.
404
405 QualType PTy = Context.isPromotableBitField(E);
406 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000407 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
408 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000409 }
410 if (Ty->isPromotableIntegerType()) {
411 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000412 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
413 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000414 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000415 }
John Wiegley01296292011-04-08 18:41:53 +0000416 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000417}
418
Chris Lattner2ce500f2008-07-25 22:25:12 +0000419/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000420/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000421/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000422ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
423 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000424 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000425
John Wiegley01296292011-04-08 18:41:53 +0000426 ExprResult Res = UsualUnaryConversions(E);
427 if (Res.isInvalid())
428 return Owned(E);
429 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000430
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000432 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000433 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
434
435 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000436}
437
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000438/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
439/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000440/// interfaces passed by value.
441ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000442 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000443 ExprResult ExprRes = CheckPlaceholderExpr(E);
444 if (ExprRes.isInvalid())
445 return ExprError();
446
447 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000448 if (ExprRes.isInvalid())
449 return ExprError();
450 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000451
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000452 // __builtin_va_start takes the second argument as a "varargs" argument, but
453 // it doesn't actually do anything with it. It doesn't need to be non-pod
454 // etc.
455 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000456 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000457
Douglas Gregor347e0f22011-05-21 19:26:31 +0000458 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000459 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000460 DiagRuntimeBehavior(E->getLocStart(), 0,
461 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
462 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000463 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000464
John McCall31168b02011-06-15 23:02:42 +0000465 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000466 // C++0x [expr.call]p7:
467 // Passing a potentially-evaluated argument of class type (Clause 9)
468 // having a non-trivial copy constructor, a non-trivial move constructor,
469 // or a non-trivial destructor, with no corresponding parameter,
470 // is conditionally-supported with implementation-defined semantics.
471 bool TrivialEnough = false;
472 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
473 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
474 if (Record->hasTrivialCopyConstructor() &&
475 Record->hasTrivialMoveConstructor() &&
476 Record->hasTrivialDestructor())
477 TrivialEnough = true;
478 }
479 }
John McCall31168b02011-06-15 23:02:42 +0000480
481 if (!TrivialEnough &&
482 getLangOptions().ObjCAutoRefCount &&
483 E->getType()->isObjCLifetimeType())
484 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000485
486 if (TrivialEnough) {
487 // Nothing to diagnose. This is okay.
488 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000489 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000490 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000491 << CT)) {
492 // Turn this into a trap.
493 CXXScopeSpec SS;
494 UnqualifiedId Name;
495 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
496 E->getLocStart());
497 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
498 if (TrapFn.isInvalid())
499 return ExprError();
500
501 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
502 MultiExprArg(), E->getLocEnd());
503 if (Call.isInvalid())
504 return ExprError();
505
506 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
507 Call.get(), E);
508 if (Comma.isInvalid())
509 return ExprError();
510
511 E = Comma.get();
512 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000513 }
514
John Wiegley01296292011-04-08 18:41:53 +0000515 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000516}
517
Chris Lattner513165e2008-07-25 21:10:04 +0000518/// UsualArithmeticConversions - Performs various conversions that are common to
519/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000520/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000521/// responsible for emitting appropriate error diagnostics.
522/// FIXME: verify the conversion rules for "complex int" are consistent with
523/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000524QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000525 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000526 if (!isCompAssign) {
527 lhsExpr = UsualUnaryConversions(lhsExpr.take());
528 if (lhsExpr.isInvalid())
529 return QualType();
530 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000531
John Wiegley01296292011-04-08 18:41:53 +0000532 rhsExpr = UsualUnaryConversions(rhsExpr.take());
533 if (rhsExpr.isInvalid())
534 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000535
Mike Stump11289f42009-09-09 15:08:12 +0000536 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000537 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000538 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000539 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000540 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000541 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000542
543 // If both types are identical, no conversion is needed.
544 if (lhs == rhs)
545 return lhs;
546
547 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
548 // The caller can deal with this (e.g. pointer + int).
549 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
550 return lhs;
551
John McCalld005ac92010-11-13 08:17:45 +0000552 // Apply unary and bitfield promotions to the LHS's type.
553 QualType lhs_unpromoted = lhs;
554 if (lhs->isPromotableIntegerType())
555 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000556 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000557 if (!LHSBitfieldPromoteTy.isNull())
558 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000559 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000560 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000561
John McCalld005ac92010-11-13 08:17:45 +0000562 // If both types are identical, no conversion is needed.
563 if (lhs == rhs)
564 return lhs;
565
566 // At this point, we have two different arithmetic types.
567
568 // Handle complex types first (C99 6.3.1.8p1).
569 bool LHSComplexFloat = lhs->isComplexType();
570 bool RHSComplexFloat = rhs->isComplexType();
571 if (LHSComplexFloat || RHSComplexFloat) {
572 // if we have an integer operand, the result is the complex type.
573
John McCallc5e62b42010-11-13 09:02:35 +0000574 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
575 if (rhs->isIntegerType()) {
576 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000577 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
578 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000579 } else {
580 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000581 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000582 }
John McCalld005ac92010-11-13 08:17:45 +0000583 return lhs;
584 }
585
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
587 if (!isCompAssign) {
588 // int -> float -> _Complex float
589 if (lhs->isIntegerType()) {
590 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000591 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
592 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000593 } else {
594 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000595 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000596 }
597 }
John McCalld005ac92010-11-13 08:17:45 +0000598 return rhs;
599 }
600
601 // This handles complex/complex, complex/float, or float/complex.
602 // When both operands are complex, the shorter operand is converted to the
603 // type of the longer, and that is the type of the result. This corresponds
604 // to what is done when combining two real floating-point operands.
605 // The fun begins when size promotion occur across type domains.
606 // From H&S 6.3.4: When one operand is complex and the other is a real
607 // floating-point type, the less precise type is converted, within it's
608 // real or complex domain, to the precision of the other type. For example,
609 // when combining a "long double" with a "double _Complex", the
610 // "double _Complex" is promoted to "long double _Complex".
611 int order = Context.getFloatingTypeOrder(lhs, rhs);
612
613 // If both are complex, just cast to the more precise type.
614 if (LHSComplexFloat && RHSComplexFloat) {
615 if (order > 0) {
616 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000618 return lhs;
619
620 } else if (order < 0) {
621 // _Complex float -> _Complex double
622 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626 return lhs;
627 }
628
629 // If just the LHS is complex, the RHS needs to be converted,
630 // and the LHS might need to be promoted.
631 if (LHSComplexFloat) {
632 if (order > 0) { // LHS is wider
633 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000634 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000635 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
636 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000637 return lhs;
638 }
639
640 // RHS is at least as wide. Find its corresponding complex type.
641 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
642
643 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000644 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645
646 // _Complex float -> _Complex double
647 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000648 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000649
650 return result;
651 }
652
653 // Just the RHS is complex, so the LHS needs to be converted
654 // and the RHS might need to be promoted.
655 assert(RHSComplexFloat);
656
657 if (order < 0) { // RHS is wider
658 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000659 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000660 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000661 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
662 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000663 }
John McCalld005ac92010-11-13 08:17:45 +0000664 return rhs;
665 }
666
667 // LHS is at least as wide. Find its corresponding complex type.
668 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
669
670 // double -> _Complex double
671 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000672 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000673
674 // _Complex float -> _Complex double
675 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000676 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000677
678 return result;
679 }
680
681 // Now handle "real" floating types (i.e. float, double, long double).
682 bool LHSFloat = lhs->isRealFloatingType();
683 bool RHSFloat = rhs->isRealFloatingType();
684 if (LHSFloat || RHSFloat) {
685 // If we have two real floating types, convert the smaller operand
686 // to the bigger result.
687 if (LHSFloat && RHSFloat) {
688 int order = Context.getFloatingTypeOrder(lhs, rhs);
689 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000690 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000691 return lhs;
692 }
693
694 assert(order < 0 && "illegal float comparison");
695 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000697 return rhs;
698 }
699
700 // If we have an integer operand, the result is the real floating type.
701 if (LHSFloat) {
702 if (rhs->isIntegerType()) {
703 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000704 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000705 return lhs;
706 }
707
708 // Convert both sides to the appropriate complex float.
709 assert(rhs->isComplexIntegerType());
710 QualType result = Context.getComplexType(lhs);
711
712 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000713 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000714
715 // float -> _Complex float
716 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000717 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000718
719 return result;
720 }
721
722 assert(RHSFloat);
723 if (lhs->isIntegerType()) {
724 // Convert lhs to the rhs floating point type.
725 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000726 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000727 return rhs;
728 }
729
730 // Convert both sides to the appropriate complex float.
731 assert(lhs->isComplexIntegerType());
732 QualType result = Context.getComplexType(rhs);
733
734 // _Complex int -> _Complex float
735 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000736 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000737
738 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000740
741 return result;
742 }
743
744 // Handle GCC complex int extension.
745 // FIXME: if the operands are (int, _Complex long), we currently
746 // don't promote the complex. Also, signedness?
747 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
748 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
749 if (lhsComplexInt && rhsComplexInt) {
750 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
751 rhsComplexInt->getElementType());
752 assert(order && "inequal types with equal element ordering");
753 if (order > 0) {
754 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000755 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000756 return lhs;
757 }
758
759 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000760 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000761 return rhs;
762 } else if (lhsComplexInt) {
763 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000764 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000765 return lhs;
766 } else if (rhsComplexInt) {
767 // int -> _Complex int
768 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000769 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000770 return rhs;
771 }
772
773 // Finally, we have two differing integer types.
774 // The rules for this case are in C99 6.3.1.8
775 int compare = Context.getIntegerTypeOrder(lhs, rhs);
776 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
777 rhsSigned = rhs->hasSignedIntegerRepresentation();
778 if (lhsSigned == rhsSigned) {
779 // Same signedness; use the higher-ranked type
780 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000781 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000782 return lhs;
783 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000784 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000785 return rhs;
786 } else if (compare != (lhsSigned ? 1 : -1)) {
787 // The unsigned type has greater than or equal rank to the
788 // signed type, so use the unsigned type
789 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000790 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000791 return lhs;
792 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000793 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000794 return rhs;
795 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
796 // The two types are different widths; if we are here, that
797 // means the signed type is larger than the unsigned type, so
798 // use the signed type.
799 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000800 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000801 return lhs;
802 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000803 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000804 return rhs;
805 } else {
806 // The signed type is higher-ranked than the unsigned type,
807 // but isn't actually any bigger (like unsigned int and long
808 // on most 32-bit systems). Use the unsigned type corresponding
809 // to the signed type.
810 QualType result =
811 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000812 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000813 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000814 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000815 return result;
816 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000817}
818
Chris Lattner513165e2008-07-25 21:10:04 +0000819//===----------------------------------------------------------------------===//
820// Semantic Analysis for various Expression Types
821//===----------------------------------------------------------------------===//
822
823
Peter Collingbourne91147592011-04-15 00:35:48 +0000824ExprResult
825Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
826 SourceLocation DefaultLoc,
827 SourceLocation RParenLoc,
828 Expr *ControllingExpr,
829 MultiTypeArg types,
830 MultiExprArg exprs) {
831 unsigned NumAssocs = types.size();
832 assert(NumAssocs == exprs.size());
833
834 ParsedType *ParsedTypes = types.release();
835 Expr **Exprs = exprs.release();
836
837 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
838 for (unsigned i = 0; i < NumAssocs; ++i) {
839 if (ParsedTypes[i])
840 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
841 else
842 Types[i] = 0;
843 }
844
845 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
846 ControllingExpr, Types, Exprs,
847 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000848 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000849 return ER;
850}
851
852ExprResult
853Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
854 SourceLocation DefaultLoc,
855 SourceLocation RParenLoc,
856 Expr *ControllingExpr,
857 TypeSourceInfo **Types,
858 Expr **Exprs,
859 unsigned NumAssocs) {
860 bool TypeErrorFound = false,
861 IsResultDependent = ControllingExpr->isTypeDependent(),
862 ContainsUnexpandedParameterPack
863 = ControllingExpr->containsUnexpandedParameterPack();
864
865 for (unsigned i = 0; i < NumAssocs; ++i) {
866 if (Exprs[i]->containsUnexpandedParameterPack())
867 ContainsUnexpandedParameterPack = true;
868
869 if (Types[i]) {
870 if (Types[i]->getType()->containsUnexpandedParameterPack())
871 ContainsUnexpandedParameterPack = true;
872
873 if (Types[i]->getType()->isDependentType()) {
874 IsResultDependent = true;
875 } else {
876 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
877 // complete object type other than a variably modified type."
878 unsigned D = 0;
879 if (Types[i]->getType()->isIncompleteType())
880 D = diag::err_assoc_type_incomplete;
881 else if (!Types[i]->getType()->isObjectType())
882 D = diag::err_assoc_type_nonobject;
883 else if (Types[i]->getType()->isVariablyModifiedType())
884 D = diag::err_assoc_type_variably_modified;
885
886 if (D != 0) {
887 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
888 << Types[i]->getTypeLoc().getSourceRange()
889 << Types[i]->getType();
890 TypeErrorFound = true;
891 }
892
893 // C1X 6.5.1.1p2 "No two generic associations in the same generic
894 // selection shall specify compatible types."
895 for (unsigned j = i+1; j < NumAssocs; ++j)
896 if (Types[j] && !Types[j]->getType()->isDependentType() &&
897 Context.typesAreCompatible(Types[i]->getType(),
898 Types[j]->getType())) {
899 Diag(Types[j]->getTypeLoc().getBeginLoc(),
900 diag::err_assoc_compatible_types)
901 << Types[j]->getTypeLoc().getSourceRange()
902 << Types[j]->getType()
903 << Types[i]->getType();
904 Diag(Types[i]->getTypeLoc().getBeginLoc(),
905 diag::note_compat_assoc)
906 << Types[i]->getTypeLoc().getSourceRange()
907 << Types[i]->getType();
908 TypeErrorFound = true;
909 }
910 }
911 }
912 }
913 if (TypeErrorFound)
914 return ExprError();
915
916 // If we determined that the generic selection is result-dependent, don't
917 // try to compute the result expression.
918 if (IsResultDependent)
919 return Owned(new (Context) GenericSelectionExpr(
920 Context, KeyLoc, ControllingExpr,
921 Types, Exprs, NumAssocs, DefaultLoc,
922 RParenLoc, ContainsUnexpandedParameterPack));
923
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000925 unsigned DefaultIndex = -1U;
926 for (unsigned i = 0; i < NumAssocs; ++i) {
927 if (!Types[i])
928 DefaultIndex = i;
929 else if (Context.typesAreCompatible(ControllingExpr->getType(),
930 Types[i]->getType()))
931 CompatIndices.push_back(i);
932 }
933
934 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
935 // type compatible with at most one of the types named in its generic
936 // association list."
937 if (CompatIndices.size() > 1) {
938 // We strip parens here because the controlling expression is typically
939 // parenthesized in macro definitions.
940 ControllingExpr = ControllingExpr->IgnoreParens();
941 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
942 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
943 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000944 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000945 E = CompatIndices.end(); I != E; ++I) {
946 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
947 diag::note_compat_assoc)
948 << Types[*I]->getTypeLoc().getSourceRange()
949 << Types[*I]->getType();
950 }
951 return ExprError();
952 }
953
954 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
955 // its controlling expression shall have type compatible with exactly one of
956 // the types named in its generic association list."
957 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
958 // We strip parens here because the controlling expression is typically
959 // parenthesized in macro definitions.
960 ControllingExpr = ControllingExpr->IgnoreParens();
961 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
962 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
963 return ExprError();
964 }
965
966 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
967 // type name that is compatible with the type of the controlling expression,
968 // then the result expression of the generic selection is the expression
969 // in that generic association. Otherwise, the result expression of the
970 // generic selection is the expression in the default generic association."
971 unsigned ResultIndex =
972 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
973
974 return Owned(new (Context) GenericSelectionExpr(
975 Context, KeyLoc, ControllingExpr,
976 Types, Exprs, NumAssocs, DefaultLoc,
977 RParenLoc, ContainsUnexpandedParameterPack,
978 ResultIndex));
979}
980
Steve Naroff83895f72007-09-16 03:34:24 +0000981/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000982/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
983/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
984/// multiple tokens. However, the common case is that StringToks points to one
985/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000986///
John McCalldadc5752010-08-24 06:29:42 +0000987ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000988Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000989 assert(NumStringToks && "Must have at least one string!");
990
Chris Lattner8a24e582009-01-16 18:51:42 +0000991 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000992 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000993 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000994
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000995 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000996 for (unsigned i = 0; i != NumStringToks; ++i)
997 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000998
Chris Lattner36fc8792008-02-11 00:02:17 +0000999 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001000 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001001 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001002 else if (Literal.isUTF16())
1003 StrTy = Context.Char16Ty;
1004 else if (Literal.isUTF32())
1005 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001006 else if (Literal.Pascal)
1007 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001008
Douglas Gregorfb65e592011-07-27 05:40:30 +00001009 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1010 if (Literal.isWide())
1011 Kind = StringLiteral::Wide;
1012 else if (Literal.isUTF8())
1013 Kind = StringLiteral::UTF8;
1014 else if (Literal.isUTF16())
1015 Kind = StringLiteral::UTF16;
1016 else if (Literal.isUTF32())
1017 Kind = StringLiteral::UTF32;
1018
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001019 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001020 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001021 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001022
Chris Lattner36fc8792008-02-11 00:02:17 +00001023 // Get an array type for the string, according to C99 6.4.5. This includes
1024 // the nul terminator character as well as the string length for pascal
1025 // strings.
1026 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001027 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001028 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001029
Chris Lattner5b183d82006-11-10 05:03:26 +00001030 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001031 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001032 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001033 &StringTokLocs[0],
1034 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001035}
1036
John McCallc63de662011-02-02 13:00:07 +00001037enum CaptureResult {
1038 /// No capture is required.
1039 CR_NoCapture,
1040
1041 /// A capture is required.
1042 CR_Capture,
1043
John McCall351762c2011-02-07 10:33:21 +00001044 /// A by-ref capture is required.
1045 CR_CaptureByRef,
1046
John McCallc63de662011-02-02 13:00:07 +00001047 /// An error occurred when trying to capture the given variable.
1048 CR_Error
1049};
1050
1051/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001052///
John McCallc63de662011-02-02 13:00:07 +00001053/// \param var - the variable referenced
1054/// \param DC - the context which we couldn't capture through
1055static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001056diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001057 VarDecl *var, DeclContext *DC) {
1058 switch (S.ExprEvalContexts.back().Context) {
1059 case Sema::Unevaluated:
1060 // The argument will never be evaluated, so don't complain.
1061 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCallc63de662011-02-02 13:00:07 +00001063 case Sema::PotentiallyEvaluated:
1064 case Sema::PotentiallyEvaluatedIfUsed:
1065 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001066
John McCallc63de662011-02-02 13:00:07 +00001067 case Sema::PotentiallyPotentiallyEvaluated:
1068 // FIXME: delay these!
1069 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCallc63de662011-02-02 13:00:07 +00001072 // Don't diagnose about capture if we're not actually in code right
1073 // now; in general, there are more appropriate places that will
1074 // diagnose this.
1075 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1076
John McCall92d627e2011-03-22 23:15:50 +00001077 // Certain madnesses can happen with parameter declarations, which
1078 // we want to ignore.
1079 if (isa<ParmVarDecl>(var)) {
1080 // - If the parameter still belongs to the translation unit, then
1081 // we're actually just using one parameter in the declaration of
1082 // the next. This is useful in e.g. VLAs.
1083 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1084 return CR_NoCapture;
1085
1086 // - This particular madness can happen in ill-formed default
1087 // arguments; claim it's okay and let downstream code handle it.
1088 if (S.CurContext == var->getDeclContext()->getParent())
1089 return CR_NoCapture;
1090 }
John McCallc63de662011-02-02 13:00:07 +00001091
1092 DeclarationName functionName;
1093 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1094 functionName = fn->getDeclName();
1095 // FIXME: variable from enclosing block that we couldn't capture from!
1096
1097 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1098 << var->getIdentifier() << functionName;
1099 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1100 << var->getIdentifier();
1101
1102 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001103}
1104
John McCall351762c2011-02-07 10:33:21 +00001105/// There is a well-formed capture at a particular scope level;
1106/// propagate it through all the nested blocks.
1107static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1108 const BlockDecl::Capture &capture) {
1109 VarDecl *var = capture.getVariable();
1110
1111 // Update all the inner blocks with the capture information.
1112 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1113 i != e; ++i) {
1114 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1115 innerBlock->Captures.push_back(
1116 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1117 /*nested*/ true, capture.getCopyExpr()));
1118 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1119 }
1120
1121 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1122}
1123
1124/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001125/// given value in the current context requires a variable capture.
1126///
1127/// This also keeps the captures set in the BlockScopeInfo records
1128/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001129static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001130 ValueDecl *value) {
1131 // Only variables ever require capture.
1132 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001133 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001134
1135 // Fast path: variables from the current context never require capture.
1136 DeclContext *DC = S.CurContext;
1137 if (var->getDeclContext() == DC) return CR_NoCapture;
1138
1139 // Only variables with local storage require capture.
1140 // FIXME: What about 'const' variables in C++?
1141 if (!var->hasLocalStorage()) return CR_NoCapture;
1142
1143 // Otherwise, we need to capture.
1144
1145 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001146 do {
1147 // Only blocks (and eventually C++0x closures) can capture; other
1148 // scopes don't work.
1149 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001150 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001151
1152 BlockScopeInfo *blockScope =
1153 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1154 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1155
John McCall351762c2011-02-07 10:33:21 +00001156 // Check whether we've already captured it in this block. If so,
1157 // we're done.
1158 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1159 return propagateCapture(S, functionScopesIndex,
1160 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001161
1162 functionScopesIndex--;
1163 DC = cast<BlockDecl>(DC)->getDeclContext();
1164 } while (var->getDeclContext() != DC);
1165
John McCall351762c2011-02-07 10:33:21 +00001166 // Okay, we descended all the way to the block that defines the variable.
1167 // Actually try to capture it.
1168 QualType type = var->getType();
1169
1170 // Prohibit variably-modified types.
1171 if (type->isVariablyModifiedType()) {
1172 S.Diag(loc, diag::err_ref_vm_type);
1173 S.Diag(var->getLocation(), diag::note_declared_at);
1174 return CR_Error;
1175 }
1176
1177 // Prohibit arrays, even in __block variables, but not references to
1178 // them.
1179 if (type->isArrayType()) {
1180 S.Diag(loc, diag::err_ref_array_type);
1181 S.Diag(var->getLocation(), diag::note_declared_at);
1182 return CR_Error;
1183 }
1184
1185 S.MarkDeclarationReferenced(loc, var);
1186
1187 // The BlocksAttr indicates the variable is bound by-reference.
1188 bool byRef = var->hasAttr<BlocksAttr>();
1189
1190 // Build a copy expression.
1191 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001192 const RecordType *rtype;
1193 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1194 (rtype = type->getAs<RecordType>())) {
1195
1196 // The capture logic needs the destructor, so make sure we mark it.
1197 // Usually this is unnecessary because most local variables have
1198 // their destructors marked at declaration time, but parameters are
1199 // an exception because it's technically only the call site that
1200 // actually requires the destructor.
1201 if (isa<ParmVarDecl>(var))
1202 S.FinalizeVarWithDestructor(var, rtype);
1203
John McCall351762c2011-02-07 10:33:21 +00001204 // According to the blocks spec, the capture of a variable from
1205 // the stack requires a const copy constructor. This is not true
1206 // of the copy/move done to move a __block variable to the heap.
1207 type.addConst();
1208
1209 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1210 ExprResult result =
1211 S.PerformCopyInitialization(
1212 InitializedEntity::InitializeBlock(var->getLocation(),
1213 type, false),
1214 loc, S.Owned(declRef));
1215
1216 // Build a full-expression copy expression if initialization
1217 // succeeded and used a non-trivial constructor. Recover from
1218 // errors by pretending that the copy isn't necessary.
1219 if (!result.isInvalid() &&
1220 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1221 result = S.MaybeCreateExprWithCleanups(result);
1222 copyExpr = result.take();
1223 }
1224 }
1225
1226 // We're currently at the declarer; go back to the closure.
1227 functionScopesIndex++;
1228 BlockScopeInfo *blockScope =
1229 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1230
1231 // Build a valid capture in this scope.
1232 blockScope->Captures.push_back(
1233 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1234 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1235
1236 // Propagate that to inner captures if necessary.
1237 return propagateCapture(S, functionScopesIndex,
1238 blockScope->Captures.back());
1239}
1240
1241static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1242 const DeclarationNameInfo &NameInfo,
1243 bool byRef) {
1244 assert(isa<VarDecl>(vd) && "capturing non-variable");
1245
1246 VarDecl *var = cast<VarDecl>(vd);
1247 assert(var->hasLocalStorage() && "capturing non-local");
1248 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1249
1250 QualType exprType = var->getType().getNonReferenceType();
1251
1252 BlockDeclRefExpr *BDRE;
1253 if (!byRef) {
1254 // The variable will be bound by copy; make it const within the
1255 // closure, but record that this was done in the expression.
1256 bool constAdded = !exprType.isConstQualified();
1257 exprType.addConst();
1258
1259 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1260 NameInfo.getLoc(), false,
1261 constAdded);
1262 } else {
1263 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1264 NameInfo.getLoc(), true);
1265 }
1266
1267 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001268}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001269
John McCalldadc5752010-08-24 06:29:42 +00001270ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001271Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001272 SourceLocation Loc,
1273 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001274 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001275 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001276}
1277
John McCallf4cd4f92011-02-09 01:13:10 +00001278/// BuildDeclRefExpr - Build an expression that references a
1279/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001280ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001281Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001282 const DeclarationNameInfo &NameInfo,
1283 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001284 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001285
John McCall086a4642010-11-24 05:12:34 +00001286 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001287 SS? SS->getWithLocInContext(Context)
1288 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001289 D, NameInfo, Ty, VK);
1290
1291 // Just in case we're building an illegal pointer-to-member.
1292 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1293 E->setObjectKind(OK_BitField);
1294
1295 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001296}
1297
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001298/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001299/// possibly a list of template arguments.
1300///
1301/// If this produces template arguments, it is permitted to call
1302/// DecomposeTemplateName.
1303///
1304/// This actually loses a lot of source location information for
1305/// non-standard name kinds; we should consider preserving that in
1306/// some way.
Douglas Gregor5476205b2011-06-23 00:49:38 +00001307void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1308 TemplateArgumentListInfo &Buffer,
1309 DeclarationNameInfo &NameInfo,
1310 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001311 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1312 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1313 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1314
Douglas Gregor5476205b2011-06-23 00:49:38 +00001315 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001316 Id.TemplateId->getTemplateArgs(),
1317 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001318 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001319 TemplateArgsPtr.release();
1320
John McCall3e56fd42010-08-23 07:28:44 +00001321 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001322 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001323 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001324 TemplateArgs = &Buffer;
1325 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001326 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001327 TemplateArgs = 0;
1328 }
1329}
1330
John McCalld681c392009-12-16 08:11:27 +00001331/// Diagnose an empty lookup.
1332///
1333/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001334bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1335 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001336 DeclarationName Name = R.getLookupName();
1337
John McCalld681c392009-12-16 08:11:27 +00001338 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001339 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001340 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1341 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001342 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001343 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001344 diagnostic_suggest = diag::err_undeclared_use_suggest;
1345 }
John McCalld681c392009-12-16 08:11:27 +00001346
Douglas Gregor598b08f2009-12-31 05:20:13 +00001347 // If the original lookup was an unqualified lookup, fake an
1348 // unqualified lookup. This is useful when (for example) the
1349 // original lookup would not have found something because it was a
1350 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001351 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001352 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001353 if (isa<CXXRecordDecl>(DC)) {
1354 LookupQualifiedName(R, DC);
1355
1356 if (!R.empty()) {
1357 // Don't give errors about ambiguities in this lookup.
1358 R.suppressDiagnostics();
1359
1360 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1361 bool isInstance = CurMethod &&
1362 CurMethod->isInstance() &&
1363 DC == CurMethod->getParent();
1364
1365 // Give a code modification hint to insert 'this->'.
1366 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1367 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001368 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001369 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1370 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001371 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001372 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001373 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001374 Diag(R.getNameLoc(), diagnostic) << Name
1375 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1376 QualType DepThisType = DepMethod->getThisType(Context);
1377 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1378 R.getNameLoc(), DepThisType, false);
1379 TemplateArgumentListInfo TList;
1380 if (ULE->hasExplicitTemplateArgs())
1381 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001382
Douglas Gregore16af532011-02-28 18:50:33 +00001383 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001384 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001385 CXXDependentScopeMemberExpr *DepExpr =
1386 CXXDependentScopeMemberExpr::Create(
1387 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001388 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001389 R.getLookupNameInfo(), &TList);
1390 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001391 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001392 // FIXME: we should be able to handle this case too. It is correct
1393 // to add this-> here. This is a workaround for PR7947.
1394 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001395 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001396 } else {
John McCalld681c392009-12-16 08:11:27 +00001397 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001398 }
John McCalld681c392009-12-16 08:11:27 +00001399
1400 // Do we really want to note all of these?
1401 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1402 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1403
1404 // Tell the callee to try to recover.
1405 return false;
1406 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001407
1408 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001409 }
1410 }
1411
Douglas Gregor598b08f2009-12-31 05:20:13 +00001412 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001413 TypoCorrection Corrected;
1414 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1415 S, &SS, NULL, false, CTC))) {
1416 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1417 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1418 R.setLookupName(Corrected.getCorrection());
1419
Hans Wennborg38198de2011-07-12 08:45:31 +00001420 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 R.addDecl(ND);
1422 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001423 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001424 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1425 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001426 else
1427 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001428 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001429 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001430 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1431 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001432 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001433 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001434
1435 // Tell the callee to try to recover.
1436 return false;
1437 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001438
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001439 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001440 // FIXME: If we ended up with a typo for a type name or
1441 // Objective-C class name, we're in trouble because the parser
1442 // is in the wrong place to recover. Suggest the typo
1443 // correction, but don't make it a fix-it since we're not going
1444 // to recover well anyway.
1445 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001446 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001447 else
1448 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001449 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001450 << SS.getRange();
1451
1452 // Don't try to recover; it won't work.
1453 return true;
1454 }
1455 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001456 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001457 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001458 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001459 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001460 else
Douglas Gregor25363982010-01-01 00:15:04 +00001461 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001462 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001463 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001464 return true;
1465 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001466 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001467 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001468
1469 // Emit a special diagnostic for failed member lookups.
1470 // FIXME: computing the declaration context might fail here (?)
1471 if (!SS.isEmpty()) {
1472 Diag(R.getNameLoc(), diag::err_no_member)
1473 << Name << computeDeclContext(SS, false)
1474 << SS.getRange();
1475 return true;
1476 }
1477
John McCalld681c392009-12-16 08:11:27 +00001478 // Give up, we can't recover.
1479 Diag(R.getNameLoc(), diagnostic) << Name;
1480 return true;
1481}
1482
Douglas Gregor05fcf842010-11-02 20:36:02 +00001483ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1484 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001485 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1486 if (!IDecl)
1487 return 0;
1488 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1489 if (!ClassImpDecl)
1490 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001491 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001492 if (!property)
1493 return 0;
1494 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001495 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1496 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001497 return 0;
1498 return property;
1499}
1500
Douglas Gregor05fcf842010-11-02 20:36:02 +00001501bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1502 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1503 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1504 if (!IDecl)
1505 return false;
1506 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1507 if (!ClassImpDecl)
1508 return false;
1509 if (ObjCPropertyImplDecl *PIDecl
1510 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1511 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1512 PIDecl->getPropertyIvarDecl())
1513 return false;
1514
1515 return true;
1516}
1517
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001518ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1519 IdentifierInfo *II,
1520 SourceLocation NameLoc) {
1521 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001522 bool LookForIvars;
1523 if (Lookup.empty())
1524 LookForIvars = true;
1525 else if (CurMeth->isClassMethod())
1526 LookForIvars = false;
1527 else
1528 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001529 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1530 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001531 if (!LookForIvars)
1532 return 0;
1533
Fariborz Jahanian18722982010-07-17 00:59:30 +00001534 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1535 if (!IDecl)
1536 return 0;
1537 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001538 if (!ClassImpDecl)
1539 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001540 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001541 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001542 if (!property)
1543 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001544 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001545 DynamicImplSeen =
1546 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001547 // property implementation has a designated ivar. No need to assume a new
1548 // one.
1549 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1550 return 0;
1551 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001552 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001553 QualType PropType = Context.getCanonicalType(property->getType());
1554 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001555 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001556 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001557 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001558 (Expr *)0, true);
1559 ClassImpDecl->addDecl(Ivar);
1560 IDecl->makeDeclVisibleInContext(Ivar, false);
1561 property->setPropertyIvarDecl(Ivar);
1562 return Ivar;
1563 }
1564 return 0;
1565}
1566
John McCalldadc5752010-08-24 06:29:42 +00001567ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001568 CXXScopeSpec &SS,
1569 UnqualifiedId &Id,
1570 bool HasTrailingLParen,
1571 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001572 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1573 "cannot be direct & operand and have a trailing lparen");
1574
1575 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001576 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001577
John McCall10eae182009-11-30 22:42:35 +00001578 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001579
1580 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001582 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001584
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001586 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001588
John McCalle66edc12009-11-24 19:00:30 +00001589 // C++ [temp.dep.expr]p3:
1590 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001591 // -- an identifier that was declared with a dependent type,
1592 // (note: handled after lookup)
1593 // -- a template-id that is dependent,
1594 // (note: handled in BuildTemplateIdExpr)
1595 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001596 // -- a nested-name-specifier that contains a class-name that
1597 // names a dependent type.
1598 // Determine whether this is a member of an unknown specialization;
1599 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001600 bool DependentID = false;
1601 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1602 Name.getCXXNameType()->isDependentType()) {
1603 DependentID = true;
1604 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001605 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001606 if (RequireCompleteDeclContext(SS, DC))
1607 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001608 } else {
1609 DependentID = true;
1610 }
1611 }
1612
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001613 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001614 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001615 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001616
Fariborz Jahanian86151342010-07-22 23:33:21 +00001617 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001618 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001619 LookupResult R(*this, NameInfo,
1620 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1621 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001622 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001623 // Lookup the template name again to correctly establish the context in
1624 // which it was found. This is really unfortunate as we already did the
1625 // lookup to determine that it was a template name in the first place. If
1626 // this becomes a performance hit, we can work harder to preserve those
1627 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001628 bool MemberOfUnknownSpecialization;
1629 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1630 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001631
1632 if (MemberOfUnknownSpecialization ||
1633 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1634 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1635 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001636 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001637 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001638 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Douglas Gregora5226932011-02-04 13:35:07 +00001640 // If the result might be in a dependent base class, this is a dependent
1641 // id-expression.
1642 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1643 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1644 TemplateArgs);
1645
John McCalle66edc12009-11-24 19:00:30 +00001646 // If this reference is in an Objective-C method, then we need to do
1647 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001648 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001649 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001650 if (E.isInvalid())
1651 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001652
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001653 if (Expr *Ex = E.takeAs<Expr>())
1654 return Owned(Ex);
1655
1656 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001657 if (getLangOptions().ObjCDefaultSynthProperties &&
1658 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001659 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001660 if (const ObjCPropertyDecl *Property =
1661 canSynthesizeProvisionalIvar(II)) {
1662 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1663 Diag(Property->getLocation(), diag::note_property_declare);
1664 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001665 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1666 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001667 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001668 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001669 // for further use, this must be set to false if in class method.
1670 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001671 }
Chris Lattner59a25942008-03-31 00:36:02 +00001672 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001673
John McCalle66edc12009-11-24 19:00:30 +00001674 if (R.isAmbiguous())
1675 return ExprError();
1676
Douglas Gregor171c45a2009-02-18 21:56:37 +00001677 // Determine whether this name might be a candidate for
1678 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001679 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001680
John McCalle66edc12009-11-24 19:00:30 +00001681 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001682 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001683 // in C90, extension in C99, forbidden in C++).
1684 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1685 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1686 if (D) R.addDecl(D);
1687 }
1688
1689 // If this name wasn't predeclared and if this is not a function
1690 // call, diagnose the problem.
1691 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001692 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001693 return ExprError();
1694
1695 assert(!R.empty() &&
1696 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001697
1698 // If we found an Objective-C instance variable, let
1699 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001700 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001701 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1702 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001703 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001704 assert(E.isInvalid() || E.get());
1705 return move(E);
1706 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001707 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCalle66edc12009-11-24 19:00:30 +00001710 // This is guaranteed from this point on.
1711 assert(!R.empty() || ADL);
1712
John McCall2d74de92009-12-01 22:10:20 +00001713 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001714 // C++ [class.mfct.non-static]p3:
1715 // When an id-expression that is not part of a class member access
1716 // syntax and not used to form a pointer to member is used in the
1717 // body of a non-static member function of class X, if name lookup
1718 // resolves the name in the id-expression to a non-static non-type
1719 // member of some class C, the id-expression is transformed into a
1720 // class member access expression using (*this) as the
1721 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001722 //
1723 // But we don't actually need to do this for '&' operands if R
1724 // resolved to a function or overloaded function set, because the
1725 // expression is ill-formed if it actually works out to be a
1726 // non-static member function:
1727 //
1728 // C++ [expr.ref]p4:
1729 // Otherwise, if E1.E2 refers to a non-static member function. . .
1730 // [t]he expression can be used only as the left-hand operand of a
1731 // member function call.
1732 //
1733 // There are other safeguards against such uses, but it's important
1734 // to get this right here so that we don't end up making a
1735 // spuriously dependent expression if we're inside a dependent
1736 // instance method.
John McCall57500772009-12-16 12:17:52 +00001737 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001738 bool MightBeImplicitMember;
1739 if (!isAddressOfOperand)
1740 MightBeImplicitMember = true;
1741 else if (!SS.isEmpty())
1742 MightBeImplicitMember = false;
1743 else if (R.isOverloadedResult())
1744 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001745 else if (R.isUnresolvableResult())
1746 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001747 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001748 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1749 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001750
1751 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001752 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001753 }
1754
John McCalle66edc12009-11-24 19:00:30 +00001755 if (TemplateArgs)
1756 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001757
John McCalle66edc12009-11-24 19:00:30 +00001758 return BuildDeclarationNameExpr(SS, R, ADL);
1759}
1760
John McCall10eae182009-11-30 22:42:35 +00001761/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1762/// declaration name, generally during template instantiation.
1763/// There's a large number of things which don't need to be done along
1764/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001765ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001766Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001767 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001768 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001769 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001770 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001771
John McCall0b66eb32010-05-01 00:40:08 +00001772 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001773 return ExprError();
1774
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001775 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001776 LookupQualifiedName(R, DC);
1777
1778 if (R.isAmbiguous())
1779 return ExprError();
1780
1781 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001782 Diag(NameInfo.getLoc(), diag::err_no_member)
1783 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001784 return ExprError();
1785 }
1786
1787 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1788}
1789
1790/// LookupInObjCMethod - The parser has read a name in, and Sema has
1791/// detected that we're currently inside an ObjC method. Perform some
1792/// additional lookup.
1793///
1794/// Ideally, most of this would be done by lookup, but there's
1795/// actually quite a lot of extra work involved.
1796///
1797/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001798ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001799Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001800 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001801 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001802 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001803
John McCalle66edc12009-11-24 19:00:30 +00001804 // There are two cases to handle here. 1) scoped lookup could have failed,
1805 // in which case we should look for an ivar. 2) scoped lookup could have
1806 // found a decl, but that decl is outside the current instance method (i.e.
1807 // a global variable). In these two cases, we do a lookup for an ivar with
1808 // this name, if the lookup sucedes, we replace it our current decl.
1809
1810 // If we're in a class method, we don't normally want to look for
1811 // ivars. But if we don't find anything else, and there's an
1812 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001813 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001814
1815 bool LookForIvars;
1816 if (Lookup.empty())
1817 LookForIvars = true;
1818 else if (IsClassMethod)
1819 LookForIvars = false;
1820 else
1821 LookForIvars = (Lookup.isSingleResult() &&
1822 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001823 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001824 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001825 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001826 ObjCInterfaceDecl *ClassDeclared;
1827 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1828 // Diagnose using an ivar in a class method.
1829 if (IsClassMethod)
1830 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1831 << IV->getDeclName());
1832
1833 // If we're referencing an invalid decl, just return this as a silent
1834 // error node. The error diagnostic was already emitted on the decl.
1835 if (IV->isInvalidDecl())
1836 return ExprError();
1837
1838 // Check if referencing a field with __attribute__((deprecated)).
1839 if (DiagnoseUseOfDecl(IV, Loc))
1840 return ExprError();
1841
1842 // Diagnose the use of an ivar outside of the declaring class.
1843 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1844 ClassDeclared != IFace)
1845 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1846
1847 // FIXME: This should use a new expr for a direct reference, don't
1848 // turn this into Self->ivar, just return a BareIVarExpr or something.
1849 IdentifierInfo &II = Context.Idents.get("self");
1850 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001851 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001852 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001853 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001854 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001855 SelfName, false, false);
1856 if (SelfExpr.isInvalid())
1857 return ExprError();
1858
John Wiegley01296292011-04-08 18:41:53 +00001859 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1860 if (SelfExpr.isInvalid())
1861 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001862
John McCalle66edc12009-11-24 19:00:30 +00001863 MarkDeclarationReferenced(Loc, IV);
1864 return Owned(new (Context)
1865 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001866 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001867 }
Chris Lattner87313662010-04-12 05:10:17 +00001868 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001869 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001870 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001871 ObjCInterfaceDecl *ClassDeclared;
1872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1873 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1874 IFace == ClassDeclared)
1875 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1876 }
1877 }
1878
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001879 if (Lookup.empty() && II && AllowBuiltinCreation) {
1880 // FIXME. Consolidate this with similar code in LookupName.
1881 if (unsigned BuiltinID = II->getBuiltinID()) {
1882 if (!(getLangOptions().CPlusPlus &&
1883 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1884 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1885 S, Lookup.isForRedeclaration(),
1886 Lookup.getNameLoc());
1887 if (D) Lookup.addDecl(D);
1888 }
1889 }
1890 }
John McCalle66edc12009-11-24 19:00:30 +00001891 // Sentinel value saying that we didn't do anything special.
1892 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001893}
John McCalld14a8642009-11-21 08:51:07 +00001894
John McCall16df1e52010-03-30 21:47:33 +00001895/// \brief Cast a base object to a member's actual type.
1896///
1897/// Logically this happens in three phases:
1898///
1899/// * First we cast from the base type to the naming class.
1900/// The naming class is the class into which we were looking
1901/// when we found the member; it's the qualifier type if a
1902/// qualifier was provided, and otherwise it's the base type.
1903///
1904/// * Next we cast from the naming class to the declaring class.
1905/// If the member we found was brought into a class's scope by
1906/// a using declaration, this is that class; otherwise it's
1907/// the class declaring the member.
1908///
1909/// * Finally we cast from the declaring class to the "true"
1910/// declaring class of the member. This conversion does not
1911/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001912ExprResult
1913Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001914 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001915 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001916 NamedDecl *Member) {
1917 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1918 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001919 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001920
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001921 QualType DestRecordType;
1922 QualType DestType;
1923 QualType FromRecordType;
1924 QualType FromType = From->getType();
1925 bool PointerConversions = false;
1926 if (isa<FieldDecl>(Member)) {
1927 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001928
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001929 if (FromType->getAs<PointerType>()) {
1930 DestType = Context.getPointerType(DestRecordType);
1931 FromRecordType = FromType->getPointeeType();
1932 PointerConversions = true;
1933 } else {
1934 DestType = DestRecordType;
1935 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001936 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001937 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1938 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001939 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001940
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 DestType = Method->getThisType(Context);
1942 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 if (FromType->getAs<PointerType>()) {
1945 FromRecordType = FromType->getPointeeType();
1946 PointerConversions = true;
1947 } else {
1948 FromRecordType = FromType;
1949 DestType = DestRecordType;
1950 }
1951 } else {
1952 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001953 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001954 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001957 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 // If the unqualified types are the same, no conversion is necessary.
1960 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001961 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
John McCall16df1e52010-03-30 21:47:33 +00001963 SourceRange FromRange = From->getSourceRange();
1964 SourceLocation FromLoc = FromRange.getBegin();
1965
John McCall2536c6d2010-08-25 10:28:54 +00001966 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001969 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001970 // class name.
1971 //
1972 // If the member was a qualified name and the qualified referred to a
1973 // specific base subobject type, we'll cast to that intermediate type
1974 // first and then to the object in which the member is declared. That allows
1975 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1976 //
1977 // class Base { public: int x; };
1978 // class Derived1 : public Base { };
1979 // class Derived2 : public Base { };
1980 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1981 //
1982 // void VeryDerived::f() {
1983 // x = 17; // error: ambiguous base subobjects
1984 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1985 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001987 QualType QType = QualType(Qualifier->getAsType(), 0);
1988 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1989 assert(QType->isRecordType() && "lookup done with non-record type");
1990
1991 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1992
1993 // In C++98, the qualifier type doesn't actually have to be a base
1994 // type of the object type, in which case we just ignore it.
1995 // Otherwise build the appropriate casts.
1996 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001997 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001998 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001999 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002000 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002001
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002003 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002004 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2005 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002006
2007 FromType = QType;
2008 FromRecordType = QRecordType;
2009
2010 // If the qualifier type was the same as the destination type,
2011 // we're done.
2012 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002013 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 }
2015 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002016
John McCall16df1e52010-03-30 21:47:33 +00002017 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002018
John McCall16df1e52010-03-30 21:47:33 +00002019 // If we actually found the member through a using declaration, cast
2020 // down to the using declaration's type.
2021 //
2022 // Pointer equality is fine here because only one declaration of a
2023 // class ever has member declarations.
2024 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2025 assert(isa<UsingShadowDecl>(FoundDecl));
2026 QualType URecordType = Context.getTypeDeclType(
2027 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2028
2029 // We only need to do this if the naming-class to declaring-class
2030 // conversion is non-trivial.
2031 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2032 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002033 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002034 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002035 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002036 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002037
John McCall16df1e52010-03-30 21:47:33 +00002038 QualType UType = URecordType;
2039 if (PointerConversions)
2040 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002041 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2042 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002043 FromType = UType;
2044 FromRecordType = URecordType;
2045 }
2046
2047 // We don't do access control for the conversion from the
2048 // declaring class to the true declaring class.
2049 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002050 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002051
John McCallcf142162010-08-07 06:22:56 +00002052 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2054 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002055 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002056 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002057
John Wiegley01296292011-04-08 18:41:53 +00002058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2059 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002060}
Douglas Gregor3256d042009-06-30 15:47:41 +00002061
John McCalle66edc12009-11-24 19:00:30 +00002062bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002063 const LookupResult &R,
2064 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002065 // Only when used directly as the postfix-expression of a call.
2066 if (!HasTrailingLParen)
2067 return false;
2068
2069 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002070 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002071 return false;
2072
2073 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002074 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002075 return false;
2076
2077 // Turn off ADL when we find certain kinds of declarations during
2078 // normal lookup:
2079 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2080 NamedDecl *D = *I;
2081
2082 // C++0x [basic.lookup.argdep]p3:
2083 // -- a declaration of a class member
2084 // Since using decls preserve this property, we check this on the
2085 // original decl.
John McCall57500772009-12-16 12:17:52 +00002086 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002087 return false;
2088
2089 // C++0x [basic.lookup.argdep]p3:
2090 // -- a block-scope function declaration that is not a
2091 // using-declaration
2092 // NOTE: we also trigger this for function templates (in fact, we
2093 // don't check the decl type at all, since all other decl types
2094 // turn off ADL anyway).
2095 if (isa<UsingShadowDecl>(D))
2096 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2097 else if (D->getDeclContext()->isFunctionOrMethod())
2098 return false;
2099
2100 // C++0x [basic.lookup.argdep]p3:
2101 // -- a declaration that is neither a function or a function
2102 // template
2103 // And also for builtin functions.
2104 if (isa<FunctionDecl>(D)) {
2105 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2106
2107 // But also builtin functions.
2108 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2109 return false;
2110 } else if (!isa<FunctionTemplateDecl>(D))
2111 return false;
2112 }
2113
2114 return true;
2115}
2116
2117
John McCalld14a8642009-11-21 08:51:07 +00002118/// Diagnoses obvious problems with the use of the given declaration
2119/// as an expression. This is only actually called for lookups that
2120/// were not overloaded, and it doesn't promise that the declaration
2121/// will in fact be used.
2122static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002123 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002124 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2125 return true;
2126 }
2127
2128 if (isa<ObjCInterfaceDecl>(D)) {
2129 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2130 return true;
2131 }
2132
2133 if (isa<NamespaceDecl>(D)) {
2134 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2135 return true;
2136 }
2137
2138 return false;
2139}
2140
John McCalldadc5752010-08-24 06:29:42 +00002141ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002142Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002143 LookupResult &R,
2144 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002145 // If this is a single, fully-resolved result and we don't need ADL,
2146 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002147 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002148 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2149 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002150
2151 // We only need to check the declaration if there's exactly one
2152 // result, because in the overloaded case the results can only be
2153 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002154 if (R.isSingleResult() &&
2155 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002156 return ExprError();
2157
John McCall58cc69d2010-01-27 01:50:18 +00002158 // Otherwise, just build an unresolved lookup expression. Suppress
2159 // any lookup-related diagnostics; we'll hash these out later, when
2160 // we've picked a target.
2161 R.suppressDiagnostics();
2162
John McCalld14a8642009-11-21 08:51:07 +00002163 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002164 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002165 SS.getWithLocInContext(Context),
2166 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002167 NeedsADL, R.isOverloadedResult(),
2168 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002169
2170 return Owned(ULE);
2171}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002172
John McCalld14a8642009-11-21 08:51:07 +00002173/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002174ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002175Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002176 const DeclarationNameInfo &NameInfo,
2177 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002178 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002179 assert(!isa<FunctionTemplateDecl>(D) &&
2180 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002181
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002182 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002183 if (CheckDeclInExpr(*this, Loc, D))
2184 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002185
Douglas Gregore7488b92009-12-01 16:58:18 +00002186 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2187 // Specifically diagnose references to class templates that are missing
2188 // a template argument list.
2189 Diag(Loc, diag::err_template_decl_ref)
2190 << Template << SS.getRange();
2191 Diag(Template->getLocation(), diag::note_template_decl_here);
2192 return ExprError();
2193 }
2194
2195 // Make sure that we're referring to a value.
2196 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2197 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002198 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002199 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002200 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002201 return ExprError();
2202 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002203
Douglas Gregor171c45a2009-02-18 21:56:37 +00002204 // Check whether this declaration can be used. Note that we suppress
2205 // this check when we're going to perform argument-dependent lookup
2206 // on this function name, because this might not be the function
2207 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002208 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002209 return ExprError();
2210
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002211 // Only create DeclRefExpr's for valid Decl's.
2212 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002213 return ExprError();
2214
John McCallf3a88602011-02-03 08:15:49 +00002215 // Handle members of anonymous structs and unions. If we got here,
2216 // and the reference is to a class member indirect field, then this
2217 // must be the subject of a pointer-to-member expression.
2218 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2219 if (!indirectField->isCXXClassMember())
2220 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2221 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002222
Chris Lattner2a9d9892008-10-20 05:16:36 +00002223 // If the identifier reference is inside a block, and it refers to a value
2224 // that is outside the block, create a BlockDeclRefExpr instead of a
2225 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2226 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002227 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002228 // We do not do this for things like enum constants, global variables, etc,
2229 // as they do not get snapshotted.
2230 //
John McCall351762c2011-02-07 10:33:21 +00002231 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002232 case CR_Error:
2233 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002234
John McCallc63de662011-02-02 13:00:07 +00002235 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002236 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2237 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2238
2239 case CR_CaptureByRef:
2240 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2241 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002242
2243 case CR_NoCapture: {
2244 // If this reference is not in a block or if the referenced
2245 // variable is within the block, create a normal DeclRefExpr.
2246
2247 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002248 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002249
2250 switch (D->getKind()) {
2251 // Ignore all the non-ValueDecl kinds.
2252#define ABSTRACT_DECL(kind)
2253#define VALUE(type, base)
2254#define DECL(type, base) \
2255 case Decl::type:
2256#include "clang/AST/DeclNodes.inc"
2257 llvm_unreachable("invalid value decl kind");
2258 return ExprError();
2259
2260 // These shouldn't make it here.
2261 case Decl::ObjCAtDefsField:
2262 case Decl::ObjCIvar:
2263 llvm_unreachable("forming non-member reference to ivar?");
2264 return ExprError();
2265
2266 // Enum constants are always r-values and never references.
2267 // Unresolved using declarations are dependent.
2268 case Decl::EnumConstant:
2269 case Decl::UnresolvedUsingValue:
2270 valueKind = VK_RValue;
2271 break;
2272
2273 // Fields and indirect fields that got here must be for
2274 // pointer-to-member expressions; we just call them l-values for
2275 // internal consistency, because this subexpression doesn't really
2276 // exist in the high-level semantics.
2277 case Decl::Field:
2278 case Decl::IndirectField:
2279 assert(getLangOptions().CPlusPlus &&
2280 "building reference to field in C?");
2281
2282 // These can't have reference type in well-formed programs, but
2283 // for internal consistency we do this anyway.
2284 type = type.getNonReferenceType();
2285 valueKind = VK_LValue;
2286 break;
2287
2288 // Non-type template parameters are either l-values or r-values
2289 // depending on the type.
2290 case Decl::NonTypeTemplateParm: {
2291 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2292 type = reftype->getPointeeType();
2293 valueKind = VK_LValue; // even if the parameter is an r-value reference
2294 break;
2295 }
2296
2297 // For non-references, we need to strip qualifiers just in case
2298 // the template parameter was declared as 'const int' or whatever.
2299 valueKind = VK_RValue;
2300 type = type.getUnqualifiedType();
2301 break;
2302 }
2303
2304 case Decl::Var:
2305 // In C, "extern void blah;" is valid and is an r-value.
2306 if (!getLangOptions().CPlusPlus &&
2307 !type.hasQualifiers() &&
2308 type->isVoidType()) {
2309 valueKind = VK_RValue;
2310 break;
2311 }
2312 // fallthrough
2313
2314 case Decl::ImplicitParam:
2315 case Decl::ParmVar:
2316 // These are always l-values.
2317 valueKind = VK_LValue;
2318 type = type.getNonReferenceType();
2319 break;
2320
2321 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002322 const FunctionType *fty = type->castAs<FunctionType>();
2323
2324 // If we're referring to a function with an __unknown_anytype
2325 // result type, make the entire expression __unknown_anytype.
2326 if (fty->getResultType() == Context.UnknownAnyTy) {
2327 type = Context.UnknownAnyTy;
2328 valueKind = VK_RValue;
2329 break;
2330 }
2331
John McCallf4cd4f92011-02-09 01:13:10 +00002332 // Functions are l-values in C++.
2333 if (getLangOptions().CPlusPlus) {
2334 valueKind = VK_LValue;
2335 break;
2336 }
2337
2338 // C99 DR 316 says that, if a function type comes from a
2339 // function definition (without a prototype), that type is only
2340 // used for checking compatibility. Therefore, when referencing
2341 // the function, we pretend that we don't have the full function
2342 // type.
John McCall2979fe02011-04-12 00:42:48 +00002343 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2344 isa<FunctionProtoType>(fty))
2345 type = Context.getFunctionNoProtoType(fty->getResultType(),
2346 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002347
2348 // Functions are r-values in C.
2349 valueKind = VK_RValue;
2350 break;
2351 }
2352
2353 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002354 // If we're referring to a method with an __unknown_anytype
2355 // result type, make the entire expression __unknown_anytype.
2356 // This should only be possible with a type written directly.
2357 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2358 if (proto->getResultType() == Context.UnknownAnyTy) {
2359 type = Context.UnknownAnyTy;
2360 valueKind = VK_RValue;
2361 break;
2362 }
2363
John McCallf4cd4f92011-02-09 01:13:10 +00002364 // C++ methods are l-values if static, r-values if non-static.
2365 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2366 valueKind = VK_LValue;
2367 break;
2368 }
2369 // fallthrough
2370
2371 case Decl::CXXConversion:
2372 case Decl::CXXDestructor:
2373 case Decl::CXXConstructor:
2374 valueKind = VK_RValue;
2375 break;
2376 }
2377
2378 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2379 }
2380
John McCallc63de662011-02-02 13:00:07 +00002381 }
John McCall7decc9e2010-11-18 06:31:45 +00002382
John McCall351762c2011-02-07 10:33:21 +00002383 llvm_unreachable("unknown capture result");
2384 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002385}
Chris Lattnere168f762006-11-10 05:29:30 +00002386
John McCall2979fe02011-04-12 00:42:48 +00002387ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002388 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002389
Chris Lattnere168f762006-11-10 05:29:30 +00002390 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002391 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002392 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2393 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2394 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002395 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002396
Chris Lattnera81a0272008-01-12 08:14:25 +00002397 // Pre-defined identifiers are of type char[x], where x is the length of the
2398 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002399
Anders Carlsson2fb08242009-09-08 18:24:21 +00002400 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002401 if (!currentDecl && getCurBlock())
2402 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002403 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002404 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002405 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002406 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002407
Anders Carlsson0b209a82009-09-11 01:22:35 +00002408 QualType ResTy;
2409 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2410 ResTy = Context.DependentTy;
2411 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002412 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002413
Anders Carlsson0b209a82009-09-11 01:22:35 +00002414 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002415 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002416 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2417 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002418 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002419}
2420
John McCalldadc5752010-08-24 06:29:42 +00002421ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002422 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002423 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002424 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002425 if (Invalid)
2426 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002427
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002428 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002429 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002430 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002431 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002432
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002433 QualType Ty;
2434 if (!getLangOptions().CPlusPlus)
2435 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2436 else if (Literal.isWide())
2437 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002438 else if (Literal.isUTF16())
2439 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2440 else if (Literal.isUTF32())
2441 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002442 else if (Literal.isMultiChar())
2443 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002444 else
2445 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002446
Douglas Gregorfb65e592011-07-27 05:40:30 +00002447 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2448 if (Literal.isWide())
2449 Kind = CharacterLiteral::Wide;
2450 else if (Literal.isUTF16())
2451 Kind = CharacterLiteral::UTF16;
2452 else if (Literal.isUTF32())
2453 Kind = CharacterLiteral::UTF32;
2454
2455 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2456 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002457}
2458
John McCalldadc5752010-08-24 06:29:42 +00002459ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002460 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002461 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2462 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002463 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002464 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002465 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002466 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002467 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002468
Chris Lattner23b7eb62007-06-15 23:05:46 +00002469 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002470 // Add padding so that NumericLiteralParser can overread by one character.
2471 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002472 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002473
Chris Lattner67ca9252007-05-21 01:08:44 +00002474 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002475 bool Invalid = false;
2476 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2477 if (Invalid)
2478 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002479
Mike Stump11289f42009-09-09 15:08:12 +00002480 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002481 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002482 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002483 return ExprError();
2484
Chris Lattner1c20a172007-08-26 03:42:43 +00002485 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002486
Chris Lattner1c20a172007-08-26 03:42:43 +00002487 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002488 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002489 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002490 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002491 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002492 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002493 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002494 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002495
2496 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2497
John McCall53b93a02009-12-24 09:08:04 +00002498 using llvm::APFloat;
2499 APFloat Val(Format);
2500
2501 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002502
2503 // Overflow is always an error, but underflow is only an error if
2504 // we underflowed to zero (APFloat reports denormals as underflow).
2505 if ((result & APFloat::opOverflow) ||
2506 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002507 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002508 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002509 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002510 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002511 APFloat::getLargest(Format).toString(buffer);
2512 } else {
John McCall62abc942010-02-26 23:35:57 +00002513 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002514 APFloat::getSmallest(Format).toString(buffer);
2515 }
2516
2517 Diag(Tok.getLocation(), diagnostic)
2518 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002519 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002520 }
2521
2522 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002523 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002524
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002525 if (Ty == Context.DoubleTy) {
2526 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002527 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002528 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2529 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002530 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002531 }
2532 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002533 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002534 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002535 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002536 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002537
Neil Boothac582c52007-08-29 22:00:19 +00002538 // long long is a C99 feature.
2539 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002540 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002541 Diag(Tok.getLocation(), diag::ext_longlong);
2542
Chris Lattner67ca9252007-05-21 01:08:44 +00002543 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002544 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002545
Chris Lattner67ca9252007-05-21 01:08:44 +00002546 if (Literal.GetIntegerValue(ResultVal)) {
2547 // If this value didn't fit into uintmax_t, warn and force to ull.
2548 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002549 Ty = Context.UnsignedLongLongTy;
2550 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002551 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002552 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002553 // If this value fits into a ULL, try to figure out what else it fits into
2554 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002555
Chris Lattner67ca9252007-05-21 01:08:44 +00002556 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2557 // be an unsigned int.
2558 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2559
2560 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002561 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002562 if (!Literal.isLong && !Literal.isLongLong) {
2563 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002564 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002565
Chris Lattner67ca9252007-05-21 01:08:44 +00002566 // Does it fit in a unsigned int?
2567 if (ResultVal.isIntN(IntSize)) {
2568 // Does it fit in a signed int?
2569 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002570 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002571 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002572 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002573 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002574 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002575 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002576
Chris Lattner67ca9252007-05-21 01:08:44 +00002577 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002578 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002579 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002580
Chris Lattner67ca9252007-05-21 01:08:44 +00002581 // Does it fit in a unsigned long?
2582 if (ResultVal.isIntN(LongSize)) {
2583 // Does it fit in a signed long?
2584 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002585 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002586 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002587 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002588 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002589 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002590 }
2591
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002593 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002594 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002595
Chris Lattner67ca9252007-05-21 01:08:44 +00002596 // Does it fit in a unsigned long long?
2597 if (ResultVal.isIntN(LongLongSize)) {
2598 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002599 // To be compatible with MSVC, hex integer literals ending with the
2600 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002601 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2602 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002603 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002604 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002605 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002606 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002607 }
2608 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002609
Chris Lattner67ca9252007-05-21 01:08:44 +00002610 // If we still couldn't decide a type, we probably have something that
2611 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002612 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002613 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002614 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002615 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002616 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002617
Chris Lattner55258cf2008-05-09 05:59:00 +00002618 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002619 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002620 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002621 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002622 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002623
Chris Lattner1c20a172007-08-26 03:42:43 +00002624 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2625 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002626 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002627 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002628
2629 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002630}
2631
John McCalldadc5752010-08-24 06:29:42 +00002632ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002633 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002634 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002635 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002636}
2637
Chandler Carruth62da79c2011-05-26 08:53:12 +00002638static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2639 SourceLocation Loc,
2640 SourceRange ArgRange) {
2641 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2642 // scalar or vector data type argument..."
2643 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2644 // type (C99 6.2.5p18) or void.
2645 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2646 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2647 << T << ArgRange;
2648 return true;
2649 }
2650
2651 assert((T->isVoidType() || !T->isIncompleteType()) &&
2652 "Scalar types should always be complete");
2653 return false;
2654}
2655
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002656static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2657 SourceLocation Loc,
2658 SourceRange ArgRange,
2659 UnaryExprOrTypeTrait TraitKind) {
2660 // C99 6.5.3.4p1:
2661 if (T->isFunctionType()) {
2662 // alignof(function) is allowed as an extension.
2663 if (TraitKind == UETT_SizeOf)
2664 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2665 return false;
2666 }
2667
2668 // Allow sizeof(void)/alignof(void) as an extension.
2669 if (T->isVoidType()) {
2670 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2671 return false;
2672 }
2673
2674 return true;
2675}
2676
2677static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2678 SourceLocation Loc,
2679 SourceRange ArgRange,
2680 UnaryExprOrTypeTrait TraitKind) {
2681 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2682 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2683 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2684 << T << (TraitKind == UETT_SizeOf)
2685 << ArgRange;
2686 return true;
2687 }
2688
2689 return false;
2690}
2691
Chandler Carruth14502c22011-05-26 08:53:10 +00002692/// \brief Check the constrains on expression operands to unary type expression
2693/// and type traits.
2694///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002695/// Completes any types necessary and validates the constraints on the operand
2696/// expression. The logic mostly mirrors the type-based overload, but may modify
2697/// the expression as it completes the type for that expression through template
2698/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002699bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2700 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002701 QualType ExprTy = Op->getType();
2702
2703 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2704 // the result is the size of the referenced type."
2705 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2706 // result shall be the alignment of the referenced type."
2707 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2708 ExprTy = Ref->getPointeeType();
2709
2710 if (ExprKind == UETT_VecStep)
2711 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2712 Op->getSourceRange());
2713
2714 // Whitelist some types as extensions
2715 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2716 Op->getSourceRange(), ExprKind))
2717 return false;
2718
2719 if (RequireCompleteExprType(Op,
2720 PDiag(diag::err_sizeof_alignof_incomplete_type)
2721 << ExprKind << Op->getSourceRange(),
2722 std::make_pair(SourceLocation(), PDiag(0))))
2723 return true;
2724
2725 // Completeing the expression's type may have changed it.
2726 ExprTy = Op->getType();
2727 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2728 ExprTy = Ref->getPointeeType();
2729
2730 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2731 Op->getSourceRange(), ExprKind))
2732 return true;
2733
Nico Weber0870deb2011-06-15 02:47:03 +00002734 if (ExprKind == UETT_SizeOf) {
2735 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2736 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2737 QualType OType = PVD->getOriginalType();
2738 QualType Type = PVD->getType();
2739 if (Type->isPointerType() && OType->isArrayType()) {
2740 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2741 << Type << OType;
2742 Diag(PVD->getLocation(), diag::note_declared_at);
2743 }
2744 }
2745 }
2746 }
2747
Chandler Carruth7c430c02011-05-27 01:33:31 +00002748 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002749}
2750
2751/// \brief Check the constraints on operands to unary expression and type
2752/// traits.
2753///
2754/// This will complete any types necessary, and validate the various constraints
2755/// on those operands.
2756///
Steve Naroff71b59a92007-06-04 22:22:31 +00002757/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002758/// C99 6.3.2.1p[2-4] all state:
2759/// Except when it is the operand of the sizeof operator ...
2760///
2761/// C++ [expr.sizeof]p4
2762/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2763/// standard conversions are not applied to the operand of sizeof.
2764///
2765/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002766bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2767 SourceLocation OpLoc,
2768 SourceRange ExprRange,
2769 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002770 if (exprType->isDependentType())
2771 return false;
2772
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002773 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2774 // the result is the size of the referenced type."
2775 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2776 // result shall be the alignment of the referenced type."
2777 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2778 exprType = Ref->getPointeeType();
2779
Chandler Carruth62da79c2011-05-26 08:53:12 +00002780 if (ExprKind == UETT_VecStep)
2781 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002782
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002783 // Whitelist some types as extensions
2784 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2785 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002786 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattner62975a72009-04-24 00:30:45 +00002788 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002789 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002790 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002791 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002792
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002793 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2794 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002795 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner62975a72009-04-24 00:30:45 +00002797 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002798}
2799
Chandler Carruth14502c22011-05-26 08:53:10 +00002800static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002801 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002802
Mike Stump11289f42009-09-09 15:08:12 +00002803 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002804 if (isa<DeclRefExpr>(E))
2805 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002806
2807 // Cannot know anything else if the expression is dependent.
2808 if (E->isTypeDependent())
2809 return false;
2810
Douglas Gregor71235ec2009-05-02 02:18:30 +00002811 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002812 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2813 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002814 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002815 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002816
2817 // Alignment of a field access is always okay, so long as it isn't a
2818 // bit-field.
2819 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002820 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002821 return false;
2822
Chandler Carruth14502c22011-05-26 08:53:10 +00002823 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002824}
2825
Chandler Carruth14502c22011-05-26 08:53:10 +00002826bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002827 E = E->IgnoreParens();
2828
2829 // Cannot know anything else if the expression is dependent.
2830 if (E->isTypeDependent())
2831 return false;
2832
Chandler Carruth14502c22011-05-26 08:53:10 +00002833 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002834}
2835
Douglas Gregor0950e412009-03-13 21:01:28 +00002836/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002837ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002838Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2839 SourceLocation OpLoc,
2840 UnaryExprOrTypeTrait ExprKind,
2841 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002842 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002843 return ExprError();
2844
John McCallbcd03502009-12-07 02:54:59 +00002845 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002846
Douglas Gregor0950e412009-03-13 21:01:28 +00002847 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002848 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002849 return ExprError();
2850
2851 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2853 Context.getSizeType(),
2854 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002855}
2856
2857/// \brief Build a sizeof or alignof expression given an expression
2858/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002859ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002860Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2861 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002862 ExprResult PE = CheckPlaceholderExpr(E);
2863 if (PE.isInvalid())
2864 return ExprError();
2865
2866 E = PE.get();
2867
Douglas Gregor0950e412009-03-13 21:01:28 +00002868 // Verify that the operand is valid.
2869 bool isInvalid = false;
2870 if (E->isTypeDependent()) {
2871 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002872 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002873 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002874 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002875 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002876 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002877 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002878 isInvalid = true;
2879 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002880 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002881 }
2882
2883 if (isInvalid)
2884 return ExprError();
2885
2886 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002887 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002888 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002889 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002890}
2891
Peter Collingbournee190dee2011-03-11 19:24:49 +00002892/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2893/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002894/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002895ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002896Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2897 UnaryExprOrTypeTrait ExprKind, bool isType,
2898 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002899 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002900 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002901
Sebastian Redl6f282892008-11-11 17:56:53 +00002902 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002903 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002904 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002905 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002906 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002907
Douglas Gregor0950e412009-03-13 21:01:28 +00002908 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002909 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002910 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002911}
2912
John Wiegley01296292011-04-08 18:41:53 +00002913static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002914 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002915 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002916 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002917
John McCall34376a62010-12-04 03:47:34 +00002918 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002919 if (V.get()->getObjectKind() != OK_Ordinary) {
2920 V = S.DefaultLvalueConversion(V.take());
2921 if (V.isInvalid())
2922 return QualType();
2923 }
John McCall34376a62010-12-04 03:47:34 +00002924
Chris Lattnere267f5d2007-08-26 05:39:26 +00002925 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002926 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002927 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattnere267f5d2007-08-26 05:39:26 +00002929 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002930 if (V.get()->getType()->isArithmeticType())
2931 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002932
John McCall36226622010-10-12 02:09:17 +00002933 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002934 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002935 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002936 if (PR.get() != V.get()) {
2937 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002938 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002939 }
2940
Chris Lattnere267f5d2007-08-26 05:39:26 +00002941 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002942 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002943 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002944 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002945}
2946
2947
Chris Lattnere168f762006-11-10 05:29:30 +00002948
John McCalldadc5752010-08-24 06:29:42 +00002949ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002950Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002951 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002952 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002953 switch (Kind) {
2954 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002955 case tok::plusplus: Opc = UO_PostInc; break;
2956 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002957 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002958
John McCallb268a282010-08-23 23:25:46 +00002959 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002960}
2961
John McCalldadc5752010-08-24 06:29:42 +00002962ExprResult
John McCallb268a282010-08-23 23:25:46 +00002963Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2964 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002965 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002966 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002967 if (Result.isInvalid()) return ExprError();
2968 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002969
John McCallb268a282010-08-23 23:25:46 +00002970 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregor40412ac2008-11-19 17:17:41 +00002972 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002973 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002974 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002975 Context.DependentTy,
2976 VK_LValue, OK_Ordinary,
2977 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002978 }
2979
Mike Stump11289f42009-09-09 15:08:12 +00002980 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002981 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002982 LHSExp->getType()->isEnumeralType() ||
2983 RHSExp->getType()->isRecordType() ||
2984 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002985 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002986 }
2987
John McCallb268a282010-08-23 23:25:46 +00002988 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002989}
2990
2991
John McCalldadc5752010-08-24 06:29:42 +00002992ExprResult
John McCallb268a282010-08-23 23:25:46 +00002993Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2994 Expr *Idx, SourceLocation RLoc) {
2995 Expr *LHSExp = Base;
2996 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002997
Chris Lattner36d572b2007-07-16 00:14:47 +00002998 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00002999 if (!LHSExp->getType()->getAs<VectorType>()) {
3000 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3001 if (Result.isInvalid())
3002 return ExprError();
3003 LHSExp = Result.take();
3004 }
3005 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3006 if (Result.isInvalid())
3007 return ExprError();
3008 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003009
Chris Lattner36d572b2007-07-16 00:14:47 +00003010 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003011 ExprValueKind VK = VK_LValue;
3012 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003013
Steve Naroffc1aadb12007-03-28 21:49:40 +00003014 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003015 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003016 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003017 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003018 Expr *BaseExpr, *IndexExpr;
3019 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003020 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3021 BaseExpr = LHSExp;
3022 IndexExpr = RHSExp;
3023 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003024 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003025 BaseExpr = LHSExp;
3026 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003027 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003028 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003029 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003030 BaseExpr = RHSExp;
3031 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003032 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003033 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003034 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003035 BaseExpr = LHSExp;
3036 IndexExpr = RHSExp;
3037 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003038 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003039 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003040 // Handle the uncommon case of "123[Ptr]".
3041 BaseExpr = RHSExp;
3042 IndexExpr = LHSExp;
3043 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003044 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003045 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003046 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003047 VK = LHSExp->getValueKind();
3048 if (VK != VK_RValue)
3049 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003050
Chris Lattner36d572b2007-07-16 00:14:47 +00003051 // FIXME: need to deal with const...
3052 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003053 } else if (LHSTy->isArrayType()) {
3054 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003055 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003056 // wasn't promoted because of the C90 rule that doesn't
3057 // allow promoting non-lvalue arrays. Warn, then
3058 // force the promotion here.
3059 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3060 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003061 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3062 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003063 LHSTy = LHSExp->getType();
3064
3065 BaseExpr = LHSExp;
3066 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003067 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003068 } else if (RHSTy->isArrayType()) {
3069 // Same as previous, except for 123[f().a] case
3070 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3071 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003072 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3073 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003074 RHSTy = RHSExp->getType();
3075
3076 BaseExpr = RHSExp;
3077 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003078 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003079 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003080 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3081 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003082 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003083 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003084 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003085 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3086 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003087
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003088 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003089 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3090 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003091 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3092
Douglas Gregorac1fb652009-03-24 19:52:54 +00003093 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003094 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3095 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003096 // incomplete types are not object types.
3097 if (ResultType->isFunctionType()) {
3098 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3099 << ResultType << BaseExpr->getSourceRange();
3100 return ExprError();
3101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003103 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3104 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003105 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3106 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003107
3108 // C forbids expressions of unqualified void type from being l-values.
3109 // See IsCForbiddenLValueType.
3110 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003111 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003112 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003113 PDiag(diag::err_subscript_incomplete_type)
3114 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003115 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003116
Chris Lattner62975a72009-04-24 00:30:45 +00003117 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003118 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003119 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3120 << ResultType << BaseExpr->getSourceRange();
3121 return ExprError();
3122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
John McCall4bc41ae2010-11-18 19:01:18 +00003124 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003125 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003126
Mike Stump4e1f26a2009-02-19 03:04:26 +00003127 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003128 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003129}
3130
John McCalldadc5752010-08-24 06:29:42 +00003131ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003132 FunctionDecl *FD,
3133 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003134 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003135 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003136 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003137 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003138 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003139 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003140 return ExprError();
3141 }
3142
3143 if (Param->hasUninstantiatedDefaultArg()) {
3144 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003145
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003146 // Instantiate the expression.
3147 MultiLevelTemplateArgumentList ArgList
3148 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003149
Nico Weber44887f62010-11-29 18:19:25 +00003150 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003151 = ArgList.getInnermost();
3152 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3153 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003154
Nico Weber44887f62010-11-29 18:19:25 +00003155 ExprResult Result;
3156 {
3157 // C++ [dcl.fct.default]p5:
3158 // The names in the [default argument] expression are bound, and
3159 // the semantic constraints are checked, at the point where the
3160 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003161 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003162 Result = SubstExpr(UninstExpr, ArgList);
3163 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003164 if (Result.isInvalid())
3165 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003167 // Check the expression as an initializer for the parameter.
3168 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003169 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003170 InitializationKind Kind
3171 = InitializationKind::CreateCopy(Param->getLocation(),
3172 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3173 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003174
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003175 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3176 Result = InitSeq.Perform(*this, Entity, Kind,
3177 MultiExprArg(*this, &ResultE, 1));
3178 if (Result.isInvalid())
3179 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003180
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003181 // Build the default argument expression.
3182 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3183 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003184 }
3185
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003186 // If the default expression creates temporaries, we need to
3187 // push them to the current stack of expression temporaries so they'll
3188 // be properly destroyed.
3189 // FIXME: We should really be rebuilding the default argument with new
3190 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003191 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3192 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3193 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3194 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3195 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003196 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003197 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198
3199 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003200 // Just mark all of the declarations in this potentially-evaluated expression
3201 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003202 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003203 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003204}
3205
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003206/// ConvertArgumentsForCall - Converts the arguments specified in
3207/// Args/NumArgs to the parameter types of the function FDecl with
3208/// function prototype Proto. Call is the call expression itself, and
3209/// Fn is the function expression. For a C++ member function, this
3210/// routine does not attempt to convert the object argument. Returns
3211/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003212bool
3213Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003214 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003215 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003216 Expr **Args, unsigned NumArgs,
3217 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003218 // Bail out early if calling a builtin with custom typechecking.
3219 // We don't need to do this in the
3220 if (FDecl)
3221 if (unsigned ID = FDecl->getBuiltinID())
3222 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3223 return false;
3224
Mike Stump4e1f26a2009-02-19 03:04:26 +00003225 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003226 // assignment, to the types of the corresponding parameter, ...
3227 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003228 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003229
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003230 // If too few arguments are available (and we don't have default
3231 // arguments for the remaining parameters), don't make the call.
3232 if (NumArgs < NumArgsInProto) {
3233 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3234 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003235 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003236 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003237 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003238 }
3239
3240 // If too many are passed and not variadic, error on the extras and drop
3241 // them.
3242 if (NumArgs > NumArgsInProto) {
3243 if (!Proto->isVariadic()) {
3244 Diag(Args[NumArgsInProto]->getLocStart(),
3245 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003246 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003247 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003248 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3249 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003250
3251 // Emit the location of the prototype.
3252 if (FDecl && !FDecl->getBuiltinID())
3253 Diag(FDecl->getLocStart(),
3254 diag::note_typecheck_call_too_many_args)
3255 << FDecl;
3256
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003257 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003258 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003259 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003260 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003261 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003262 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003263 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003264 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3265 if (Fn->getType()->isBlockPointerType())
3266 CallType = VariadicBlock; // Block
3267 else if (isa<MemberExpr>(Fn))
3268 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003269 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003270 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003271 if (Invalid)
3272 return true;
3273 unsigned TotalNumArgs = AllArgs.size();
3274 for (unsigned i = 0; i < TotalNumArgs; ++i)
3275 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003276
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003277 return false;
3278}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003279
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003280bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3281 FunctionDecl *FDecl,
3282 const FunctionProtoType *Proto,
3283 unsigned FirstProtoArg,
3284 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003285 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003286 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003287 unsigned NumArgsInProto = Proto->getNumArgs();
3288 unsigned NumArgsToCheck = NumArgs;
3289 bool Invalid = false;
3290 if (NumArgs != NumArgsInProto)
3291 // Use default arguments for missing arguments
3292 NumArgsToCheck = NumArgsInProto;
3293 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003294 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003295 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003296 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003297
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003298 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003299 if (ArgIx < NumArgs) {
3300 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003301
Eli Friedman3164fb12009-03-22 22:00:50 +00003302 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3303 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003304 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003305 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003306 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003307
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003308 // Pass the argument
3309 ParmVarDecl *Param = 0;
3310 if (FDecl && i < FDecl->getNumParams())
3311 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003312
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003313 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003314 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003315 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3316 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003317 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003318 SourceLocation(),
3319 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003320 if (ArgE.isInvalid())
3321 return true;
3322
3323 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003324 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003325 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003326
John McCalldadc5752010-08-24 06:29:42 +00003327 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003328 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003329 if (ArgExpr.isInvalid())
3330 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003331
Anders Carlsson355933d2009-08-25 03:49:14 +00003332 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003333 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003334 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003335 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003336
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003337 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003338 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003339
3340 // Assume that extern "C" functions with variadic arguments that
3341 // return __unknown_anytype aren't *really* variadic.
3342 if (Proto->getResultType() == Context.UnknownAnyTy &&
3343 FDecl && FDecl->isExternC()) {
3344 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3345 ExprResult arg;
3346 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3347 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3348 else
3349 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3350 Invalid |= arg.isInvalid();
3351 AllArgs.push_back(arg.take());
3352 }
3353
3354 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3355 } else {
3356 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3357 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3358 Invalid |= Arg.isInvalid();
3359 AllArgs.push_back(Arg.take());
3360 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003361 }
3362 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003363 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003364}
3365
John McCall2979fe02011-04-12 00:42:48 +00003366/// Given a function expression of unknown-any type, try to rebuild it
3367/// to have a function type.
3368static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3369
Steve Naroff83895f72007-09-16 03:34:24 +00003370/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003371/// This provides the location of the left/right parens and a list of comma
3372/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003373ExprResult
John McCallb268a282010-08-23 23:25:46 +00003374Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003375 MultiExprArg args, SourceLocation RParenLoc,
3376 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003377 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003378
3379 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003380 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003381 if (Result.isInvalid()) return ExprError();
3382 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003383
John McCallb268a282010-08-23 23:25:46 +00003384 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003385
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003386 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003387 // If this is a pseudo-destructor expression, build the call immediately.
3388 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3389 if (NumArgs > 0) {
3390 // Pseudo-destructor calls should not have any arguments.
3391 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003392 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003393 SourceRange(Args[0]->getLocStart(),
3394 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003395
Douglas Gregorad8a3362009-09-04 17:36:40 +00003396 NumArgs = 0;
3397 }
Mike Stump11289f42009-09-09 15:08:12 +00003398
Douglas Gregorad8a3362009-09-04 17:36:40 +00003399 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003400 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003403 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003404 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003405 // FIXME: Will need to cache the results of name lookup (including ADL) in
3406 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003407 bool Dependent = false;
3408 if (Fn->isTypeDependent())
3409 Dependent = true;
3410 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3411 Dependent = true;
3412
Peter Collingbourne41f85462011-02-09 21:07:24 +00003413 if (Dependent) {
3414 if (ExecConfig) {
3415 return Owned(new (Context) CUDAKernelCallExpr(
3416 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3417 Context.DependentTy, VK_RValue, RParenLoc));
3418 } else {
3419 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3420 Context.DependentTy, VK_RValue,
3421 RParenLoc));
3422 }
3423 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003424
3425 // Determine whether this is a call to an object (C++ [over.call.object]).
3426 if (Fn->getType()->isRecordType())
3427 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003428 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003429
John McCall2979fe02011-04-12 00:42:48 +00003430 if (Fn->getType() == Context.UnknownAnyTy) {
3431 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3432 if (result.isInvalid()) return ExprError();
3433 Fn = result.take();
3434 }
3435
John McCall0009fcc2011-04-26 20:42:42 +00003436 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003437 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003438 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003439 }
John McCall0009fcc2011-04-26 20:42:42 +00003440 }
John McCall10eae182009-11-30 22:42:35 +00003441
John McCall0009fcc2011-04-26 20:42:42 +00003442 // Check for overloaded calls. This can happen even in C due to extensions.
3443 if (Fn->getType() == Context.OverloadTy) {
3444 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3445
3446 // We aren't supposed to apply this logic if there's an '&' involved.
3447 if (!find.IsAddressOfOperand) {
3448 OverloadExpr *ovl = find.Expression;
3449 if (isa<UnresolvedLookupExpr>(ovl)) {
3450 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3451 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3452 RParenLoc, ExecConfig);
3453 } else {
John McCall2d74de92009-12-01 22:10:20 +00003454 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003455 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003456 }
3457 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003458 }
3459
Douglas Gregore254f902009-02-04 00:32:51 +00003460 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003461
Eli Friedmane14b1992009-12-26 03:35:45 +00003462 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003463
John McCall57500772009-12-16 12:17:52 +00003464 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003465 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3466 if (UnOp->getOpcode() == UO_AddrOf)
3467 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3468
John McCall57500772009-12-16 12:17:52 +00003469 if (isa<DeclRefExpr>(NakedFn))
3470 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003471 else if (isa<MemberExpr>(NakedFn))
3472 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003473
Peter Collingbourne41f85462011-02-09 21:07:24 +00003474 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3475 ExecConfig);
3476}
3477
3478ExprResult
3479Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3480 MultiExprArg execConfig, SourceLocation GGGLoc) {
3481 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3482 if (!ConfigDecl)
3483 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3484 << "cudaConfigureCall");
3485 QualType ConfigQTy = ConfigDecl->getType();
3486
3487 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3488 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3489
3490 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003491}
3492
Tanya Lattner55808c12011-06-04 00:47:47 +00003493/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3494///
3495/// __builtin_astype( value, dst type )
3496///
3497ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3498 SourceLocation BuiltinLoc,
3499 SourceLocation RParenLoc) {
3500 ExprValueKind VK = VK_RValue;
3501 ExprObjectKind OK = OK_Ordinary;
3502 QualType DstTy = GetTypeFromParser(destty);
3503 QualType SrcTy = expr->getType();
3504 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3505 return ExprError(Diag(BuiltinLoc,
3506 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003507 << DstTy
3508 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003509 << expr->getSourceRange());
3510 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3511}
3512
John McCall57500772009-12-16 12:17:52 +00003513/// BuildResolvedCallExpr - Build a call to a resolved expression,
3514/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003515/// unary-convert to an expression of function-pointer or
3516/// block-pointer type.
3517///
3518/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003519ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003520Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3521 SourceLocation LParenLoc,
3522 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003523 SourceLocation RParenLoc,
3524 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003525 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3526
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003527 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003528 ExprResult Result = UsualUnaryConversions(Fn);
3529 if (Result.isInvalid())
3530 return ExprError();
3531 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003532
Chris Lattner08464942007-12-28 05:29:59 +00003533 // Make the call expr early, before semantic checks. This guarantees cleanup
3534 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003535 CallExpr *TheCall;
3536 if (Config) {
3537 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3538 cast<CallExpr>(Config),
3539 Args, NumArgs,
3540 Context.BoolTy,
3541 VK_RValue,
3542 RParenLoc);
3543 } else {
3544 TheCall = new (Context) CallExpr(Context, Fn,
3545 Args, NumArgs,
3546 Context.BoolTy,
3547 VK_RValue,
3548 RParenLoc);
3549 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003550
John McCallbebede42011-02-26 05:39:39 +00003551 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3552
3553 // Bail out early if calling a builtin with custom typechecking.
3554 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3555 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3556
John McCall31996342011-04-07 08:22:57 +00003557 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003558 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003559 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003560 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3561 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003562 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003563 if (FuncT == 0)
3564 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3565 << Fn->getType() << Fn->getSourceRange());
3566 } else if (const BlockPointerType *BPT =
3567 Fn->getType()->getAs<BlockPointerType>()) {
3568 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3569 } else {
John McCall31996342011-04-07 08:22:57 +00003570 // Handle calls to expressions of unknown-any type.
3571 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003572 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003573 if (rewrite.isInvalid()) return ExprError();
3574 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003575 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003576 goto retry;
3577 }
3578
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003579 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3580 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003581 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003582
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003583 if (getLangOptions().CUDA) {
3584 if (Config) {
3585 // CUDA: Kernel calls must be to global functions
3586 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3587 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3588 << FDecl->getName() << Fn->getSourceRange());
3589
3590 // CUDA: Kernel function must have 'void' return type
3591 if (!FuncT->getResultType()->isVoidType())
3592 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3593 << Fn->getType() << Fn->getSourceRange());
3594 }
3595 }
3596
Eli Friedman3164fb12009-03-22 22:00:50 +00003597 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003598 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003599 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003600 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003601 return ExprError();
3602
Chris Lattner08464942007-12-28 05:29:59 +00003603 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003604 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003605 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003606
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003607 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003608 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003609 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003610 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003611 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003612 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003613
Douglas Gregord8e97de2009-04-02 15:37:10 +00003614 if (FDecl) {
3615 // Check if we have too few/too many template arguments, based
3616 // on our knowledge of the function definition.
3617 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003618 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003619 const FunctionProtoType *Proto
3620 = Def->getType()->getAs<FunctionProtoType>();
3621 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003622 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3623 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003624 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003625
3626 // If the function we're calling isn't a function prototype, but we have
3627 // a function prototype from a prior declaratiom, use that prototype.
3628 if (!FDecl->hasPrototype())
3629 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003630 }
3631
Steve Naroff0b661582007-08-28 23:30:39 +00003632 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003633 for (unsigned i = 0; i != NumArgs; i++) {
3634 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003635
3636 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003637 InitializedEntity Entity
3638 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003639 Proto->getArgType(i),
3640 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003641 ExprResult ArgE = PerformCopyInitialization(Entity,
3642 SourceLocation(),
3643 Owned(Arg));
3644 if (ArgE.isInvalid())
3645 return true;
3646
3647 Arg = ArgE.takeAs<Expr>();
3648
3649 } else {
John Wiegley01296292011-04-08 18:41:53 +00003650 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3651
3652 if (ArgE.isInvalid())
3653 return true;
3654
3655 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003656 }
3657
Douglas Gregor83025412010-10-26 05:45:40 +00003658 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3659 Arg->getType(),
3660 PDiag(diag::err_call_incomplete_argument)
3661 << Arg->getSourceRange()))
3662 return ExprError();
3663
Chris Lattner08464942007-12-28 05:29:59 +00003664 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003665 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003666 }
Chris Lattner08464942007-12-28 05:29:59 +00003667
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003668 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3669 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003670 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3671 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003672
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003673 // Check for sentinels
3674 if (NDecl)
3675 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003676
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003677 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003678 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003679 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003680 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003681
John McCallbebede42011-02-26 05:39:39 +00003682 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003683 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003684 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003685 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003686 return ExprError();
3687 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003688
John McCallb268a282010-08-23 23:25:46 +00003689 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003690}
3691
John McCalldadc5752010-08-24 06:29:42 +00003692ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003693Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003694 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003695 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003696 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003697 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003698
3699 TypeSourceInfo *TInfo;
3700 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3701 if (!TInfo)
3702 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3703
John McCallb268a282010-08-23 23:25:46 +00003704 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003705}
3706
John McCalldadc5752010-08-24 06:29:42 +00003707ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003708Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003709 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003710 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003711
Eli Friedman37a186d2008-05-20 05:22:08 +00003712 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003713 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3714 PDiag(diag::err_illegal_decl_array_incomplete_type)
3715 << SourceRange(LParenLoc,
3716 literalExpr->getSourceRange().getEnd())))
3717 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003718 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003719 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3720 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003721 } else if (!literalType->isDependentType() &&
3722 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003723 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003724 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003725 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003726 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003727
Douglas Gregor85dabae2009-12-16 01:38:02 +00003728 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003729 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003730 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003731 = InitializationKind::CreateCStyleCast(LParenLoc,
3732 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003733 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003734 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003735 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003736 &literalType);
3737 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003738 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003739 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003740
Chris Lattner79413952008-12-04 23:50:19 +00003741 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003742 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003743 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003744 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003745 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003746
John McCall7decc9e2010-11-18 06:31:45 +00003747 // In C, compound literals are l-values for some reason.
3748 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3749
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003750 return MaybeBindToTemporary(
3751 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3752 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003753}
3754
John McCalldadc5752010-08-24 06:29:42 +00003755ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003756Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003757 SourceLocation RBraceLoc) {
3758 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003759 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003760
Steve Naroff30d242c2007-09-15 18:49:24 +00003761 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003762 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003763
Ted Kremenekac034612010-04-13 23:39:13 +00003764 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3765 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003766 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003767 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003768}
3769
John McCalld7646252010-11-14 08:17:51 +00003770/// Prepares for a scalar cast, performing all the necessary stages
3771/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003772static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003773 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3774 // Also, callers should have filtered out the invalid cases with
3775 // pointers. Everything else should be possible.
3776
John Wiegley01296292011-04-08 18:41:53 +00003777 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003778 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003779 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003780
John McCall8cb679e2010-11-15 09:13:47 +00003781 switch (SrcTy->getScalarTypeKind()) {
3782 case Type::STK_MemberPointer:
3783 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003784
John McCall8cb679e2010-11-15 09:13:47 +00003785 case Type::STK_Pointer:
3786 switch (DestTy->getScalarTypeKind()) {
3787 case Type::STK_Pointer:
3788 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003789 CK_AnyPointerToObjCPointerCast :
3790 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003791 case Type::STK_Bool:
3792 return CK_PointerToBoolean;
3793 case Type::STK_Integral:
3794 return CK_PointerToIntegral;
3795 case Type::STK_Floating:
3796 case Type::STK_FloatingComplex:
3797 case Type::STK_IntegralComplex:
3798 case Type::STK_MemberPointer:
3799 llvm_unreachable("illegal cast from pointer");
3800 }
3801 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003802
John McCall8cb679e2010-11-15 09:13:47 +00003803 case Type::STK_Bool: // casting from bool is like casting from an integer
3804 case Type::STK_Integral:
3805 switch (DestTy->getScalarTypeKind()) {
3806 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003807 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003808 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003809 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003810 case Type::STK_Bool:
3811 return CK_IntegralToBoolean;
3812 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003813 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003814 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003815 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003816 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003817 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3818 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003819 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003820 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003821 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3822 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003823 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003824 case Type::STK_MemberPointer:
3825 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003826 }
3827 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003828
John McCall8cb679e2010-11-15 09:13:47 +00003829 case Type::STK_Floating:
3830 switch (DestTy->getScalarTypeKind()) {
3831 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003832 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003833 case Type::STK_Bool:
3834 return CK_FloatingToBoolean;
3835 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003836 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003837 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003838 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3839 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003840 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003841 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003842 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3843 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003844 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003845 case Type::STK_Pointer:
3846 llvm_unreachable("valid float->pointer cast?");
3847 case Type::STK_MemberPointer:
3848 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003849 }
3850 break;
3851
John McCall8cb679e2010-11-15 09:13:47 +00003852 case Type::STK_FloatingComplex:
3853 switch (DestTy->getScalarTypeKind()) {
3854 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003855 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003856 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003857 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003858 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003859 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003860 if (S.Context.hasSameType(ET, DestTy))
3861 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003862 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003863 return CK_FloatingCast;
3864 }
John McCall8cb679e2010-11-15 09:13:47 +00003865 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003866 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003867 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003868 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3869 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003870 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003871 case Type::STK_Pointer:
3872 llvm_unreachable("valid complex float->pointer cast?");
3873 case Type::STK_MemberPointer:
3874 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003875 }
3876 break;
3877
John McCall8cb679e2010-11-15 09:13:47 +00003878 case Type::STK_IntegralComplex:
3879 switch (DestTy->getScalarTypeKind()) {
3880 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003881 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003882 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003883 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003884 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003885 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003886 if (S.Context.hasSameType(ET, DestTy))
3887 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003888 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003889 return CK_IntegralCast;
3890 }
John McCall8cb679e2010-11-15 09:13:47 +00003891 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003892 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003893 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003894 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3895 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003896 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003897 case Type::STK_Pointer:
3898 llvm_unreachable("valid complex int->pointer cast?");
3899 case Type::STK_MemberPointer:
3900 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003901 }
3902 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003903 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003904
John McCalld7646252010-11-14 08:17:51 +00003905 llvm_unreachable("Unhandled scalar cast");
3906 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003907}
3908
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003909/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003910ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3911 QualType castType, Expr *castExpr,
3912 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003913 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003914 if (castExpr->getType() == Context.UnknownAnyTy)
3915 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3916
Sebastian Redl9f831db2009-07-25 15:41:38 +00003917 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003918 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003919 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003920 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003921 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003922
John McCall3aef3d82011-04-10 19:13:55 +00003923 assert(!castExpr->getType()->isPlaceholderType());
3924
John McCall7decc9e2010-11-18 06:31:45 +00003925 // We only support r-value casts in C.
3926 VK = VK_RValue;
3927
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003928 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3929 // type needs to be scalar.
3930 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003931 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003932 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3933 if (castExprRes.isInvalid())
3934 return ExprError();
3935 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003936
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003937 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003938 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003939 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003940 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003941
John Wiegley01296292011-04-08 18:41:53 +00003942 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3943 if (castExprRes.isInvalid())
3944 return ExprError();
3945 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003946
Eli Friedmane98194d2010-07-17 20:43:49 +00003947 if (RequireCompleteType(TyR.getBegin(), castType,
3948 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003949 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003950
Anders Carlssonef918ac2009-10-16 02:35:04 +00003951 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003952 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003953 (castType->isStructureType() || castType->isUnionType())) {
3954 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003955 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003956 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3957 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003958 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003959 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003960 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003961
Anders Carlsson525b76b2009-10-16 02:48:28 +00003962 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003963 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003964 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003965 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003966 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003967 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003968 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003969 castExpr->getType()) &&
3970 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003971 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3972 << castExpr->getSourceRange();
3973 break;
3974 }
3975 }
John Wiegley01296292011-04-08 18:41:53 +00003976 if (Field == FieldEnd) {
3977 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003978 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003979 return ExprError();
3980 }
John McCalle3027922010-08-25 11:45:40 +00003981 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00003982 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003984
Anders Carlsson525b76b2009-10-16 02:48:28 +00003985 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00003986 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00003987 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003988 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003989 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003990
John McCalld7646252010-11-14 08:17:51 +00003991 // The type we're casting to is known to be a scalar or vector.
3992
3993 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003994 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003995 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00003996 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003997 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003998 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003999 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004000 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004001
4002 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004003 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004004
Anton Yartsev28ccef72011-03-27 09:32:40 +00004005 if (castType->isVectorType()) {
4006 if (castType->getAs<VectorType>()->getVectorKind() ==
4007 VectorType::AltiVecVector &&
4008 (castExpr->getType()->isIntegerType() ||
4009 castExpr->getType()->isFloatingType())) {
4010 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004011 return Owned(castExpr);
4012 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4013 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004014 } else
John Wiegley01296292011-04-08 18:41:53 +00004015 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004016 }
John Wiegley01296292011-04-08 18:41:53 +00004017 if (castExpr->getType()->isVectorType()) {
4018 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4019 return ExprError();
4020 else
4021 return Owned(castExpr);
4022 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004023
John McCalld7646252010-11-14 08:17:51 +00004024 // The source and target types are both scalars, i.e.
4025 // - arithmetic types (fundamental, enum, and complex)
4026 // - all kinds of pointers
4027 // Note that member pointers were filtered out with C++, above.
4028
John Wiegley01296292011-04-08 18:41:53 +00004029 if (isa<ObjCSelectorExpr>(castExpr)) {
4030 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4031 return ExprError();
4032 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004033
John McCalld7646252010-11-14 08:17:51 +00004034 // If either type is a pointer, the other type has to be either an
4035 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004036 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004037 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004038 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004039 castExprType->isArithmeticType()) {
4040 Diag(castExpr->getLocStart(),
4041 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004042 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004043 return ExprError();
4044 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004045 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004046 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4047 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004048 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004049 return ExprError();
4050 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004051 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004052
John McCall31168b02011-06-15 23:02:42 +00004053 if (getLangOptions().ObjCAutoRefCount) {
4054 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4055 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4056 castType, castExpr, CCK_CStyleCast);
4057
4058 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4059 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4060 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4061 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4062 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4063 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4064 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4065 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004066 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004067 << castExprType << castType << AA_Casting
4068 << castExpr->getSourceRange();
4069
4070 return ExprError();
4071 }
4072 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004073 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004074 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4075 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004076 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004077 << castExprType << castType
4078 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004079 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004080 }
4081 }
4082
John Wiegley01296292011-04-08 18:41:53 +00004083 castExprRes = Owned(castExpr);
4084 Kind = PrepareScalarCast(*this, castExprRes, castType);
4085 if (castExprRes.isInvalid())
4086 return ExprError();
4087 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004088
John McCalld7646252010-11-14 08:17:51 +00004089 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004090 CheckCastAlign(castExpr, castType, TyR);
4091
John Wiegley01296292011-04-08 18:41:53 +00004092 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004093}
4094
Anders Carlsson525b76b2009-10-16 02:48:28 +00004095bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004096 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004097 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004098
Anders Carlssonde71adf2007-11-27 05:51:55 +00004099 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004100 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004101 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004102 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004103 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004104 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004105 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004106 } else
4107 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004108 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004109 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004110
John McCalle3027922010-08-25 11:45:40 +00004111 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004112 return false;
4113}
4114
John Wiegley01296292011-04-08 18:41:53 +00004115ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4116 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004117 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004118
Anders Carlsson43d70f82009-10-16 05:23:41 +00004119 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004120
Nate Begemanc8961a42009-06-27 22:05:55 +00004121 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4122 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004123 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004124 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4125 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004126 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004127 return ExprError();
4128 }
John McCalle3027922010-08-25 11:45:40 +00004129 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004130 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004131 }
4132
Nate Begemanbd956c42009-06-28 02:36:38 +00004133 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004134 // conversion will take place first from scalar to elt type, and then
4135 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004136 if (SrcTy->isPointerType())
4137 return Diag(R.getBegin(),
4138 diag::err_invalid_conversion_between_vector_and_scalar)
4139 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004140
4141 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004142 ExprResult CastExprRes = Owned(CastExpr);
4143 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4144 if (CastExprRes.isInvalid())
4145 return ExprError();
4146 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004147
John McCalle3027922010-08-25 11:45:40 +00004148 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004149 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004150}
4151
John McCalldadc5752010-08-24 06:29:42 +00004152ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004153Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4154 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004155 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004156 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004157 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004158
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004159 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4160 if (D.isInvalidType())
4161 return ExprError();
4162
4163 if (getLangOptions().CPlusPlus) {
4164 // Check that there are no default arguments (C++ only).
4165 CheckExtraCXXDefaultArguments(D);
4166 }
4167
4168 QualType castType = castTInfo->getType();
4169 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004170
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004171 bool isVectorLiteral = false;
4172
4173 // Check for an altivec or OpenCL literal,
4174 // i.e. all the elements are integer constants.
4175 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4176 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4177 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4178 if (PLE && PLE->getNumExprs() == 0) {
4179 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4180 return ExprError();
4181 }
4182 if (PE || PLE->getNumExprs() == 1) {
4183 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4184 if (!E->getType()->isVectorType())
4185 isVectorLiteral = true;
4186 }
4187 else
4188 isVectorLiteral = true;
4189 }
4190
4191 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4192 // then handle it as such.
4193 if (isVectorLiteral)
4194 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4195
Nate Begeman5ec4b312009-08-10 23:49:36 +00004196 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004197 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4198 // sequence of BinOp comma operators.
4199 if (isa<ParenListExpr>(castExpr)) {
4200 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4201 if (Result.isInvalid()) return ExprError();
4202 castExpr = Result.take();
4203 }
John McCallebe54742010-01-15 18:56:44 +00004204
John McCallb268a282010-08-23 23:25:46 +00004205 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004206}
4207
John McCalldadc5752010-08-24 06:29:42 +00004208ExprResult
John McCallebe54742010-01-15 18:56:44 +00004209Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004210 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004211 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004212 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004213 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004214 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004215 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4216 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004217 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004218 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004219 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004220
John McCallcf142162010-08-07 06:22:56 +00004221 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004222 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004223 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004224 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004225}
4226
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004227ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4228 SourceLocation RParenLoc, Expr *E,
4229 TypeSourceInfo *TInfo) {
4230 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4231 "Expected paren or paren list expression");
4232
4233 Expr **exprs;
4234 unsigned numExprs;
4235 Expr *subExpr;
4236 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4237 exprs = PE->getExprs();
4238 numExprs = PE->getNumExprs();
4239 } else {
4240 subExpr = cast<ParenExpr>(E)->getSubExpr();
4241 exprs = &subExpr;
4242 numExprs = 1;
4243 }
4244
4245 QualType Ty = TInfo->getType();
4246 assert(Ty->isVectorType() && "Expected vector type");
4247
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004248 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004249 const VectorType *VTy = Ty->getAs<VectorType>();
4250 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4251
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004252 // '(...)' form of vector initialization in AltiVec: the number of
4253 // initializers must be one or must match the size of the vector.
4254 // If a single value is specified in the initializer then it will be
4255 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004256 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004257 // The number of initializers must be one or must match the size of the
4258 // vector. If a single value is specified in the initializer then it will
4259 // be replicated to all the components of the vector
4260 if (numExprs == 1) {
4261 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4262 ExprResult Literal = Owned(exprs[0]);
4263 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4264 PrepareScalarCast(*this, Literal, ElemTy));
4265 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4266 }
4267 else if (numExprs < numElems) {
4268 Diag(E->getExprLoc(),
4269 diag::err_incorrect_number_of_vector_initializers);
4270 return ExprError();
4271 }
4272 else
4273 for (unsigned i = 0, e = numExprs; i != e; ++i)
4274 initExprs.push_back(exprs[i]);
4275 }
Tanya Lattner83559382011-07-15 23:07:01 +00004276 else {
4277 // For OpenCL, when the number of initializers is a single value,
4278 // it will be replicated to all components of the vector.
4279 if (getLangOptions().OpenCL &&
4280 VTy->getVectorKind() == VectorType::GenericVector &&
4281 numExprs == 1) {
4282 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4283 ExprResult Literal = Owned(exprs[0]);
4284 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4285 PrepareScalarCast(*this, Literal, ElemTy));
4286 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4287 }
4288
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004289 for (unsigned i = 0, e = numExprs; i != e; ++i)
4290 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004291 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004292 // FIXME: This means that pretty-printing the final AST will produce curly
4293 // braces instead of the original commas.
4294 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4295 &initExprs[0],
4296 initExprs.size(), RParenLoc);
4297 initE->setType(Ty);
4298 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4299}
4300
Nate Begeman5ec4b312009-08-10 23:49:36 +00004301/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4302/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004303ExprResult
John McCallb268a282010-08-23 23:25:46 +00004304Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004305 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4306 if (!E)
4307 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004308
John McCalldadc5752010-08-24 06:29:42 +00004309 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004310
Nate Begeman5ec4b312009-08-10 23:49:36 +00004311 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004312 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4313 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004314
John McCallb268a282010-08-23 23:25:46 +00004315 if (Result.isInvalid()) return ExprError();
4316
4317 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004318}
4319
John McCalldadc5752010-08-24 06:29:42 +00004320ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004321 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004322 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004323 unsigned nexprs = Val.size();
4324 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004325 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4326 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004327 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004328 expr = new (Context) ParenExpr(L, R, exprs[0]);
4329 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004330 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4331 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004332 return Owned(expr);
4333}
4334
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004335/// \brief Emit a specialized diagnostic when one expression is a null pointer
4336/// constant and the other is not a pointer.
4337bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4338 SourceLocation QuestionLoc) {
4339 Expr *NullExpr = LHS;
4340 Expr *NonPointerExpr = RHS;
4341 Expr::NullPointerConstantKind NullKind =
4342 NullExpr->isNullPointerConstant(Context,
4343 Expr::NPC_ValueDependentIsNotNull);
4344
4345 if (NullKind == Expr::NPCK_NotNull) {
4346 NullExpr = RHS;
4347 NonPointerExpr = LHS;
4348 NullKind =
4349 NullExpr->isNullPointerConstant(Context,
4350 Expr::NPC_ValueDependentIsNotNull);
4351 }
4352
4353 if (NullKind == Expr::NPCK_NotNull)
4354 return false;
4355
4356 if (NullKind == Expr::NPCK_ZeroInteger) {
4357 // In this case, check to make sure that we got here from a "NULL"
4358 // string in the source code.
4359 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004360 SourceLocation loc = NullExpr->getExprLoc();
4361 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004362 return false;
4363 }
4364
4365 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4366 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4367 << NonPointerExpr->getType() << DiagType
4368 << NonPointerExpr->getSourceRange();
4369 return true;
4370}
4371
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004372/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4373/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004374/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004375QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004376 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004377 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004378
John McCall3aef3d82011-04-10 19:13:55 +00004379 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004380 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004381 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004382
John McCall3aef3d82011-04-10 19:13:55 +00004383 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004384 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004385 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004386
Sebastian Redl1a99f442009-04-16 17:51:27 +00004387 // C++ is sufficiently different to merit its own checker.
4388 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004389 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004390
4391 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004392 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004393
John Wiegley01296292011-04-08 18:41:53 +00004394 Cond = UsualUnaryConversions(Cond.take());
4395 if (Cond.isInvalid())
4396 return QualType();
4397 LHS = UsualUnaryConversions(LHS.take());
4398 if (LHS.isInvalid())
4399 return QualType();
4400 RHS = UsualUnaryConversions(RHS.take());
4401 if (RHS.isInvalid())
4402 return QualType();
4403
4404 QualType CondTy = Cond.get()->getType();
4405 QualType LHSTy = LHS.get()->getType();
4406 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004407
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004408 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004409 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004410 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4411 // Throw an error if its not either.
4412 if (getLangOptions().OpenCL) {
4413 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004414 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004415 diag::err_typecheck_cond_expect_scalar_or_vector)
4416 << CondTy;
4417 return QualType();
4418 }
4419 }
4420 else {
John Wiegley01296292011-04-08 18:41:53 +00004421 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004422 << CondTy;
4423 return QualType();
4424 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004425 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426
Chris Lattnere2949f42008-01-06 22:42:25 +00004427 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004428 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004429 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004430
Nate Begemanabb5a732010-09-20 22:41:17 +00004431 // OpenCL: If the condition is a vector, and both operands are scalar,
4432 // attempt to implicity convert them to the vector type to act like the
4433 // built in select.
4434 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4435 // Both operands should be of scalar type.
4436 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004437 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004438 << CondTy;
4439 return QualType();
4440 }
4441 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004442 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004443 << CondTy;
4444 return QualType();
4445 }
4446 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004447 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4448 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004449 }
4450
Chris Lattnere2949f42008-01-06 22:42:25 +00004451 // If both operands have arithmetic type, do the usual arithmetic conversions
4452 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004453 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4454 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004455 if (LHS.isInvalid() || RHS.isInvalid())
4456 return QualType();
4457 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004458 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004459
Chris Lattnere2949f42008-01-06 22:42:25 +00004460 // If both operands are the same structure or union type, the result is that
4461 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004462 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4463 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004464 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004465 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004466 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004467 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004468 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004469 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004470
Chris Lattnere2949f42008-01-06 22:42:25 +00004471 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004472 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004473 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4474 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004475 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4476 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004477 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004478 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4479 << LHS.get()->getSourceRange();
4480 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4481 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004482 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004483 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004484 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4485 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004486 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004487 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004488 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004489 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004490 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004491 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004492 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004493 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4494 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004495 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004496 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004497
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004498 // All objective-c pointer type analysis is done here.
4499 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4500 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004501 if (LHS.isInvalid() || RHS.isInvalid())
4502 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004503 if (!compositeType.isNull())
4504 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004505
4506
Steve Naroff05efa972009-07-01 14:36:47 +00004507 // Handle block pointer types.
4508 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4509 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4510 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4511 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004512 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4513 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004514 return destType;
4515 }
4516 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004517 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004518 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004519 }
Steve Naroff05efa972009-07-01 14:36:47 +00004520 // We have 2 block pointer types.
4521 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4522 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004523 return LHSTy;
4524 }
Steve Naroff05efa972009-07-01 14:36:47 +00004525 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004526 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4527 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004528
Steve Naroff05efa972009-07-01 14:36:47 +00004529 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4530 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004531 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004532 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004533 // In this situation, we assume void* type. No especially good
4534 // reason, but this is what gcc does, and we do have to pick
4535 // to get a consistent AST.
4536 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004537 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4538 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004539 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004540 }
Steve Naroff05efa972009-07-01 14:36:47 +00004541 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004542 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4543 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004544 return LHSTy;
4545 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004546
Steve Naroff05efa972009-07-01 14:36:47 +00004547 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4548 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4549 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004550 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4551 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004552
4553 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4554 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4555 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004556 QualType destPointee
4557 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004558 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004559 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004560 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004561 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004562 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004563 return destType;
4564 }
4565 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004566 QualType destPointee
4567 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004568 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004569 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004570 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004571 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004572 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004573 return destType;
4574 }
4575
4576 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4577 // Two identical pointer types are always compatible.
4578 return LHSTy;
4579 }
4580 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4581 rhptee.getUnqualifiedType())) {
4582 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004583 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004584 // In this situation, we assume void* type. No especially good
4585 // reason, but this is what gcc does, and we do have to pick
4586 // to get a consistent AST.
4587 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004588 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4589 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004590 return incompatTy;
4591 }
4592 // The pointer types are compatible.
4593 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4594 // differently qualified versions of compatible types, the result type is
4595 // a pointer to an appropriately qualified version of the *composite*
4596 // type.
4597 // FIXME: Need to calculate the composite type.
4598 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004599 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4600 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004601 return LHSTy;
4602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
John McCalle84af4e2010-11-13 01:35:44 +00004604 // GCC compatibility: soften pointer/integer mismatch. Note that
4605 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004606 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4607 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004608 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4609 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004610 return RHSTy;
4611 }
4612 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4613 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004614 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4615 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004616 return LHSTy;
4617 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004618
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004619 // Emit a better diagnostic if one of the expressions is a null pointer
4620 // constant and the other is not a pointer type. In this case, the user most
4621 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004622 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004623 return QualType();
4624
Chris Lattnere2949f42008-01-06 22:42:25 +00004625 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004626 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004627 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004628 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004629}
4630
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004631/// FindCompositeObjCPointerType - Helper method to find composite type of
4632/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004633QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004634 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004635 QualType LHSTy = LHS.get()->getType();
4636 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004637
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004638 // Handle things like Class and struct objc_class*. Here we case the result
4639 // to the pseudo-builtin, because that will be implicitly cast back to the
4640 // redefinition type if an attempt is made to access its fields.
4641 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004642 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004643 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004644 return LHSTy;
4645 }
4646 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004647 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004648 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004649 return RHSTy;
4650 }
4651 // And the same for struct objc_object* / id
4652 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004653 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004654 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004655 return LHSTy;
4656 }
4657 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004658 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004659 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004660 return RHSTy;
4661 }
4662 // And the same for struct objc_selector* / SEL
4663 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004664 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004665 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004666 return LHSTy;
4667 }
4668 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004669 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004670 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004671 return RHSTy;
4672 }
4673 // Check constraints for Objective-C object pointers types.
4674 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004675
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004676 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4677 // Two identical object pointer types are always compatible.
4678 return LHSTy;
4679 }
4680 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4681 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4682 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004683
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004684 // If both operands are interfaces and either operand can be
4685 // assigned to the other, use that type as the composite
4686 // type. This allows
4687 // xxx ? (A*) a : (B*) b
4688 // where B is a subclass of A.
4689 //
4690 // Additionally, as for assignment, if either type is 'id'
4691 // allow silent coercion. Finally, if the types are
4692 // incompatible then make sure to use 'id' as the composite
4693 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004694
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004695 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4696 // It could return the composite type.
4697 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4698 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4699 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4700 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4701 } else if ((LHSTy->isObjCQualifiedIdType() ||
4702 RHSTy->isObjCQualifiedIdType()) &&
4703 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4704 // Need to handle "id<xx>" explicitly.
4705 // GCC allows qualified id and any Objective-C type to devolve to
4706 // id. Currently localizing to here until clear this should be
4707 // part of ObjCQualifiedIdTypesAreCompatible.
4708 compositeType = Context.getObjCIdType();
4709 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4710 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004711 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004712 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4713 ;
4714 else {
4715 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4716 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004717 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004718 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004719 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4720 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004721 return incompatTy;
4722 }
4723 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004724 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4725 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004726 return compositeType;
4727 }
4728 // Check Objective-C object pointer types and 'void *'
4729 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4730 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4731 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4732 QualType destPointee
4733 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4734 QualType destType = Context.getPointerType(destPointee);
4735 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004736 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004737 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004738 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004739 return destType;
4740 }
4741 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4742 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4743 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4744 QualType destPointee
4745 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4746 QualType destType = Context.getPointerType(destPointee);
4747 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004748 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004750 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004751 return destType;
4752 }
4753 return QualType();
4754}
4755
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004756/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004757/// ParenRange in parentheses.
4758static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004759 const PartialDiagnostic &Note,
4760 SourceRange ParenRange) {
4761 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4762 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4763 EndLoc.isValid()) {
4764 Self.Diag(Loc, Note)
4765 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4766 << FixItHint::CreateInsertion(EndLoc, ")");
4767 } else {
4768 // We can't display the parentheses, so just show the bare note.
4769 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004770 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004771}
4772
4773static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4774 return Opc >= BO_Mul && Opc <= BO_Shr;
4775}
4776
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004777/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4778/// expression, either using a built-in or overloaded operator,
4779/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4780static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4781 Expr **RHS) {
4782 E = E->IgnoreParenImpCasts();
4783 E = E->IgnoreConversionOperator();
4784 E = E->IgnoreParenImpCasts();
4785
4786 // Built-in binary operator.
4787 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4788 if (IsArithmeticOp(OP->getOpcode())) {
4789 *Opcode = OP->getOpcode();
4790 *RHS = OP->getRHS();
4791 return true;
4792 }
4793 }
4794
4795 // Overloaded operator.
4796 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4797 if (Call->getNumArgs() != 2)
4798 return false;
4799
4800 // Make sure this is really a binary operator that is safe to pass into
4801 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4802 OverloadedOperatorKind OO = Call->getOperator();
4803 if (OO < OO_Plus || OO > OO_Arrow)
4804 return false;
4805
4806 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4807 if (IsArithmeticOp(OpKind)) {
4808 *Opcode = OpKind;
4809 *RHS = Call->getArg(1);
4810 return true;
4811 }
4812 }
4813
4814 return false;
4815}
4816
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004817static bool IsLogicOp(BinaryOperatorKind Opc) {
4818 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4819}
4820
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004821/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4822/// or is a logical expression such as (x==y) which has int type, but is
4823/// commonly interpreted as boolean.
4824static bool ExprLooksBoolean(Expr *E) {
4825 E = E->IgnoreParenImpCasts();
4826
4827 if (E->getType()->isBooleanType())
4828 return true;
4829 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4830 return IsLogicOp(OP->getOpcode());
4831 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4832 return OP->getOpcode() == UO_LNot;
4833
4834 return false;
4835}
4836
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004837/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4838/// and binary operator are mixed in a way that suggests the programmer assumed
4839/// the conditional operator has higher precedence, for example:
4840/// "int x = a + someBinaryCondition ? 1 : 2".
4841static void DiagnoseConditionalPrecedence(Sema &Self,
4842 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004843 Expr *Condition,
4844 Expr *LHS,
4845 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004846 BinaryOperatorKind CondOpcode;
4847 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004848
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004849 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004850 return;
4851 if (!ExprLooksBoolean(CondRHS))
4852 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004853
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004854 // The condition is an arithmetic binary expression, with a right-
4855 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004856
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004857 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004858 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004859 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004860
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004861 SuggestParentheses(Self, OpLoc,
4862 Self.PDiag(diag::note_precedence_conditional_silence)
4863 << BinaryOperator::getOpcodeStr(CondOpcode),
4864 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004865
4866 SuggestParentheses(Self, OpLoc,
4867 Self.PDiag(diag::note_precedence_conditional_first),
4868 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004869}
4870
Steve Naroff83895f72007-09-16 03:34:24 +00004871/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004872/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004873ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004874 SourceLocation ColonLoc,
4875 Expr *CondExpr, Expr *LHSExpr,
4876 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004877 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4878 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004879 OpaqueValueExpr *opaqueValue = 0;
4880 Expr *commonExpr = 0;
4881 if (LHSExpr == 0) {
4882 commonExpr = CondExpr;
4883
4884 // We usually want to apply unary conversions *before* saving, except
4885 // in the special case of a C++ l-value conditional.
4886 if (!(getLangOptions().CPlusPlus
4887 && !commonExpr->isTypeDependent()
4888 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4889 && commonExpr->isGLValue()
4890 && commonExpr->isOrdinaryOrBitFieldObject()
4891 && RHSExpr->isOrdinaryOrBitFieldObject()
4892 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004893 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4894 if (commonRes.isInvalid())
4895 return ExprError();
4896 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004897 }
4898
4899 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4900 commonExpr->getType(),
4901 commonExpr->getValueKind(),
4902 commonExpr->getObjectKind());
4903 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004904 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004905
John McCall7decc9e2010-11-18 06:31:45 +00004906 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004907 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004908 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4909 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004910 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004911 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4912 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004913 return ExprError();
4914
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004915 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4916 RHS.get());
4917
John McCallc07a0c72011-02-17 10:25:35 +00004918 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004919 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4920 LHS.take(), ColonLoc,
4921 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004922
4923 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004924 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4925 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004926}
4927
John McCallaba90822011-01-31 23:13:11 +00004928// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004929// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004930// routine is it effectively iqnores the qualifiers on the top level pointee.
4931// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4932// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004933static Sema::AssignConvertType
4934checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4935 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4936 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004937
Steve Naroff1f4d7272007-05-11 04:00:31 +00004938 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004939 const Type *lhptee, *rhptee;
4940 Qualifiers lhq, rhq;
4941 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4942 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004943
John McCallaba90822011-01-31 23:13:11 +00004944 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004945
4946 // C99 6.5.16.1p1: This following citation is common to constraints
4947 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4948 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004949 Qualifiers lq;
4950
John McCall31168b02011-06-15 23:02:42 +00004951 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4952 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4953 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4954 // Ignore lifetime for further calculation.
4955 lhq.removeObjCLifetime();
4956 rhq.removeObjCLifetime();
4957 }
4958
John McCall4fff8f62011-02-01 00:10:29 +00004959 if (!lhq.compatiblyIncludes(rhq)) {
4960 // Treat address-space mismatches as fatal. TODO: address subspaces
4961 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4962 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4963
John McCall31168b02011-06-15 23:02:42 +00004964 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004965 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004966 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4967 .compatiblyIncludes(
4968 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004969 && (lhptee->isVoidType() || rhptee->isVoidType()))
4970 ; // keep old
4971
John McCall31168b02011-06-15 23:02:42 +00004972 // Treat lifetime mismatches as fatal.
4973 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4974 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4975
John McCall4fff8f62011-02-01 00:10:29 +00004976 // For GCC compatibility, other qualifier mismatches are treated
4977 // as still compatible in C.
4978 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4979 }
Steve Naroff3f597292007-05-11 22:18:03 +00004980
Mike Stump4e1f26a2009-02-19 03:04:26 +00004981 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4982 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004983 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004984 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004985 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004986 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004987
Chris Lattner0a788432008-01-03 22:56:36 +00004988 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004989 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004990 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004991 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004992
Chris Lattner0a788432008-01-03 22:56:36 +00004993 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004994 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004995 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004996
4997 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004998 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004999 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005000 }
John McCall4fff8f62011-02-01 00:10:29 +00005001
Mike Stump4e1f26a2009-02-19 03:04:26 +00005002 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005003 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005004 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5005 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005006 // Check if the pointee types are compatible ignoring the sign.
5007 // We explicitly check for char so that we catch "char" vs
5008 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005009 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005010 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005011 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005012 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005013
Chris Lattnerec3a1562009-10-17 20:33:28 +00005014 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005015 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005016 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005017 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005018
John McCall4fff8f62011-02-01 00:10:29 +00005019 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005020 // Types are compatible ignoring the sign. Qualifier incompatibility
5021 // takes priority over sign incompatibility because the sign
5022 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005023 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005024 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005025
John McCallaba90822011-01-31 23:13:11 +00005026 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005027 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005028
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005029 // If we are a multi-level pointer, it's possible that our issue is simply
5030 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5031 // the eventual target type is the same and the pointers have the same
5032 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005033 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005034 do {
John McCall4fff8f62011-02-01 00:10:29 +00005035 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5036 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005037 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005038
John McCall4fff8f62011-02-01 00:10:29 +00005039 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005040 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005041 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005042
Eli Friedman80160bd2009-03-22 23:59:44 +00005043 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005044 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005045 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005046 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005047}
5048
John McCallaba90822011-01-31 23:13:11 +00005049/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005050/// block pointer types are compatible or whether a block and normal pointer
5051/// are compatible. It is more restrict than comparing two function pointer
5052// types.
John McCallaba90822011-01-31 23:13:11 +00005053static Sema::AssignConvertType
5054checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5055 QualType rhsType) {
5056 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5057 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5058
Steve Naroff081c7422008-09-04 15:10:53 +00005059 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005060
Steve Naroff081c7422008-09-04 15:10:53 +00005061 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005062 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5063 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005064
John McCallaba90822011-01-31 23:13:11 +00005065 // In C++, the types have to match exactly.
5066 if (S.getLangOptions().CPlusPlus)
5067 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005068
John McCallaba90822011-01-31 23:13:11 +00005069 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005070
Steve Naroff081c7422008-09-04 15:10:53 +00005071 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005072 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5073 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005074
John McCallaba90822011-01-31 23:13:11 +00005075 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5076 return Sema::IncompatibleBlockPointer;
5077
Steve Naroff081c7422008-09-04 15:10:53 +00005078 return ConvTy;
5079}
5080
John McCallaba90822011-01-31 23:13:11 +00005081/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005082/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005083static Sema::AssignConvertType
5084checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5085 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5086 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5087
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005088 if (lhsType->isObjCBuiltinType()) {
5089 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005090 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5091 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005092 return Sema::IncompatiblePointer;
5093 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005094 }
5095 if (rhsType->isObjCBuiltinType()) {
5096 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005097 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5098 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005099 return Sema::IncompatiblePointer;
5100 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005101 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005102 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005103 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005104 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005105 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005106
John McCallaba90822011-01-31 23:13:11 +00005107 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5108 return Sema::CompatiblePointerDiscardsQualifiers;
5109
5110 if (S.Context.typesAreCompatible(lhsType, rhsType))
5111 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005112 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005113 return Sema::IncompatibleObjCQualifiedId;
5114 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005115}
5116
John McCall29600e12010-11-16 02:32:08 +00005117Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005118Sema::CheckAssignmentConstraints(SourceLocation Loc,
5119 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005120 // Fake up an opaque expression. We don't actually care about what
5121 // cast operations are required, so if CheckAssignmentConstraints
5122 // adds casts to this they'll be wasted, but fortunately that doesn't
5123 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005124 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005125 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005126 CastKind K = CK_Invalid;
5127
5128 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5129}
5130
Mike Stump4e1f26a2009-02-19 03:04:26 +00005131/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5132/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005133/// pointers. Here are some objectionable examples that GCC considers warnings:
5134///
5135/// int a, *pint;
5136/// short *pshort;
5137/// struct foo *pfoo;
5138///
5139/// pint = pshort; // warning: assignment from incompatible pointer type
5140/// a = pint; // warning: assignment makes integer from pointer without a cast
5141/// pint = a; // warning: assignment makes pointer from integer without a cast
5142/// pint = pfoo; // warning: assignment from incompatible pointer type
5143///
5144/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005145/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005146///
John McCall8cb679e2010-11-15 09:13:47 +00005147/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005148Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005149Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005150 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005151 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005152 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005153
Chris Lattnera52c2f22008-01-04 23:18:45 +00005154 // Get canonical types. We're not formatting these types, just comparing
5155 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005156 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5157 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005158
John McCalle5255932011-01-31 22:28:28 +00005159 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005160 if (lhsType == rhsType) {
5161 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005162 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005163 }
5164
Douglas Gregor6b754842008-10-28 00:22:11 +00005165 // If the left-hand side is a reference type, then we are in a
5166 // (rare!) case where we've allowed the use of references in C,
5167 // e.g., as a parameter type in a built-in function. In this case,
5168 // just make sure that the type referenced is compatible with the
5169 // right-hand side type. The caller is responsible for adjusting
5170 // lhsType so that the resulting expression does not have reference
5171 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005172 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005173 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5174 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005175 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005176 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005177 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005178 }
John McCalle5255932011-01-31 22:28:28 +00005179
Nate Begemanbd956c42009-06-28 02:36:38 +00005180 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5181 // to the same ExtVector type.
5182 if (lhsType->isExtVectorType()) {
5183 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005184 return Incompatible;
5185 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005186 // CK_VectorSplat does T -> vector T, so first cast to the
5187 // element type.
5188 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5189 if (elType != rhsType) {
5190 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005191 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005192 }
5193 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005194 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005195 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005196 }
Mike Stump11289f42009-09-09 15:08:12 +00005197
John McCalle5255932011-01-31 22:28:28 +00005198 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005199 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005200 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005201 // Allow assignments of an AltiVec vector type to an equivalent GCC
5202 // vector type and vice versa
5203 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5204 Kind = CK_BitCast;
5205 return Compatible;
5206 }
5207
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005208 // If we are allowing lax vector conversions, and LHS and RHS are both
5209 // vectors, the total size only needs to be the same. This is a bitcast;
5210 // no bits are changed but the result type is different.
5211 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005212 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005213 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005214 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005215 }
Chris Lattner881a2122008-01-04 23:32:24 +00005216 }
5217 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005218 }
Eli Friedman3360d892008-05-30 18:07:22 +00005219
John McCalle5255932011-01-31 22:28:28 +00005220 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005221 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005222 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005223 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005224 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005225 }
Eli Friedman3360d892008-05-30 18:07:22 +00005226
John McCalle5255932011-01-31 22:28:28 +00005227 // Conversions to normal pointers.
5228 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5229 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005230 if (isa<PointerType>(rhsType)) {
5231 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005232 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005233 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005234
John McCalle5255932011-01-31 22:28:28 +00005235 // int -> T*
5236 if (rhsType->isIntegerType()) {
5237 Kind = CK_IntegralToPointer; // FIXME: null?
5238 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005239 }
John McCalle5255932011-01-31 22:28:28 +00005240
5241 // C pointers are not compatible with ObjC object pointers,
5242 // with two exceptions:
5243 if (isa<ObjCObjectPointerType>(rhsType)) {
5244 // - conversions to void*
5245 if (lhsPointer->getPointeeType()->isVoidType()) {
5246 Kind = CK_AnyPointerToObjCPointerCast;
5247 return Compatible;
5248 }
5249
5250 // - conversions from 'Class' to the redefinition type
5251 if (rhsType->isObjCClassType() &&
5252 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005253 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005254 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005255 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005256
John McCalle5255932011-01-31 22:28:28 +00005257 Kind = CK_BitCast;
5258 return IncompatiblePointer;
5259 }
5260
5261 // U^ -> void*
5262 if (rhsType->getAs<BlockPointerType>()) {
5263 if (lhsPointer->getPointeeType()->isVoidType()) {
5264 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005265 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005266 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005267 }
John McCalle5255932011-01-31 22:28:28 +00005268
Steve Naroff081c7422008-09-04 15:10:53 +00005269 return Incompatible;
5270 }
5271
John McCalle5255932011-01-31 22:28:28 +00005272 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005273 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005274 // U^ -> T^
5275 if (rhsType->isBlockPointerType()) {
5276 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005277 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005278 }
5279
5280 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005281 if (rhsType->isIntegerType()) {
5282 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005283 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005284 }
5285
John McCalle5255932011-01-31 22:28:28 +00005286 // id -> T^
5287 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5288 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005289 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005290 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005291
John McCalle5255932011-01-31 22:28:28 +00005292 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005293 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005294 if (RHSPT->getPointeeType()->isVoidType()) {
5295 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005296 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005297 }
John McCall8cb679e2010-11-15 09:13:47 +00005298
Chris Lattnera52c2f22008-01-04 23:18:45 +00005299 return Incompatible;
5300 }
5301
John McCalle5255932011-01-31 22:28:28 +00005302 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005303 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005304 // A* -> B*
5305 if (rhsType->isObjCObjectPointerType()) {
5306 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005307 Sema::AssignConvertType result =
5308 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5309 if (getLangOptions().ObjCAutoRefCount &&
5310 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005311 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5312 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005313 return result;
John McCalle5255932011-01-31 22:28:28 +00005314 }
5315
5316 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005317 if (rhsType->isIntegerType()) {
5318 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005319 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005320 }
5321
John McCalle5255932011-01-31 22:28:28 +00005322 // In general, C pointers are not compatible with ObjC object pointers,
5323 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005324 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005325 // - conversions from 'void*'
5326 if (rhsType->isVoidPointerType()) {
5327 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005328 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005329 }
5330
5331 // - conversions to 'Class' from its redefinition type
5332 if (lhsType->isObjCClassType() &&
5333 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5334 Kind = CK_BitCast;
5335 return Compatible;
5336 }
5337
5338 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005339 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005340 }
John McCalle5255932011-01-31 22:28:28 +00005341
5342 // T^ -> A*
5343 if (rhsType->isBlockPointerType()) {
5344 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005345 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005346 }
5347
Steve Naroff7cae42b2009-07-10 23:34:53 +00005348 return Incompatible;
5349 }
John McCalle5255932011-01-31 22:28:28 +00005350
5351 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005352 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005353 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005354 if (lhsType == Context.BoolTy) {
5355 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005356 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005357 }
Eli Friedman3360d892008-05-30 18:07:22 +00005358
John McCalle5255932011-01-31 22:28:28 +00005359 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005360 if (lhsType->isIntegerType()) {
5361 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005362 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005363 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005364
Chris Lattnera52c2f22008-01-04 23:18:45 +00005365 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005366 }
John McCalle5255932011-01-31 22:28:28 +00005367
5368 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005369 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005370 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005371 if (lhsType == Context.BoolTy) {
5372 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005373 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005374 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005375
John McCalle5255932011-01-31 22:28:28 +00005376 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005377 if (lhsType->isIntegerType()) {
5378 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005379 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005380 }
5381
Steve Naroff7cae42b2009-07-10 23:34:53 +00005382 return Incompatible;
5383 }
Eli Friedman3360d892008-05-30 18:07:22 +00005384
John McCalle5255932011-01-31 22:28:28 +00005385 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005386 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005387 if (Context.typesAreCompatible(lhsType, rhsType)) {
5388 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005389 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005390 }
Bill Wendling216423b2007-05-30 06:30:29 +00005391 }
John McCalle5255932011-01-31 22:28:28 +00005392
Steve Naroff98cf3e92007-06-06 18:38:38 +00005393 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005394}
5395
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005396/// \brief Constructs a transparent union from an expression that is
5397/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005398static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005399 QualType UnionType, FieldDecl *Field) {
5400 // Build an initializer list that designates the appropriate member
5401 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005402 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005403 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005404 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005405 SourceLocation());
5406 Initializer->setType(UnionType);
5407 Initializer->setInitializedFieldInUnion(Field);
5408
5409 // Build a compound literal constructing a value of the transparent
5410 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005411 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005412 EResult = S.Owned(
5413 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5414 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005415}
5416
5417Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005418Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5419 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005420
Mike Stump11289f42009-09-09 15:08:12 +00005421 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005422 // transparent_union GCC extension.
5423 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005424 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005425 return Incompatible;
5426
5427 // The field to initialize within the transparent union.
5428 RecordDecl *UD = UT->getDecl();
5429 FieldDecl *InitField = 0;
5430 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005431 for (RecordDecl::field_iterator it = UD->field_begin(),
5432 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005433 it != itend; ++it) {
5434 if (it->getType()->isPointerType()) {
5435 // If the transparent union contains a pointer type, we allow:
5436 // 1) void pointer
5437 // 2) null pointer constant
5438 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005439 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005440 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005441 InitField = *it;
5442 break;
5443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
John Wiegley01296292011-04-08 18:41:53 +00005445 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005446 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005447 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005448 InitField = *it;
5449 break;
5450 }
5451 }
5452
John McCall8cb679e2010-11-15 09:13:47 +00005453 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005454 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005455 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005456 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005457 InitField = *it;
5458 break;
5459 }
5460 }
5461
5462 if (!InitField)
5463 return Incompatible;
5464
John Wiegley01296292011-04-08 18:41:53 +00005465 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005466 return Compatible;
5467}
5468
Chris Lattner9bad62c2008-01-04 18:04:52 +00005469Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005470Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005471 if (getLangOptions().CPlusPlus) {
5472 if (!lhsType->isRecordType()) {
5473 // C++ 5.17p3: If the left operand is not of class type, the
5474 // expression is implicitly converted (C++ 4) to the
5475 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005476 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5477 lhsType.getUnqualifiedType(),
5478 AA_Assigning);
5479 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005480 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005481 Sema::AssignConvertType result = Compatible;
5482 if (getLangOptions().ObjCAutoRefCount &&
5483 !CheckObjCARCUnavailableWeakConversion(lhsType, rExpr.get()->getType()))
5484 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005485 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005486 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005487 }
5488
5489 // FIXME: Currently, we fall through and treat C++ classes like C
5490 // structures.
John McCall34376a62010-12-04 03:47:34 +00005491 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005492
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005493 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5494 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005495 if ((lhsType->isPointerType() ||
5496 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005497 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005498 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005499 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005500 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005501 return Compatible;
5502 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005503
Chris Lattnere6dcd502007-10-16 02:55:40 +00005504 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005505 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005506 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005507 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005508 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005509 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005510 if (!lhsType->isReferenceType()) {
5511 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5512 if (rExpr.isInvalid())
5513 return Incompatible;
5514 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005515
John McCall8cb679e2010-11-15 09:13:47 +00005516 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005517 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005518 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005519
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005520 // C99 6.5.16.1p2: The value of the right operand is converted to the
5521 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005522 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5523 // so that we can use references in built-in functions even in C.
5524 // The getNonReferenceType() call makes sure that the resulting expression
5525 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005526 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5527 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005528 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005529}
5530
John Wiegley01296292011-04-08 18:41:53 +00005531QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005532 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005533 << lex.get()->getType() << rex.get()->getType()
5534 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005535 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005536}
5537
Eli Friedman1408bc92011-06-23 18:10:35 +00005538QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5539 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005540 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005541 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005542 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005543 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005544 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005545 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005546
Nate Begeman191a6b12008-07-14 18:02:46 +00005547 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005548 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005549 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005550
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005551 // Handle the case of equivalent AltiVec and GCC vector types
5552 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5553 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005554 if (lhsType->isExtVectorType()) {
5555 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5556 return lhsType;
5557 }
5558
5559 if (!isCompAssign)
5560 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005561 return rhsType;
5562 }
5563
Eli Friedman1408bc92011-06-23 18:10:35 +00005564 if (getLangOptions().LaxVectorConversions &&
5565 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5566 // If we are allowing lax vector conversions, and LHS and RHS are both
5567 // vectors, the total size only needs to be the same. This is a
5568 // bitcast; no bits are changed but the result type is different.
5569 // FIXME: Should we really be allowing this?
5570 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5571 return lhsType;
5572 }
5573
Nate Begemanbd956c42009-06-28 02:36:38 +00005574 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5575 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5576 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005577 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005578 swapped = true;
5579 std::swap(rex, lex);
5580 std::swap(rhsType, lhsType);
5581 }
Mike Stump11289f42009-09-09 15:08:12 +00005582
Nate Begeman886448d2009-06-28 19:12:57 +00005583 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005584 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005585 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005586 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005587 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5588 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005589 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005590 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005591 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005592 if (swapped) std::swap(rex, lex);
5593 return lhsType;
5594 }
5595 }
5596 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5597 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005598 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5599 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005600 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005601 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005602 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005603 if (swapped) std::swap(rex, lex);
5604 return lhsType;
5605 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005606 }
5607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608
Nate Begeman886448d2009-06-28 19:12:57 +00005609 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005610 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005611 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005612 << lex.get()->getType() << rex.get()->getType()
5613 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005614 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005615}
5616
Chris Lattnerfaa54172010-01-12 21:23:57 +00005617QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005618 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5619 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005620 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005621
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005622 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005623 if (lex.isInvalid() || rex.isInvalid())
5624 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005625
John Wiegley01296292011-04-08 18:41:53 +00005626 if (!lex.get()->getType()->isArithmeticType() ||
5627 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005628 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005629
Chris Lattnerfaa54172010-01-12 21:23:57 +00005630 // Check for division by zero.
5631 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005632 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5633 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5634 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005635
Chris Lattnerfaa54172010-01-12 21:23:57 +00005636 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005637}
5638
Chris Lattnerfaa54172010-01-12 21:23:57 +00005639QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005640 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5641 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5642 if (lex.get()->getType()->hasIntegerRepresentation() &&
5643 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005644 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005645 return InvalidOperands(Loc, lex, rex);
5646 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005647
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005648 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005649 if (lex.isInvalid() || rex.isInvalid())
5650 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005651
John Wiegley01296292011-04-08 18:41:53 +00005652 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005653 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005654
Chris Lattnerfaa54172010-01-12 21:23:57 +00005655 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005656 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5657 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5658 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005659
Chris Lattnerfaa54172010-01-12 21:23:57 +00005660 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005661}
5662
Chandler Carruthc9332212011-06-27 08:02:19 +00005663/// \brief Diagnose invalid arithmetic on two void pointers.
5664static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5665 Expr *LHS, Expr *RHS) {
5666 S.Diag(Loc, S.getLangOptions().CPlusPlus
5667 ? diag::err_typecheck_pointer_arith_void_type
5668 : diag::ext_gnu_void_ptr)
5669 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5670}
5671
5672/// \brief Diagnose invalid arithmetic on a void pointer.
5673static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5674 Expr *Pointer) {
5675 S.Diag(Loc, S.getLangOptions().CPlusPlus
5676 ? diag::err_typecheck_pointer_arith_void_type
5677 : diag::ext_gnu_void_ptr)
5678 << 0 /* one pointer */ << Pointer->getSourceRange();
5679}
5680
5681/// \brief Diagnose invalid arithmetic on two function pointers.
5682static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5683 Expr *LHS, Expr *RHS) {
5684 assert(LHS->getType()->isAnyPointerType());
5685 assert(RHS->getType()->isAnyPointerType());
5686 S.Diag(Loc, S.getLangOptions().CPlusPlus
5687 ? diag::err_typecheck_pointer_arith_function_type
5688 : diag::ext_gnu_ptr_func_arith)
5689 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5690 // We only show the second type if it differs from the first.
5691 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5692 RHS->getType())
5693 << RHS->getType()->getPointeeType()
5694 << LHS->getSourceRange() << RHS->getSourceRange();
5695}
5696
5697/// \brief Diagnose invalid arithmetic on a function pointer.
5698static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5699 Expr *Pointer) {
5700 assert(Pointer->getType()->isAnyPointerType());
5701 S.Diag(Loc, S.getLangOptions().CPlusPlus
5702 ? diag::err_typecheck_pointer_arith_function_type
5703 : diag::ext_gnu_ptr_func_arith)
5704 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5705 << 0 /* one pointer, so only one type */
5706 << Pointer->getSourceRange();
5707}
5708
5709/// \brief Check the validity of an arithmetic pointer operand.
5710///
5711/// If the operand has pointer type, this code will check for pointer types
5712/// which are invalid in arithmetic operations. These will be diagnosed
5713/// appropriately, including whether or not the use is supported as an
5714/// extension.
5715///
5716/// \returns True when the operand is valid to use (even if as an extension).
5717static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5718 Expr *Operand) {
5719 if (!Operand->getType()->isAnyPointerType()) return true;
5720
5721 QualType PointeeTy = Operand->getType()->getPointeeType();
5722 if (PointeeTy->isVoidType()) {
5723 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5724 return !S.getLangOptions().CPlusPlus;
5725 }
5726 if (PointeeTy->isFunctionType()) {
5727 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5728 return !S.getLangOptions().CPlusPlus;
5729 }
5730
5731 if ((Operand->getType()->isPointerType() &&
5732 !Operand->getType()->isDependentType()) ||
5733 Operand->getType()->isObjCObjectPointerType()) {
5734 QualType PointeeTy = Operand->getType()->getPointeeType();
5735 if (S.RequireCompleteType(
5736 Loc, PointeeTy,
5737 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5738 << PointeeTy << Operand->getSourceRange()))
5739 return false;
5740 }
5741
5742 return true;
5743}
5744
5745/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5746/// operands.
5747///
5748/// This routine will diagnose any invalid arithmetic on pointer operands much
5749/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5750/// for emitting a single diagnostic even for operations where both LHS and RHS
5751/// are (potentially problematic) pointers.
5752///
5753/// \returns True when the operand is valid to use (even if as an extension).
5754static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5755 Expr *LHS, Expr *RHS) {
5756 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5757 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5758 if (!isLHSPointer && !isRHSPointer) return true;
5759
5760 QualType LHSPointeeTy, RHSPointeeTy;
5761 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5762 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5763
5764 // Check for arithmetic on pointers to incomplete types.
5765 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5766 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5767 if (isLHSVoidPtr || isRHSVoidPtr) {
5768 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5769 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5770 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5771
5772 return !S.getLangOptions().CPlusPlus;
5773 }
5774
5775 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5776 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5777 if (isLHSFuncPtr || isRHSFuncPtr) {
5778 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5779 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5780 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5781
5782 return !S.getLangOptions().CPlusPlus;
5783 }
5784
5785 Expr *Operands[] = { LHS, RHS };
5786 for (unsigned i = 0; i < 2; ++i) {
5787 Expr *Operand = Operands[i];
5788 if ((Operand->getType()->isPointerType() &&
5789 !Operand->getType()->isDependentType()) ||
5790 Operand->getType()->isObjCObjectPointerType()) {
5791 QualType PointeeTy = Operand->getType()->getPointeeType();
5792 if (S.RequireCompleteType(
5793 Loc, PointeeTy,
5794 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5795 << PointeeTy << Operand->getSourceRange()))
5796 return false;
5797 }
5798 }
5799 return true;
5800}
5801
Chris Lattnerfaa54172010-01-12 21:23:57 +00005802QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005803 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5804 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005805 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005806 if (CompLHSTy) *CompLHSTy = compType;
5807 return compType;
5808 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005809
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005810 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005811 if (lex.isInvalid() || rex.isInvalid())
5812 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005813
Steve Naroffe4718892007-04-27 18:30:00 +00005814 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005815 if (lex.get()->getType()->isArithmeticType() &&
5816 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005817 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005818 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005819 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005820
Eli Friedman8e122982008-05-18 18:08:51 +00005821 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005822 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005823 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005824 std::swap(PExp, IExp);
5825
Steve Naroff6b712a72009-07-14 18:25:06 +00005826 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005827 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005828 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5829 return QualType();
5830
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005831 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005832
Chris Lattner12bdebb2009-04-24 23:50:08 +00005833 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005834 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005835 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5836 << PointeeTy << PExp->getSourceRange();
5837 return QualType();
5838 }
Mike Stump11289f42009-09-09 15:08:12 +00005839
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005840 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005841 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005842 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005843 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005844 if (LHSTy->isPromotableIntegerType())
5845 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005846 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005847 *CompLHSTy = LHSTy;
5848 }
Eli Friedman8e122982008-05-18 18:08:51 +00005849 return PExp->getType();
5850 }
5851 }
5852
Chris Lattner326f7572008-11-18 01:30:42 +00005853 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005854}
5855
Chris Lattner2a3569b2008-04-07 05:30:13 +00005856// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005857QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005858 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005859 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005860 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005861 if (CompLHSTy) *CompLHSTy = compType;
5862 return compType;
5863 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005864
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005865 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005866 if (lex.isInvalid() || rex.isInvalid())
5867 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005868
Chris Lattner4d62f422007-12-09 21:53:25 +00005869 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005870
Chris Lattner4d62f422007-12-09 21:53:25 +00005871 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005872 if (lex.get()->getType()->isArithmeticType() &&
5873 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005874 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005875 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005876 }
Mike Stump11289f42009-09-09 15:08:12 +00005877
Chris Lattner4d62f422007-12-09 21:53:25 +00005878 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005879 if (lex.get()->getType()->isAnyPointerType()) {
5880 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005881
Chris Lattner12bdebb2009-04-24 23:50:08 +00005882 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005883 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005884 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005885 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005886 return QualType();
5887 }
Mike Stump11289f42009-09-09 15:08:12 +00005888
Chris Lattner4d62f422007-12-09 21:53:25 +00005889 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005890 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005891 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5892 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005893
John Wiegley01296292011-04-08 18:41:53 +00005894 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5895 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005896 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005897
Chris Lattner4d62f422007-12-09 21:53:25 +00005898 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005899 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005900 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005901
Eli Friedman168fe152009-05-16 13:54:38 +00005902 if (getLangOptions().CPlusPlus) {
5903 // Pointee types must be the same: C++ [expr.add]
5904 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5905 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005906 << lex.get()->getType() << rex.get()->getType()
5907 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005908 return QualType();
5909 }
5910 } else {
5911 // Pointee types must be compatible C99 6.5.6p3
5912 if (!Context.typesAreCompatible(
5913 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5914 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5915 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005916 << lex.get()->getType() << rex.get()->getType()
5917 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005918 return QualType();
5919 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005920 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005921
Chandler Carruthc9332212011-06-27 08:02:19 +00005922 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5923 lex.get(), rex.get()))
5924 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005925
John Wiegley01296292011-04-08 18:41:53 +00005926 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005927 return Context.getPointerDiffType();
5928 }
5929 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005930
Chris Lattner326f7572008-11-18 01:30:42 +00005931 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005932}
5933
Douglas Gregor0bf31402010-10-08 23:50:27 +00005934static bool isScopedEnumerationType(QualType T) {
5935 if (const EnumType *ET = dyn_cast<EnumType>(T))
5936 return ET->getDecl()->isScoped();
5937 return false;
5938}
5939
John Wiegley01296292011-04-08 18:41:53 +00005940static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005941 SourceLocation Loc, unsigned Opc,
5942 QualType LHSTy) {
5943 llvm::APSInt Right;
5944 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005945 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005946 return;
5947
5948 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005949 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005950 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005951 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005952 return;
5953 }
5954 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005955 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005956 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005957 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005958 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005959 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005960 return;
5961 }
5962 if (Opc != BO_Shl)
5963 return;
5964
5965 // When left shifting an ICE which is signed, we can check for overflow which
5966 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5967 // integers have defined behavior modulo one more than the maximum value
5968 // representable in the result type, so never warn for those.
5969 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005970 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005971 LHSTy->hasUnsignedIntegerRepresentation())
5972 return;
5973 llvm::APInt ResultBits =
5974 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5975 if (LeftBits.uge(ResultBits))
5976 return;
5977 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5978 Result = Result.shl(Right);
5979
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005980 // Print the bit representation of the signed integer as an unsigned
5981 // hexadecimal number.
5982 llvm::SmallString<40> HexResult;
5983 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5984
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005985 // If we are only missing a sign bit, this is less likely to result in actual
5986 // bugs -- if the result is cast back to an unsigned type, it will have the
5987 // expected value. Thus we place this behind a different warning that can be
5988 // turned off separately if needed.
5989 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005990 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5991 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005992 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005993 return;
5994 }
5995
5996 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005997 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005998 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005999}
6000
Chris Lattner2a3569b2008-04-07 05:30:13 +00006001// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00006002QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006003 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006004 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006005 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6006 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006007 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006008
Douglas Gregor0bf31402010-10-08 23:50:27 +00006009 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6010 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006011 if (isScopedEnumerationType(lex.get()->getType()) ||
6012 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006013 return InvalidOperands(Loc, lex, rex);
6014 }
6015
Nate Begemane46ee9a2009-10-25 02:26:48 +00006016 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00006017 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006018 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006019
Chris Lattner5c11c412007-12-12 05:47:28 +00006020 // Shifts don't perform usual arithmetic conversions, they just do integer
6021 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006022
John McCall57cdd882010-12-16 19:28:59 +00006023 // For the LHS, do usual unary conversions, but then reset them away
6024 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006025 ExprResult old_lex = lex;
6026 lex = UsualUnaryConversions(lex.take());
6027 if (lex.isInvalid())
6028 return QualType();
6029 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006030 if (isCompAssign) lex = old_lex;
6031
6032 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006033 rex = UsualUnaryConversions(rex.take());
6034 if (rex.isInvalid())
6035 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006036
Ryan Flynnf53fab82009-08-07 16:20:20 +00006037 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006038 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006039
Chris Lattner5c11c412007-12-12 05:47:28 +00006040 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006041 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006042}
6043
Chandler Carruth17773fc2010-07-10 12:30:03 +00006044static bool IsWithinTemplateSpecialization(Decl *D) {
6045 if (DeclContext *DC = D->getDeclContext()) {
6046 if (isa<ClassTemplateSpecializationDecl>(DC))
6047 return true;
6048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6049 return FD->isFunctionTemplateSpecialization();
6050 }
6051 return false;
6052}
6053
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006054// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00006055QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006056 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006057 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006058
Chris Lattner9a152e22009-12-05 05:40:13 +00006059 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006060 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006061 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006062
John Wiegley01296292011-04-08 18:41:53 +00006063 QualType lType = lex.get()->getType();
6064 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006065
John Wiegley01296292011-04-08 18:41:53 +00006066 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6067 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006068 QualType LHSStrippedType = LHSStripped->getType();
6069 QualType RHSStrippedType = RHSStripped->getType();
6070
Douglas Gregor1beec452011-03-12 01:48:56 +00006071
6072
Chandler Carruth712563b2011-02-17 08:37:06 +00006073 // Two different enums will raise a warning when compared.
6074 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6075 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6076 if (LHSEnumType->getDecl()->getIdentifier() &&
6077 RHSEnumType->getDecl()->getIdentifier() &&
6078 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6079 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6080 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006081 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006082 }
6083 }
6084 }
6085
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006086 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006087 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006088 !lex.get()->getLocStart().isMacroID() &&
6089 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006090 // For non-floating point types, check for self-comparisons of the form
6091 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6092 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006093 //
6094 // NOTE: Don't warn about comparison expressions resulting from macro
6095 // expansion. Also don't warn about comparisons which are only self
6096 // comparisons within a template specialization. The warnings should catch
6097 // obvious cases in the definition of the template anyways. The idea is to
6098 // warn when the typed comparison operator will always evaluate to the same
6099 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006100 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006101 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006102 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006103 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006104 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006105 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006106 << (Opc == BO_EQ
6107 || Opc == BO_LE
6108 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006109 } else if (lType->isArrayType() && rType->isArrayType() &&
6110 !DRL->getDecl()->getType()->isReferenceType() &&
6111 !DRR->getDecl()->getType()->isReferenceType()) {
6112 // what is it always going to eval to?
6113 char always_evals_to;
6114 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006115 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006116 always_evals_to = 0; // false
6117 break;
John McCalle3027922010-08-25 11:45:40 +00006118 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006119 always_evals_to = 1; // true
6120 break;
6121 default:
6122 // best we can say is 'a constant'
6123 always_evals_to = 2; // e.g. array1 <= array2
6124 break;
6125 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006126 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006127 << 1 // array
6128 << always_evals_to);
6129 }
6130 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006131 }
Mike Stump11289f42009-09-09 15:08:12 +00006132
Chris Lattner222b8bd2009-03-08 19:39:53 +00006133 if (isa<CastExpr>(LHSStripped))
6134 LHSStripped = LHSStripped->IgnoreParenCasts();
6135 if (isa<CastExpr>(RHSStripped))
6136 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006137
Chris Lattner222b8bd2009-03-08 19:39:53 +00006138 // Warn about comparisons against a string constant (unless the other
6139 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006140 Expr *literalString = 0;
6141 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006142 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006143 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006144 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006145 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006146 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006147 } else if ((isa<StringLiteral>(RHSStripped) ||
6148 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006149 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006150 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006151 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006152 literalStringStripped = RHSStripped;
6153 }
6154
6155 if (literalString) {
6156 std::string resultComparison;
6157 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006158 case BO_LT: resultComparison = ") < 0"; break;
6159 case BO_GT: resultComparison = ") > 0"; break;
6160 case BO_LE: resultComparison = ") <= 0"; break;
6161 case BO_GE: resultComparison = ") >= 0"; break;
6162 case BO_EQ: resultComparison = ") == 0"; break;
6163 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006164 default: assert(false && "Invalid comparison operator");
6165 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006166
Ted Kremenek3427fac2011-02-23 01:52:04 +00006167 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006168 PDiag(diag::warn_stringcompare)
6169 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006170 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006171 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006172 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006173
Douglas Gregorec170db2010-06-08 19:50:34 +00006174 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006175 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006176 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006177 if (lex.isInvalid() || rex.isInvalid())
6178 return QualType();
6179 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006180 else {
John Wiegley01296292011-04-08 18:41:53 +00006181 lex = UsualUnaryConversions(lex.take());
6182 if (lex.isInvalid())
6183 return QualType();
6184
6185 rex = UsualUnaryConversions(rex.take());
6186 if (rex.isInvalid())
6187 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006188 }
6189
John Wiegley01296292011-04-08 18:41:53 +00006190 lType = lex.get()->getType();
6191 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006192
Douglas Gregorca63811b2008-11-19 03:25:36 +00006193 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006194 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006195
Chris Lattnerb620c342007-08-26 01:18:55 +00006196 if (isRelational) {
6197 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006198 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006199 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006200 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006201 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006202 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006203
Chris Lattnerb620c342007-08-26 01:18:55 +00006204 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006205 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006206 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006207
John Wiegley01296292011-04-08 18:41:53 +00006208 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006209 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006210 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006211 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006212
Douglas Gregorf267edd2010-06-15 21:38:40 +00006213 // All of the following pointer-related warnings are GCC extensions, except
6214 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006215 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006216 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006217 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006218 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006219 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006220
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006221 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006222 if (LCanPointeeTy == RCanPointeeTy)
6223 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006224 if (!isRelational &&
6225 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6226 // Valid unless comparison between non-null pointer and function pointer
6227 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006228 // In a SFINAE context, we treat this as a hard error to maintain
6229 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006230 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6231 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006232 Diag(Loc,
6233 isSFINAEContext()?
6234 diag::err_typecheck_comparison_of_fptr_to_void
6235 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006236 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006237
6238 if (isSFINAEContext())
6239 return QualType();
6240
John Wiegley01296292011-04-08 18:41:53 +00006241 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006242 return ResultTy;
6243 }
6244 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006245
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006246 // C++ [expr.rel]p2:
6247 // [...] Pointer conversions (4.10) and qualification
6248 // conversions (4.4) are performed on pointer operands (or on
6249 // a pointer operand and a null pointer constant) to bring
6250 // them to their composite pointer type. [...]
6251 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006252 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006253 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006254 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006255 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006256 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006257 if (T.isNull()) {
6258 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006259 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006260 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006261 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006262 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006263 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006264 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006265 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006266 }
6267
John Wiegley01296292011-04-08 18:41:53 +00006268 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6269 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006270 return ResultTy;
6271 }
Eli Friedman16c209612009-08-23 00:27:47 +00006272 // C99 6.5.9p2 and C99 6.5.8p2
6273 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6274 RCanPointeeTy.getUnqualifiedType())) {
6275 // Valid unless a relational comparison of function pointers
6276 if (isRelational && LCanPointeeTy->isFunctionType()) {
6277 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006278 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006279 }
6280 } else if (!isRelational &&
6281 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6282 // Valid unless comparison between non-null pointer and function pointer
6283 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6284 && !LHSIsNull && !RHSIsNull) {
6285 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006286 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006287 }
6288 } else {
6289 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006290 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006291 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006292 }
John McCall7684dde2011-03-11 04:25:25 +00006293 if (LCanPointeeTy != RCanPointeeTy) {
6294 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006295 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006296 else
John Wiegley01296292011-04-08 18:41:53 +00006297 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006298 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006299 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
Sebastian Redl576fd422009-05-10 18:38:11 +00006302 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006303 // Comparison of nullptr_t with itself.
6304 if (lType->isNullPtrType() && rType->isNullPtrType())
6305 return ResultTy;
6306
Mike Stump11289f42009-09-09 15:08:12 +00006307 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006308 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006309 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006310 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006311 (!isRelational &&
6312 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006313 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006314 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006315 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006316 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006317 return ResultTy;
6318 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006319 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006320 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006321 (!isRelational &&
6322 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006323 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006324 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006325 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006326 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006327 return ResultTy;
6328 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006329
6330 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006331 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006332 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6333 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006334 // In addition, pointers to members can be compared, or a pointer to
6335 // member and a null pointer constant. Pointer to member conversions
6336 // (4.11) and qualification conversions (4.4) are performed to bring
6337 // them to a common type. If one operand is a null pointer constant,
6338 // the common type is the type of the other operand. Otherwise, the
6339 // common type is a pointer to member type similar (4.4) to the type
6340 // of one of the operands, with a cv-qualification signature (4.4)
6341 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006342 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006343 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006344 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006345 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006346 if (T.isNull()) {
6347 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006348 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006349 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006350 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006351 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006352 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006353 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006354 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006355 }
Mike Stump11289f42009-09-09 15:08:12 +00006356
John Wiegley01296292011-04-08 18:41:53 +00006357 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6358 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006359 return ResultTy;
6360 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006361
6362 // Handle scoped enumeration types specifically, since they don't promote
6363 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006364 if (lex.get()->getType()->isEnumeralType() &&
6365 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006366 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006367 }
Mike Stump11289f42009-09-09 15:08:12 +00006368
Steve Naroff081c7422008-09-04 15:10:53 +00006369 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006370 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006371 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6372 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006373
Steve Naroff081c7422008-09-04 15:10:53 +00006374 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006375 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006376 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006377 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006378 }
John Wiegley01296292011-04-08 18:41:53 +00006379 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006380 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006381 }
John Wiegley01296292011-04-08 18:41:53 +00006382
Steve Naroffe18f94c2008-09-28 01:11:11 +00006383 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006384 if (!isRelational
6385 && ((lType->isBlockPointerType() && rType->isPointerType())
6386 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006387 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006388 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006389 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006390 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006391 ->getPointeeType()->isVoidType())))
6392 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006393 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006394 }
John McCall7684dde2011-03-11 04:25:25 +00006395 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006396 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006397 else
John Wiegley01296292011-04-08 18:41:53 +00006398 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006399 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006400 }
Steve Naroff081c7422008-09-04 15:10:53 +00006401
John McCall7684dde2011-03-11 04:25:25 +00006402 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6403 const PointerType *LPT = lType->getAs<PointerType>();
6404 const PointerType *RPT = rType->getAs<PointerType>();
6405 if (LPT || RPT) {
6406 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6407 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006408
Steve Naroff753567f2008-11-17 19:49:16 +00006409 if (!LPtrToVoid && !RPtrToVoid &&
6410 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006411 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006412 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006413 }
John McCall7684dde2011-03-11 04:25:25 +00006414 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006415 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006416 else
John Wiegley01296292011-04-08 18:41:53 +00006417 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006418 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006419 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006420 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006421 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006422 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006423 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006424 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006425 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006426 else
John Wiegley01296292011-04-08 18:41:53 +00006427 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006428 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006429 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006430 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006431 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6432 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006433 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006434 bool isError = false;
6435 if ((LHSIsNull && lType->isIntegerType()) ||
6436 (RHSIsNull && rType->isIntegerType())) {
6437 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006438 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006439 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006440 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006441 else if (getLangOptions().CPlusPlus) {
6442 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6443 isError = true;
6444 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006445 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006446
Chris Lattnerd99bd522009-08-23 00:03:44 +00006447 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006448 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006449 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006450 if (isError)
6451 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006452 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006453
6454 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006455 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006456 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006457 else
John Wiegley01296292011-04-08 18:41:53 +00006458 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006459 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006460 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006461 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006462
Steve Naroff4b191572008-09-04 16:56:14 +00006463 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006464 if (!isRelational && RHSIsNull
6465 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006466 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006467 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006468 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006469 if (!isRelational && LHSIsNull
6470 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006471 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006472 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006473 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006474
Chris Lattner326f7572008-11-18 01:30:42 +00006475 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006476}
6477
Nate Begeman191a6b12008-07-14 18:02:46 +00006478/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006479/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006480/// like a scalar comparison, a vector comparison produces a vector of integer
6481/// types.
John Wiegley01296292011-04-08 18:41:53 +00006482QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006483 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006484 bool isRelational) {
6485 // Check to make sure we're operating on vectors of the same type and width,
6486 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006487 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006488 if (vType.isNull())
6489 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006490
John Wiegley01296292011-04-08 18:41:53 +00006491 QualType lType = lex.get()->getType();
6492 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
Anton Yartsev530deb92011-03-27 15:36:07 +00006494 // If AltiVec, the comparison results in a numeric type, i.e.
6495 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006496 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006497 return Context.getLogicalOperationType();
6498
Nate Begeman191a6b12008-07-14 18:02:46 +00006499 // For non-floating point types, check for self-comparisons of the form
6500 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6501 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006502 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006503 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6504 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006505 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006506 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006507 PDiag(diag::warn_comparison_always)
6508 << 0 // self-
6509 << 2 // "a constant"
6510 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006511 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Nate Begeman191a6b12008-07-14 18:02:46 +00006513 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006514 if (!isRelational && lType->hasFloatingRepresentation()) {
6515 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006516 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006517 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006518
Nate Begeman191a6b12008-07-14 18:02:46 +00006519 // Return the type for the comparison, which is the same as vector type for
6520 // integer vectors, or an integer type of identical size and number of
6521 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006522 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006523 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006524
John McCall9dd450b2009-09-21 23:43:11 +00006525 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006526 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006527 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006528 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006529 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006530 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6531
Mike Stump4e1f26a2009-02-19 03:04:26 +00006532 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006533 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006534 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6535}
6536
Steve Naroff218bc2b2007-05-04 21:54:46 +00006537inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006538 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6539 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6540 if (lex.get()->getType()->hasIntegerRepresentation() &&
6541 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006542 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006543
6544 return InvalidOperands(Loc, lex, rex);
6545 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006546
John Wiegley01296292011-04-08 18:41:53 +00006547 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6548 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6549 if (lexResult.isInvalid() || rexResult.isInvalid())
6550 return QualType();
6551 lex = lexResult.take();
6552 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006553
John Wiegley01296292011-04-08 18:41:53 +00006554 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6555 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006556 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006557 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006558}
6559
Steve Naroff218bc2b2007-05-04 21:54:46 +00006560inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006561 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006562
6563 // Diagnose cases where the user write a logical and/or but probably meant a
6564 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6565 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006566 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6567 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006568 // Don't warn in macros or template instantiations.
6569 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006570 // If the RHS can be constant folded, and if it constant folds to something
6571 // that isn't 0 or 1 (which indicate a potential logical operation that
6572 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006573 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006574 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006575 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6576 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6577 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6578 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6579 << rex.get()->getSourceRange()
6580 << (Opc == BO_LAnd ? "&&" : "||")
6581 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006582 }
6583 }
Chris Lattner8406c512010-07-13 19:41:32 +00006584
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006585 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006586 lex = UsualUnaryConversions(lex.take());
6587 if (lex.isInvalid())
6588 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006589
John Wiegley01296292011-04-08 18:41:53 +00006590 rex = UsualUnaryConversions(rex.take());
6591 if (rex.isInvalid())
6592 return QualType();
6593
6594 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006595 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006596
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006597 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006598 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006599
John McCall4a2429a2010-06-04 00:29:51 +00006600 // The following is safe because we only use this method for
6601 // non-overloadable operands.
6602
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006603 // C++ [expr.log.and]p1
6604 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006605 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006606 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6607 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006608 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006609 lex = move(lexRes);
6610
6611 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6612 if (rexRes.isInvalid())
6613 return InvalidOperands(Loc, lex, rex);
6614 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006615
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006616 // C++ [expr.log.and]p2
6617 // C++ [expr.log.or]p2
6618 // The result is a bool.
6619 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006620}
6621
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006622/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6623/// is a read-only property; return true if so. A readonly property expression
6624/// depends on various declarations and thus must be treated specially.
6625///
Mike Stump11289f42009-09-09 15:08:12 +00006626static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006627 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6628 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006629 if (PropExpr->isImplicitProperty()) return false;
6630
6631 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6632 QualType BaseType = PropExpr->isSuperReceiver() ?
6633 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006634 PropExpr->getBase()->getType();
6635
John McCallb7bd14f2010-12-02 01:19:52 +00006636 if (const ObjCObjectPointerType *OPT =
6637 BaseType->getAsObjCInterfacePointerType())
6638 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6639 if (S.isPropertyReadonly(PDecl, IFace))
6640 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006641 }
6642 return false;
6643}
6644
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006645static bool IsConstProperty(Expr *E, Sema &S) {
6646 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6647 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6648 if (PropExpr->isImplicitProperty()) return false;
6649
6650 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6651 QualType T = PDecl->getType();
6652 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006653 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006654 CanQualType CT = S.Context.getCanonicalType(T);
6655 return CT.isConstQualified();
6656 }
6657 return false;
6658}
6659
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006660static bool IsReadonlyMessage(Expr *E, Sema &S) {
6661 if (E->getStmtClass() != Expr::MemberExprClass)
6662 return false;
6663 const MemberExpr *ME = cast<MemberExpr>(E);
6664 NamedDecl *Member = ME->getMemberDecl();
6665 if (isa<FieldDecl>(Member)) {
6666 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6667 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6668 return false;
6669 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6670 }
6671 return false;
6672}
6673
Chris Lattner30bd3272008-11-18 01:22:49 +00006674/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6675/// emit an error and return true. If so, return false.
6676static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006677 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006678 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006679 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006680 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6681 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006682 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6683 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006684 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6685 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006686 if (IsLV == Expr::MLV_Valid)
6687 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
Chris Lattner30bd3272008-11-18 01:22:49 +00006689 unsigned Diag = 0;
6690 bool NeedType = false;
6691 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006692 case Expr::MLV_ConstQualified:
6693 Diag = diag::err_typecheck_assign_const;
6694
John McCalld4631322011-06-17 06:42:21 +00006695 // In ARC, use some specialized diagnostics for occasions where we
6696 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006697 if (S.getLangOptions().ObjCAutoRefCount) {
6698 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6699 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6700 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6701
John McCalld4631322011-06-17 06:42:21 +00006702 // Use the normal diagnostic if it's pseudo-__strong but the
6703 // user actually wrote 'const'.
6704 if (var->isARCPseudoStrong() &&
6705 (!var->getTypeSourceInfo() ||
6706 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6707 // There are two pseudo-strong cases:
6708 // - self
John McCall31168b02011-06-15 23:02:42 +00006709 ObjCMethodDecl *method = S.getCurMethodDecl();
6710 if (method && var == method->getSelfDecl())
6711 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006712
6713 // - fast enumeration variables
6714 else
John McCall31168b02011-06-15 23:02:42 +00006715 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006716
John McCall31168b02011-06-15 23:02:42 +00006717 SourceRange Assign;
6718 if (Loc != OrigLoc)
6719 Assign = SourceRange(OrigLoc, OrigLoc);
6720 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6721 // We need to preserve the AST regardless, so migration tool
6722 // can do its job.
6723 return false;
6724 }
6725 }
6726 }
6727
6728 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006729 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006730 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6731 NeedType = true;
6732 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006733 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006734 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6735 NeedType = true;
6736 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006737 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006738 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6739 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006740 case Expr::MLV_Valid:
6741 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006742 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006743 case Expr::MLV_MemberFunction:
6744 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006745 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6746 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006747 case Expr::MLV_IncompleteType:
6748 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006749 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006750 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006751 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006752 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006753 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6754 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006755 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006756 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6757 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006758 case Expr::MLV_ReadonlyProperty:
6759 Diag = diag::error_readonly_property_assignment;
6760 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006761 case Expr::MLV_NoSetterProperty:
6762 Diag = diag::error_nosetter_property_assignment;
6763 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006764 case Expr::MLV_InvalidMessageExpression:
6765 Diag = diag::error_readonly_message_assignment;
6766 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006767 case Expr::MLV_SubObjCPropertySetting:
6768 Diag = diag::error_no_subobject_property_setting;
6769 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006770 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006771
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006772 SourceRange Assign;
6773 if (Loc != OrigLoc)
6774 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006775 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006776 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006777 else
Mike Stump11289f42009-09-09 15:08:12 +00006778 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006779 return true;
6780}
6781
6782
6783
6784// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006785QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006786 SourceLocation Loc,
6787 QualType CompoundType) {
6788 // Verify that LHS is a modifiable lvalue, and emit error if not.
6789 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006790 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006791
6792 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006793 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006794 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006795 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006796 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006797 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006798 if (LHS->getObjectKind() == OK_ObjCProperty) {
6799 ExprResult LHSResult = Owned(LHS);
6800 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6801 if (LHSResult.isInvalid())
6802 return QualType();
6803 LHS = LHSResult.take();
6804 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006805 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006806 if (RHS.isInvalid())
6807 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006808 // Special case of NSObject attributes on c-style pointer types.
6809 if (ConvTy == IncompatiblePointer &&
6810 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006811 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006812 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006813 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006814 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006815
John McCall7decc9e2010-11-18 06:31:45 +00006816 if (ConvTy == Compatible &&
6817 getLangOptions().ObjCNonFragileABI &&
6818 LHSType->isObjCObjectType())
6819 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6820 << LHSType;
6821
Chris Lattnerea714382008-08-21 18:04:13 +00006822 // If the RHS is a unary plus or minus, check to see if they = and + are
6823 // right next to each other. If so, the user may have typo'd "x =+ 4"
6824 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006825 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006826 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6827 RHSCheck = ICE->getSubExpr();
6828 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006829 if ((UO->getOpcode() == UO_Plus ||
6830 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006831 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006832 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006833 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6834 // And there is a space or other character before the subexpr of the
6835 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006836 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6837 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006838 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006839 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006840 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006841 }
Chris Lattnerea714382008-08-21 18:04:13 +00006842 }
John McCall31168b02011-06-15 23:02:42 +00006843
6844 if (ConvTy == Compatible) {
6845 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6846 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006847 else if (getLangOptions().ObjCAutoRefCount)
6848 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006849 }
Chris Lattnerea714382008-08-21 18:04:13 +00006850 } else {
6851 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006852 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006853 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006854
Chris Lattner326f7572008-11-18 01:30:42 +00006855 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006856 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006857 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006858
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006859 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006860 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006861 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006862
Steve Naroff98cf3e92007-06-06 18:38:38 +00006863 // C99 6.5.16p3: The type of an assignment expression is the type of the
6864 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006865 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006866 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6867 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006868 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006869 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006870 return (getLangOptions().CPlusPlus
6871 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006872}
6873
Chris Lattner326f7572008-11-18 01:30:42 +00006874// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006875static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006876 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006877 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006878
John McCall3aef3d82011-04-10 19:13:55 +00006879 LHS = S.CheckPlaceholderExpr(LHS.take());
6880 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006881 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006882 return QualType();
6883
John McCall73d36182010-10-12 07:14:40 +00006884 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6885 // operands, but not unary promotions.
6886 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006887
John McCall34376a62010-12-04 03:47:34 +00006888 // So we treat the LHS as a ignored value, and in C++ we allow the
6889 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006890 LHS = S.IgnoredValueConversions(LHS.take());
6891 if (LHS.isInvalid())
6892 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006893
6894 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006895 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6896 if (RHS.isInvalid())
6897 return QualType();
6898 if (!RHS.get()->getType()->isVoidType())
6899 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006900 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006901
John Wiegley01296292011-04-08 18:41:53 +00006902 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006903}
6904
Steve Naroff7a5af782007-07-13 16:58:59 +00006905/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6906/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006907static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6908 ExprValueKind &VK,
6909 SourceLocation OpLoc,
6910 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006911 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006912 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006913
Chris Lattner6b0cf142008-11-21 07:05:48 +00006914 QualType ResType = Op->getType();
6915 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006916
John McCall4bc41ae2010-11-18 19:01:18 +00006917 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006918 // Decrement of bool is not allowed.
6919 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006920 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006921 return QualType();
6922 }
6923 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006924 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006925 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006926 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006927 } else if (ResType->isAnyPointerType()) {
6928 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006929
Chris Lattner6b0cf142008-11-21 07:05:48 +00006930 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006931 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006932 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006933
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006934 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006935 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6936 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006937 << PointeeTy << Op->getSourceRange();
6938 return QualType();
6939 }
Eli Friedman090addd2010-01-03 00:20:48 +00006940 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006941 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006942 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006943 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006944 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006945 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006946 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006947 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6948 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006949 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6950 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006951 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006952 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006953 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006954 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006955 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006956 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006957 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006958 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006959 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006960 // In C++, a prefix increment is the same type as the operand. Otherwise
6961 // (in C or with postfix), the increment is the unqualified type of the
6962 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006963 if (isPrefix && S.getLangOptions().CPlusPlus) {
6964 VK = VK_LValue;
6965 return ResType;
6966 } else {
6967 VK = VK_RValue;
6968 return ResType.getUnqualifiedType();
6969 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006970}
6971
John Wiegley01296292011-04-08 18:41:53 +00006972ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006973 assert(E->getValueKind() == VK_LValue &&
6974 E->getObjectKind() == OK_ObjCProperty);
6975 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6976
Douglas Gregor33823722011-06-11 01:09:30 +00006977 QualType T = E->getType();
6978 QualType ReceiverType;
6979 if (PRE->isObjectReceiver())
6980 ReceiverType = PRE->getBase()->getType();
6981 else if (PRE->isSuperReceiver())
6982 ReceiverType = PRE->getSuperReceiverType();
6983 else
6984 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6985
John McCall34376a62010-12-04 03:47:34 +00006986 ExprValueKind VK = VK_RValue;
6987 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006988 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006989 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006990 T = getMessageSendResultType(ReceiverType, GetterMethod,
6991 PRE->isClassReceiver(),
6992 PRE->isSuperReceiver());
6993 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006994 }
6995 else {
6996 Diag(PRE->getLocation(), diag::err_getter_not_found)
6997 << PRE->getBase()->getType();
6998 }
John McCall34376a62010-12-04 03:47:34 +00006999 }
Douglas Gregor33823722011-06-11 01:09:30 +00007000
7001 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007002 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007003
7004 ExprResult Result = MaybeBindToTemporary(E);
7005 if (!Result.isInvalid())
7006 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007007
7008 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007009}
7010
John Wiegley01296292011-04-08 18:41:53 +00007011void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
7012 assert(LHS.get()->getValueKind() == VK_LValue &&
7013 LHS.get()->getObjectKind() == OK_ObjCProperty);
7014 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007015
John McCall31168b02011-06-15 23:02:42 +00007016 bool Consumed = false;
7017
John Wiegley01296292011-04-08 18:41:53 +00007018 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007019 // If using property-dot syntax notation for assignment, and there is a
7020 // setter, RHS expression is being passed to the setter argument. So,
7021 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007022 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007023 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7024 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007025 Consumed = (getLangOptions().ObjCAutoRefCount &&
7026 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007027
7028 // Otherwise, if the getter returns an l-value, just call that.
7029 } else {
John Wiegley01296292011-04-08 18:41:53 +00007030 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007031 ExprValueKind VK = Expr::getValueKindForType(Result);
7032 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007033 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7034 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007035 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007036 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007037 }
John McCall31168b02011-06-15 23:02:42 +00007038 } else if (getLangOptions().ObjCAutoRefCount) {
7039 const ObjCMethodDecl *setter
7040 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7041 if (setter) {
7042 ObjCMethodDecl::param_iterator P = setter->param_begin();
7043 LHSTy = (*P)->getType();
7044 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7045 }
John McCall34376a62010-12-04 03:47:34 +00007046 }
7047
John McCall31168b02011-06-15 23:02:42 +00007048 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7049 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007050 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007051 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007052 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007053 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007054 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007055 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7056 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7057 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007058 }
7059}
7060
7061
Anders Carlsson806700f2008-02-01 07:15:58 +00007062/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007063/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007064/// where the declaration is needed for type checking. We only need to
7065/// handle cases when the expression references a function designator
7066/// or is an lvalue. Here are some examples:
7067/// - &(x) => x
7068/// - &*****f => f for f a function designator.
7069/// - &s.xx => s
7070/// - &s.zz[1].yy -> s, if zz is an array
7071/// - *(x + 1) -> x, if x is an array
7072/// - &"123"[2] -> 0
7073/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007074static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007075 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007076 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007077 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007078 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007079 // If this is an arrow operator, the address is an offset from
7080 // the base's value, so the object the base refers to is
7081 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007082 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007083 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007084 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007085 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007086 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007087 // FIXME: This code shouldn't be necessary! We should catch the implicit
7088 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007089 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7090 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7091 if (ICE->getSubExpr()->getType()->isArrayType())
7092 return getPrimaryDecl(ICE->getSubExpr());
7093 }
7094 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007095 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007096 case Stmt::UnaryOperatorClass: {
7097 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007098
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007099 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007100 case UO_Real:
7101 case UO_Imag:
7102 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007103 return getPrimaryDecl(UO->getSubExpr());
7104 default:
7105 return 0;
7106 }
7107 }
Steve Naroff47500512007-04-19 23:00:49 +00007108 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007109 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007110 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007111 // If the result of an implicit cast is an l-value, we care about
7112 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007113 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007114 default:
7115 return 0;
7116 }
7117}
7118
7119/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007120/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007121/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007122/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007123/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007124/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007125/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007126static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7127 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007128 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007129 return S.Context.DependentTy;
7130 if (OrigOp->getType() == S.Context.OverloadTy)
7131 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007132 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7133 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007134 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7135 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7136 << OrigOp->getSourceRange();
7137 return QualType();
7138 }
John McCall8d08b9b2010-08-27 09:08:28 +00007139
John McCall2979fe02011-04-12 00:42:48 +00007140 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007141
John McCall8d08b9b2010-08-27 09:08:28 +00007142 // Make sure to ignore parentheses in subsequent checks
7143 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007144
John McCall4bc41ae2010-11-18 19:01:18 +00007145 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007146 // Implement C99-only parts of addressof rules.
7147 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007148 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007149 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7150 // (assuming the deref expression is valid).
7151 return uOp->getSubExpr()->getType();
7152 }
7153 // Technically, there should be a check for array subscript
7154 // expressions here, but the result of one is always an lvalue anyway.
7155 }
John McCallf3a88602011-02-03 08:15:49 +00007156 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007157 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007158
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007159 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007160 bool sfinae = S.isSFINAEContext();
7161 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7162 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007163 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007164 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007165 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007166 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007167 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007168 } else if (lval == Expr::LV_MemberFunction) {
7169 // If it's an instance method, make a member pointer.
7170 // The expression must have exactly the form &A::foo.
7171
7172 // If the underlying expression isn't a decl ref, give up.
7173 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007174 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007175 << OrigOp->getSourceRange();
7176 return QualType();
7177 }
7178 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7179 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7180
7181 // The id-expression was parenthesized.
7182 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007183 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007184 << OrigOp->getSourceRange();
7185
7186 // The method was named without a qualifier.
7187 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007188 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007189 << op->getSourceRange();
7190 }
7191
John McCall4bc41ae2010-11-18 19:01:18 +00007192 return S.Context.getMemberPointerType(op->getType(),
7193 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007194 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007195 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007196 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007197 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007198 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007199 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007200 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007201 return QualType();
7202 }
John McCall086a4642010-11-24 05:12:34 +00007203 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007204 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007205 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007206 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007207 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007208 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007209 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007210 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007211 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007212 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007213 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007214 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007215 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007216 << "property expression" << op->getSourceRange();
7217 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007218 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007219 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007220 // with the register storage-class specifier.
7221 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007222 // in C++ it is not error to take address of a register
7223 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007224 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007225 !S.getLangOptions().CPlusPlus) {
7226 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007227 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007228 return QualType();
7229 }
John McCalld14a8642009-11-21 08:51:07 +00007230 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007231 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007232 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007233 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007234 // Could be a pointer to member, though, if there is an explicit
7235 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007236 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007237 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007238 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007239 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007240 S.Diag(OpLoc,
7241 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007242 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007243 return QualType();
7244 }
Mike Stump11289f42009-09-09 15:08:12 +00007245
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007246 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7247 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007248 return S.Context.getMemberPointerType(op->getType(),
7249 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007250 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007251 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007252 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007253 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007254 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007255
Eli Friedmance7f9002009-05-16 23:27:50 +00007256 if (lval == Expr::LV_IncompleteVoidType) {
7257 // Taking the address of a void variable is technically illegal, but we
7258 // allow it in cases which are otherwise valid.
7259 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007260 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007261 }
7262
Steve Naroff47500512007-04-19 23:00:49 +00007263 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007264 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007265 return S.Context.getObjCObjectPointerType(op->getType());
7266 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007267}
7268
Chris Lattner9156f1b2010-07-05 19:17:26 +00007269/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007270static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7271 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007272 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007273 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007274
John Wiegley01296292011-04-08 18:41:53 +00007275 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7276 if (ConvResult.isInvalid())
7277 return QualType();
7278 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007279 QualType OpTy = Op->getType();
7280 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007281
7282 if (isa<CXXReinterpretCastExpr>(Op)) {
7283 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7284 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7285 Op->getSourceRange());
7286 }
7287
Chris Lattner9156f1b2010-07-05 19:17:26 +00007288 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7289 // is an incomplete type or void. It would be possible to warn about
7290 // dereferencing a void pointer, but it's completely well-defined, and such a
7291 // warning is unlikely to catch any mistakes.
7292 if (const PointerType *PT = OpTy->getAs<PointerType>())
7293 Result = PT->getPointeeType();
7294 else if (const ObjCObjectPointerType *OPT =
7295 OpTy->getAs<ObjCObjectPointerType>())
7296 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007297 else {
John McCall3aef3d82011-04-10 19:13:55 +00007298 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007299 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007300 if (PR.take() != Op)
7301 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007302 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007303
Chris Lattner9156f1b2010-07-05 19:17:26 +00007304 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007305 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007306 << OpTy << Op->getSourceRange();
7307 return QualType();
7308 }
John McCall4bc41ae2010-11-18 19:01:18 +00007309
7310 // Dereferences are usually l-values...
7311 VK = VK_LValue;
7312
7313 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007314 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007315 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007316
7317 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007318}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007319
John McCalle3027922010-08-25 11:45:40 +00007320static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007321 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007322 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007323 switch (Kind) {
7324 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007325 case tok::periodstar: Opc = BO_PtrMemD; break;
7326 case tok::arrowstar: Opc = BO_PtrMemI; break;
7327 case tok::star: Opc = BO_Mul; break;
7328 case tok::slash: Opc = BO_Div; break;
7329 case tok::percent: Opc = BO_Rem; break;
7330 case tok::plus: Opc = BO_Add; break;
7331 case tok::minus: Opc = BO_Sub; break;
7332 case tok::lessless: Opc = BO_Shl; break;
7333 case tok::greatergreater: Opc = BO_Shr; break;
7334 case tok::lessequal: Opc = BO_LE; break;
7335 case tok::less: Opc = BO_LT; break;
7336 case tok::greaterequal: Opc = BO_GE; break;
7337 case tok::greater: Opc = BO_GT; break;
7338 case tok::exclaimequal: Opc = BO_NE; break;
7339 case tok::equalequal: Opc = BO_EQ; break;
7340 case tok::amp: Opc = BO_And; break;
7341 case tok::caret: Opc = BO_Xor; break;
7342 case tok::pipe: Opc = BO_Or; break;
7343 case tok::ampamp: Opc = BO_LAnd; break;
7344 case tok::pipepipe: Opc = BO_LOr; break;
7345 case tok::equal: Opc = BO_Assign; break;
7346 case tok::starequal: Opc = BO_MulAssign; break;
7347 case tok::slashequal: Opc = BO_DivAssign; break;
7348 case tok::percentequal: Opc = BO_RemAssign; break;
7349 case tok::plusequal: Opc = BO_AddAssign; break;
7350 case tok::minusequal: Opc = BO_SubAssign; break;
7351 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7352 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7353 case tok::ampequal: Opc = BO_AndAssign; break;
7354 case tok::caretequal: Opc = BO_XorAssign; break;
7355 case tok::pipeequal: Opc = BO_OrAssign; break;
7356 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007357 }
7358 return Opc;
7359}
7360
John McCalle3027922010-08-25 11:45:40 +00007361static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007362 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007363 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007364 switch (Kind) {
7365 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007366 case tok::plusplus: Opc = UO_PreInc; break;
7367 case tok::minusminus: Opc = UO_PreDec; break;
7368 case tok::amp: Opc = UO_AddrOf; break;
7369 case tok::star: Opc = UO_Deref; break;
7370 case tok::plus: Opc = UO_Plus; break;
7371 case tok::minus: Opc = UO_Minus; break;
7372 case tok::tilde: Opc = UO_Not; break;
7373 case tok::exclaim: Opc = UO_LNot; break;
7374 case tok::kw___real: Opc = UO_Real; break;
7375 case tok::kw___imag: Opc = UO_Imag; break;
7376 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007377 }
7378 return Opc;
7379}
7380
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007381/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7382/// This warning is only emitted for builtin assignment operations. It is also
7383/// suppressed in the event of macro expansions.
7384static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7385 SourceLocation OpLoc) {
7386 if (!S.ActiveTemplateInstantiations.empty())
7387 return;
7388 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7389 return;
7390 lhs = lhs->IgnoreParenImpCasts();
7391 rhs = rhs->IgnoreParenImpCasts();
7392 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7393 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7394 if (!LeftDeclRef || !RightDeclRef ||
7395 LeftDeclRef->getLocation().isMacroID() ||
7396 RightDeclRef->getLocation().isMacroID())
7397 return;
7398 const ValueDecl *LeftDecl =
7399 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7400 const ValueDecl *RightDecl =
7401 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7402 if (LeftDecl != RightDecl)
7403 return;
7404 if (LeftDecl->getType().isVolatileQualified())
7405 return;
7406 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7407 if (RefTy->getPointeeType().isVolatileQualified())
7408 return;
7409
7410 S.Diag(OpLoc, diag::warn_self_assignment)
7411 << LeftDeclRef->getType()
7412 << lhs->getSourceRange() << rhs->getSourceRange();
7413}
7414
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007415/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7416/// operator @p Opc at location @c TokLoc. This routine only supports
7417/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007418ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007419 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007420 Expr *lhsExpr, Expr *rhsExpr) {
7421 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007422 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007423 // The following two variables are used for compound assignment operators
7424 QualType CompLHSTy; // Type of LHS after promotions for computation
7425 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007426 ExprValueKind VK = VK_RValue;
7427 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007428
Douglas Gregor1beec452011-03-12 01:48:56 +00007429 // Check if a 'foo<int>' involved in a binary op, identifies a single
7430 // function unambiguously (i.e. an lvalue ala 13.4)
7431 // But since an assignment can trigger target based overload, exclude it in
7432 // our blind search. i.e:
7433 // template<class T> void f(); template<class T, class U> void f(U);
7434 // f<int> == 0; // resolve f<int> blindly
7435 // void (*p)(int); p = f<int>; // resolve f<int> using target
7436 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007437 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007438 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007439 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007440
John McCall3aef3d82011-04-10 19:13:55 +00007441 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007442 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007443 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007444 }
7445
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007446 // The canonical way to check for a GNU null is with isNullPointerConstant,
7447 // but we use a bit of a hack here for speed; this is a relatively
7448 // hot path, and isNullPointerConstant is slow.
7449 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7450 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007451
7452 // Detect when a NULL constant is used improperly in an expression. These
7453 // are mainly cases where the null pointer is used as an integer instead
7454 // of a pointer.
7455 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007456 // Avoid analyzing cases where the result will either be invalid (and
7457 // diagnosed as such) or entirely valid and not something to warn about.
7458 QualType LeftType = lhs.get()->getType();
7459 QualType RightType = rhs.get()->getType();
7460 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7461 !LeftType->isFunctionType() &&
7462 !RightType->isBlockPointerType() &&
7463 !RightType->isMemberPointerType() &&
7464 !RightType->isFunctionType()) {
7465 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7466 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7467 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7468 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7469 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7470 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7471 // These are the operations that would not make sense with a null pointer
7472 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007473 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007474 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7475 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7476 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7477 Opc == BO_EQ || Opc == BO_NE) {
7478 // These are the operations that would not make sense with a null pointer
7479 // if the other expression the other expression is not a pointer.
7480 if (LeftNull != RightNull &&
7481 !LeftType->isAnyPointerType() &&
7482 !LeftType->canDecayToPointerType() &&
7483 !RightType->isAnyPointerType() &&
7484 !RightType->canDecayToPointerType()) {
7485 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7486 << (LeftNull ? lhs.get()->getSourceRange()
7487 : rhs.get()->getSourceRange());
7488 }
Richard Trieu701fb362011-06-16 21:36:56 +00007489 }
7490 }
7491 }
7492
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007493 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007494 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007495 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007496 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007497 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7498 VK = lhs.get()->getValueKind();
7499 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007500 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007501 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007502 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007503 break;
John McCalle3027922010-08-25 11:45:40 +00007504 case BO_PtrMemD:
7505 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007506 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007507 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007508 break;
John McCalle3027922010-08-25 11:45:40 +00007509 case BO_Mul:
7510 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007511 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007512 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007513 break;
John McCalle3027922010-08-25 11:45:40 +00007514 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007515 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7516 break;
John McCalle3027922010-08-25 11:45:40 +00007517 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007518 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7519 break;
John McCalle3027922010-08-25 11:45:40 +00007520 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007521 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7522 break;
John McCalle3027922010-08-25 11:45:40 +00007523 case BO_Shl:
7524 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007525 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007526 break;
John McCalle3027922010-08-25 11:45:40 +00007527 case BO_LE:
7528 case BO_LT:
7529 case BO_GE:
7530 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007531 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007532 break;
John McCalle3027922010-08-25 11:45:40 +00007533 case BO_EQ:
7534 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007535 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007536 break;
John McCalle3027922010-08-25 11:45:40 +00007537 case BO_And:
7538 case BO_Xor:
7539 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007540 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7541 break;
John McCalle3027922010-08-25 11:45:40 +00007542 case BO_LAnd:
7543 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007544 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007545 break;
John McCalle3027922010-08-25 11:45:40 +00007546 case BO_MulAssign:
7547 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007548 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007549 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007550 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007551 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7552 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007553 break;
John McCalle3027922010-08-25 11:45:40 +00007554 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007555 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7556 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007557 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7558 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007559 break;
John McCalle3027922010-08-25 11:45:40 +00007560 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007561 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007562 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7563 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007564 break;
John McCalle3027922010-08-25 11:45:40 +00007565 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007566 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007567 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7568 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007569 break;
John McCalle3027922010-08-25 11:45:40 +00007570 case BO_ShlAssign:
7571 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007572 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007573 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007574 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7575 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007576 break;
John McCalle3027922010-08-25 11:45:40 +00007577 case BO_AndAssign:
7578 case BO_XorAssign:
7579 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007580 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7581 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007582 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7583 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007584 break;
John McCalle3027922010-08-25 11:45:40 +00007585 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007586 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007587 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7588 VK = rhs.get()->getValueKind();
7589 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007590 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007591 break;
7592 }
John Wiegley01296292011-04-08 18:41:53 +00007593 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007594 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007595 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007596 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7597 ResultTy, VK, OK, OpLoc));
7598 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007599 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007600 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007601 }
John Wiegley01296292011-04-08 18:41:53 +00007602 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7603 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007604 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007605}
7606
Sebastian Redl44615072009-10-27 12:10:02 +00007607/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7608/// operators are mixed in a way that suggests that the programmer forgot that
7609/// comparison operators have higher precedence. The most typical example of
7610/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007611static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007612 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007613 typedef BinaryOperator BinOp;
7614 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7615 rhsopc = static_cast<BinOp::Opcode>(-1);
7616 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007617 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007618 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007619 rhsopc = BO->getOpcode();
7620
7621 // Subs are not binary operators.
7622 if (lhsopc == -1 && rhsopc == -1)
7623 return;
7624
7625 // Bitwise operations are sometimes used as eager logical ops.
7626 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007627 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7628 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007629 return;
7630
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007631 if (BinOp::isComparisonOp(lhsopc)) {
7632 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7633 << SourceRange(lhs->getLocStart(), OpLoc)
7634 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007635 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007636 Self.PDiag(diag::note_precedence_bitwise_silence)
7637 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007638 lhs->getSourceRange());
7639 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007640 Self.PDiag(diag::note_precedence_bitwise_first)
7641 << BinOp::getOpcodeStr(Opc),
7642 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007643 } else if (BinOp::isComparisonOp(rhsopc)) {
7644 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7645 << SourceRange(OpLoc, rhs->getLocEnd())
7646 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007647 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007648 Self.PDiag(diag::note_precedence_bitwise_silence)
7649 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007650 rhs->getSourceRange());
7651 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007652 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007653 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007654 SourceRange(lhs->getLocStart(),
7655 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007656 }
Sebastian Redl43028242009-10-26 15:24:15 +00007657}
7658
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007659/// \brief It accepts a '&' expr that is inside a '|' one.
7660/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7661/// in parentheses.
7662static void
7663EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7664 BinaryOperator *Bop) {
7665 assert(Bop->getOpcode() == BO_And);
7666 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7667 << Bop->getSourceRange() << OpLoc;
7668 SuggestParentheses(Self, Bop->getOperatorLoc(),
7669 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7670 Bop->getSourceRange());
7671}
7672
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007673/// \brief It accepts a '&&' expr that is inside a '||' one.
7674/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7675/// in parentheses.
7676static void
7677EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007678 BinaryOperator *Bop) {
7679 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007680 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7681 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007682 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007683 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007684 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007685}
7686
7687/// \brief Returns true if the given expression can be evaluated as a constant
7688/// 'true'.
7689static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7690 bool Res;
7691 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7692}
7693
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007694/// \brief Returns true if the given expression can be evaluated as a constant
7695/// 'false'.
7696static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7697 bool Res;
7698 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7699}
7700
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007701/// \brief Look for '&&' in the left hand of a '||' expr.
7702static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007703 Expr *OrLHS, Expr *OrRHS) {
7704 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007705 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007706 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7707 if (EvaluatesAsFalse(S, OrRHS))
7708 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007709 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7710 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7711 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7712 } else if (Bop->getOpcode() == BO_LOr) {
7713 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7714 // If it's "a || b && 1 || c" we didn't warn earlier for
7715 // "a || b && 1", but warn now.
7716 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7717 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7718 }
7719 }
7720 }
7721}
7722
7723/// \brief Look for '&&' in the right hand of a '||' expr.
7724static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007725 Expr *OrLHS, Expr *OrRHS) {
7726 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007727 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007728 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7729 if (EvaluatesAsFalse(S, OrLHS))
7730 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007731 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7732 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7733 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007734 }
7735 }
7736}
7737
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007738/// \brief Look for '&' in the left or right hand of a '|' expr.
7739static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7740 Expr *OrArg) {
7741 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7742 if (Bop->getOpcode() == BO_And)
7743 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7744 }
7745}
7746
Sebastian Redl43028242009-10-26 15:24:15 +00007747/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007748/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007749static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007750 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007751 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007752 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007753 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7754
7755 // Diagnose "arg1 & arg2 | arg3"
7756 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7757 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7758 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7759 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007760
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007761 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7762 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007763 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007764 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7765 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007766 }
Sebastian Redl43028242009-10-26 15:24:15 +00007767}
7768
Steve Naroff218bc2b2007-05-04 21:54:46 +00007769// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007770ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007771 tok::TokenKind Kind,
7772 Expr *lhs, Expr *rhs) {
7773 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007774 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7775 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007776
Sebastian Redl43028242009-10-26 15:24:15 +00007777 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7778 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7779
Douglas Gregor5287f092009-11-05 00:51:44 +00007780 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7781}
7782
John McCalldadc5752010-08-24 06:29:42 +00007783ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007784 BinaryOperatorKind Opc,
7785 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007786 if (getLangOptions().CPlusPlus) {
7787 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007788
John McCall622114c2010-12-06 05:26:58 +00007789 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7790 UseBuiltinOperator = false;
7791 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7792 UseBuiltinOperator = true;
7793 } else {
7794 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7795 !rhs->getType()->isOverloadableType();
7796 }
7797
7798 if (!UseBuiltinOperator) {
7799 // Find all of the overloaded operators visible from this
7800 // point. We perform both an operator-name lookup from the local
7801 // scope and an argument-dependent lookup based on the types of
7802 // the arguments.
7803 UnresolvedSet<16> Functions;
7804 OverloadedOperatorKind OverOp
7805 = BinaryOperator::getOverloadedOperator(Opc);
7806 if (S && OverOp != OO_None)
7807 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7808 Functions);
7809
7810 // Build the (potentially-overloaded, potentially-dependent)
7811 // binary operation.
7812 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7813 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007814 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007815
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007816 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007817 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007818}
7819
John McCalldadc5752010-08-24 06:29:42 +00007820ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007821 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007822 Expr *InputExpr) {
7823 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007824 ExprValueKind VK = VK_RValue;
7825 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007826 QualType resultType;
7827 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007828 case UO_PreInc:
7829 case UO_PreDec:
7830 case UO_PostInc:
7831 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007832 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007833 Opc == UO_PreInc ||
7834 Opc == UO_PostInc,
7835 Opc == UO_PreInc ||
7836 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007837 break;
John McCalle3027922010-08-25 11:45:40 +00007838 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007839 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007840 break;
John McCall31996342011-04-07 08:22:57 +00007841 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007842 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007843 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007844 Input = move(resolved);
7845 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7846 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007847 break;
John McCall31996342011-04-07 08:22:57 +00007848 }
John McCalle3027922010-08-25 11:45:40 +00007849 case UO_Plus:
7850 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007851 Input = UsualUnaryConversions(Input.take());
7852 if (Input.isInvalid()) return ExprError();
7853 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007854 if (resultType->isDependentType())
7855 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007856 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7857 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007858 break;
7859 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7860 resultType->isEnumeralType())
7861 break;
7862 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007863 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007864 resultType->isPointerType())
7865 break;
John McCall36226622010-10-12 02:09:17 +00007866 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007867 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007868 if (Input.isInvalid()) return ExprError();
7869 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007870 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007871
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007872 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007873 << resultType << Input.get()->getSourceRange());
7874
John McCalle3027922010-08-25 11:45:40 +00007875 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007876 Input = UsualUnaryConversions(Input.take());
7877 if (Input.isInvalid()) return ExprError();
7878 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007879 if (resultType->isDependentType())
7880 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007881 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7882 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7883 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007884 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007885 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007886 else if (resultType->hasIntegerRepresentation())
7887 break;
7888 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007889 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007890 if (Input.isInvalid()) return ExprError();
7891 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007892 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007893 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007894 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007895 }
Steve Naroff35d85152007-05-07 00:24:15 +00007896 break;
John Wiegley01296292011-04-08 18:41:53 +00007897
John McCalle3027922010-08-25 11:45:40 +00007898 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007899 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007900 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7901 if (Input.isInvalid()) return ExprError();
7902 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007903 if (resultType->isDependentType())
7904 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007905 if (resultType->isScalarType()) {
7906 // C99 6.5.3.3p1: ok, fallthrough;
7907 if (Context.getLangOptions().CPlusPlus) {
7908 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7909 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007910 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7911 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007912 }
John McCall36226622010-10-12 02:09:17 +00007913 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007914 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007915 if (Input.isInvalid()) return ExprError();
7916 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007917 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007918 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007919 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007920 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007921
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007922 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007923 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007924 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007925 break;
John McCalle3027922010-08-25 11:45:40 +00007926 case UO_Real:
7927 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007928 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007929 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007930 if (Input.isInvalid()) return ExprError();
7931 if (Input.get()->getValueKind() != VK_RValue &&
7932 Input.get()->getObjectKind() == OK_Ordinary)
7933 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007934 break;
John McCalle3027922010-08-25 11:45:40 +00007935 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007936 resultType = Input.get()->getType();
7937 VK = Input.get()->getValueKind();
7938 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007939 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007940 }
John Wiegley01296292011-04-08 18:41:53 +00007941 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007942 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007943
John Wiegley01296292011-04-08 18:41:53 +00007944 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007945 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007946}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007947
John McCalldadc5752010-08-24 06:29:42 +00007948ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007949 UnaryOperatorKind Opc,
7950 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007951 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007952 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007953 // Find all of the overloaded operators visible from this
7954 // point. We perform both an operator-name lookup from the local
7955 // scope and an argument-dependent lookup based on the types of
7956 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007957 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007958 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007959 if (S && OverOp != OO_None)
7960 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7961 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007962
John McCallb268a282010-08-23 23:25:46 +00007963 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007964 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007965
John McCallb268a282010-08-23 23:25:46 +00007966 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007967}
7968
Douglas Gregor5287f092009-11-05 00:51:44 +00007969// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007970ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007971 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007972 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007973}
7974
Steve Naroff66356bd2007-09-16 14:56:35 +00007975/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007976ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007977 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007978 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007979 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007980 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007981 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007982}
7983
John McCall31168b02011-06-15 23:02:42 +00007984/// Given the last statement in a statement-expression, check whether
7985/// the result is a producing expression (like a call to an
7986/// ns_returns_retained function) and, if so, rebuild it to hoist the
7987/// release out of the full-expression. Otherwise, return null.
7988/// Cannot fail.
7989static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7990 // Should always be wrapped with one of these.
7991 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7992 if (!cleanups) return 0;
7993
7994 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7995 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7996 return 0;
7997
7998 // Splice out the cast. This shouldn't modify any interesting
7999 // features of the statement.
8000 Expr *producer = cast->getSubExpr();
8001 assert(producer->getType() == cast->getType());
8002 assert(producer->getValueKind() == cast->getValueKind());
8003 cleanups->setSubExpr(producer);
8004 return cleanups;
8005}
8006
John McCalldadc5752010-08-24 06:29:42 +00008007ExprResult
John McCallb268a282010-08-23 23:25:46 +00008008Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008009 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008010 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8011 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8012
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008013 bool isFileScope
8014 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008015 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008016 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008017
Chris Lattner366727f2007-07-24 16:58:17 +00008018 // FIXME: there are a variety of strange constraints to enforce here, for
8019 // example, it is not possible to goto into a stmt expression apparently.
8020 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008021
Chris Lattner366727f2007-07-24 16:58:17 +00008022 // If there are sub stmts in the compound stmt, take the type of the last one
8023 // as the type of the stmtexpr.
8024 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008025 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008026 if (!Compound->body_empty()) {
8027 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008028 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008029 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008030 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8031 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008032 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008033 }
John McCall31168b02011-06-15 23:02:42 +00008034
John Wiegley01296292011-04-08 18:41:53 +00008035 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008036 // Do function/array conversion on the last expression, but not
8037 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008038 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8039 if (LastExpr.isInvalid())
8040 return ExprError();
8041 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008042
John Wiegley01296292011-04-08 18:41:53 +00008043 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008044 // In ARC, if the final expression ends in a consume, splice
8045 // the consume out and bind it later. In the alternate case
8046 // (when dealing with a retainable type), the result
8047 // initialization will create a produce. In both cases the
8048 // result will be +1, and we'll need to balance that out with
8049 // a bind.
8050 if (Expr *rebuiltLastStmt
8051 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8052 LastExpr = rebuiltLastStmt;
8053 } else {
8054 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008055 InitializedEntity::InitializeResult(LPLoc,
8056 Ty,
8057 false),
8058 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008059 LastExpr);
8060 }
8061
John Wiegley01296292011-04-08 18:41:53 +00008062 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008063 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008064 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008065 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008066 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008067 else
John Wiegley01296292011-04-08 18:41:53 +00008068 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008069 StmtExprMayBindToTemp = true;
8070 }
8071 }
8072 }
Chris Lattner944d3062008-07-26 19:51:01 +00008073 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008074
Eli Friedmanba961a92009-03-23 00:24:07 +00008075 // FIXME: Check that expression type is complete/non-abstract; statement
8076 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008077 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8078 if (StmtExprMayBindToTemp)
8079 return MaybeBindToTemporary(ResStmtExpr);
8080 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008081}
Steve Naroff78864672007-08-01 22:05:33 +00008082
John McCalldadc5752010-08-24 06:29:42 +00008083ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008084 TypeSourceInfo *TInfo,
8085 OffsetOfComponent *CompPtr,
8086 unsigned NumComponents,
8087 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008088 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008089 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008090 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008091
Chris Lattnerf17bd422007-08-30 17:45:32 +00008092 // We must have at least one component that refers to the type, and the first
8093 // one is known to be a field designator. Verify that the ArgTy represents
8094 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008095 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008096 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8097 << ArgTy << TypeRange);
8098
8099 // Type must be complete per C99 7.17p3 because a declaring a variable
8100 // with an incomplete type would be ill-formed.
8101 if (!Dependent
8102 && RequireCompleteType(BuiltinLoc, ArgTy,
8103 PDiag(diag::err_offsetof_incomplete_type)
8104 << TypeRange))
8105 return ExprError();
8106
Chris Lattner78502cf2007-08-31 21:49:13 +00008107 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8108 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008109 // FIXME: This diagnostic isn't actually visible because the location is in
8110 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008111 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008112 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8113 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008114
8115 bool DidWarnAboutNonPOD = false;
8116 QualType CurrentType = ArgTy;
8117 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008118 SmallVector<OffsetOfNode, 4> Comps;
8119 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008120 for (unsigned i = 0; i != NumComponents; ++i) {
8121 const OffsetOfComponent &OC = CompPtr[i];
8122 if (OC.isBrackets) {
8123 // Offset of an array sub-field. TODO: Should we allow vector elements?
8124 if (!CurrentType->isDependentType()) {
8125 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8126 if(!AT)
8127 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8128 << CurrentType);
8129 CurrentType = AT->getElementType();
8130 } else
8131 CurrentType = Context.DependentTy;
8132
8133 // The expression must be an integral expression.
8134 // FIXME: An integral constant expression?
8135 Expr *Idx = static_cast<Expr*>(OC.U.E);
8136 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8137 !Idx->getType()->isIntegerType())
8138 return ExprError(Diag(Idx->getLocStart(),
8139 diag::err_typecheck_subscript_not_integer)
8140 << Idx->getSourceRange());
8141
8142 // Record this array index.
8143 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8144 Exprs.push_back(Idx);
8145 continue;
8146 }
8147
8148 // Offset of a field.
8149 if (CurrentType->isDependentType()) {
8150 // We have the offset of a field, but we can't look into the dependent
8151 // type. Just record the identifier of the field.
8152 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8153 CurrentType = Context.DependentTy;
8154 continue;
8155 }
8156
8157 // We need to have a complete type to look into.
8158 if (RequireCompleteType(OC.LocStart, CurrentType,
8159 diag::err_offsetof_incomplete_type))
8160 return ExprError();
8161
8162 // Look for the designated field.
8163 const RecordType *RC = CurrentType->getAs<RecordType>();
8164 if (!RC)
8165 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8166 << CurrentType);
8167 RecordDecl *RD = RC->getDecl();
8168
8169 // C++ [lib.support.types]p5:
8170 // The macro offsetof accepts a restricted set of type arguments in this
8171 // International Standard. type shall be a POD structure or a POD union
8172 // (clause 9).
8173 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8174 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008175 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008176 PDiag(diag::warn_offsetof_non_pod_type)
8177 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8178 << CurrentType))
8179 DidWarnAboutNonPOD = true;
8180 }
8181
8182 // Look for the field.
8183 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8184 LookupQualifiedName(R, RD);
8185 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008186 IndirectFieldDecl *IndirectMemberDecl = 0;
8187 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008188 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008189 MemberDecl = IndirectMemberDecl->getAnonField();
8190 }
8191
Douglas Gregor882211c2010-04-28 22:16:22 +00008192 if (!MemberDecl)
8193 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8194 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8195 OC.LocEnd));
8196
Douglas Gregor10982ea2010-04-28 22:36:06 +00008197 // C99 7.17p3:
8198 // (If the specified member is a bit-field, the behavior is undefined.)
8199 //
8200 // We diagnose this as an error.
8201 if (MemberDecl->getBitWidth()) {
8202 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8203 << MemberDecl->getDeclName()
8204 << SourceRange(BuiltinLoc, RParenLoc);
8205 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8206 return ExprError();
8207 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008208
8209 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008210 if (IndirectMemberDecl)
8211 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008212
Douglas Gregord1702062010-04-29 00:18:15 +00008213 // If the member was found in a base class, introduce OffsetOfNodes for
8214 // the base class indirections.
8215 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8216 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008217 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008218 CXXBasePath &Path = Paths.front();
8219 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8220 B != BEnd; ++B)
8221 Comps.push_back(OffsetOfNode(B->Base));
8222 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008223
Francois Pichet783dd6e2010-11-21 06:08:52 +00008224 if (IndirectMemberDecl) {
8225 for (IndirectFieldDecl::chain_iterator FI =
8226 IndirectMemberDecl->chain_begin(),
8227 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8228 assert(isa<FieldDecl>(*FI));
8229 Comps.push_back(OffsetOfNode(OC.LocStart,
8230 cast<FieldDecl>(*FI), OC.LocEnd));
8231 }
8232 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008233 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008234
Douglas Gregor882211c2010-04-28 22:16:22 +00008235 CurrentType = MemberDecl->getType().getNonReferenceType();
8236 }
8237
8238 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8239 TInfo, Comps.data(), Comps.size(),
8240 Exprs.data(), Exprs.size(), RParenLoc));
8241}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008242
John McCalldadc5752010-08-24 06:29:42 +00008243ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008244 SourceLocation BuiltinLoc,
8245 SourceLocation TypeLoc,
8246 ParsedType argty,
8247 OffsetOfComponent *CompPtr,
8248 unsigned NumComponents,
8249 SourceLocation RPLoc) {
8250
Douglas Gregor882211c2010-04-28 22:16:22 +00008251 TypeSourceInfo *ArgTInfo;
8252 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8253 if (ArgTy.isNull())
8254 return ExprError();
8255
Eli Friedman06dcfd92010-08-05 10:15:45 +00008256 if (!ArgTInfo)
8257 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8258
8259 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8260 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008261}
8262
8263
John McCalldadc5752010-08-24 06:29:42 +00008264ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008265 Expr *CondExpr,
8266 Expr *LHSExpr, Expr *RHSExpr,
8267 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008268 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8269
John McCall7decc9e2010-11-18 06:31:45 +00008270 ExprValueKind VK = VK_RValue;
8271 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008272 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008273 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008274 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008275 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008276 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008277 } else {
8278 // The conditional expression is required to be a constant expression.
8279 llvm::APSInt condEval(32);
8280 SourceLocation ExpLoc;
8281 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008282 return ExprError(Diag(ExpLoc,
8283 diag::err_typecheck_choose_expr_requires_constant)
8284 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008285
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008286 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008287 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8288
8289 resType = ActiveExpr->getType();
8290 ValueDependent = ActiveExpr->isValueDependent();
8291 VK = ActiveExpr->getValueKind();
8292 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008293 }
8294
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008295 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008296 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008297 resType->isDependentType(),
8298 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008299}
8300
Steve Naroffc540d662008-09-03 18:15:37 +00008301//===----------------------------------------------------------------------===//
8302// Clang Extensions.
8303//===----------------------------------------------------------------------===//
8304
8305/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008306void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008307 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8308 PushBlockScope(BlockScope, Block);
8309 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008310 if (BlockScope)
8311 PushDeclContext(BlockScope, Block);
8312 else
8313 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008314}
8315
Mike Stump82f071f2009-02-04 22:31:32 +00008316void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008317 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008318 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008319 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008320
John McCall8cb7bdf2010-06-04 23:28:52 +00008321 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008322 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008323
John McCall3882ace2011-01-05 12:14:39 +00008324 // GetTypeForDeclarator always produces a function type for a block
8325 // literal signature. Furthermore, it is always a FunctionProtoType
8326 // unless the function was written with a typedef.
8327 assert(T->isFunctionType() &&
8328 "GetTypeForDeclarator made a non-function block signature");
8329
8330 // Look for an explicit signature in that function type.
8331 FunctionProtoTypeLoc ExplicitSignature;
8332
8333 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8334 if (isa<FunctionProtoTypeLoc>(tmp)) {
8335 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8336
8337 // Check whether that explicit signature was synthesized by
8338 // GetTypeForDeclarator. If so, don't save that as part of the
8339 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008340 if (ExplicitSignature.getLocalRangeBegin() ==
8341 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008342 // This would be much cheaper if we stored TypeLocs instead of
8343 // TypeSourceInfos.
8344 TypeLoc Result = ExplicitSignature.getResultLoc();
8345 unsigned Size = Result.getFullDataSize();
8346 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8347 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8348
8349 ExplicitSignature = FunctionProtoTypeLoc();
8350 }
John McCalla3ccba02010-06-04 11:21:44 +00008351 }
Mike Stump11289f42009-09-09 15:08:12 +00008352
John McCall3882ace2011-01-05 12:14:39 +00008353 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8354 CurBlock->FunctionType = T;
8355
8356 const FunctionType *Fn = T->getAs<FunctionType>();
8357 QualType RetTy = Fn->getResultType();
8358 bool isVariadic =
8359 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8360
John McCall8e346702010-06-04 19:02:56 +00008361 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008362
John McCalla3ccba02010-06-04 11:21:44 +00008363 // Don't allow returning a objc interface by value.
8364 if (RetTy->isObjCObjectType()) {
8365 Diag(ParamInfo.getSourceRange().getBegin(),
8366 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8367 return;
8368 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008369
John McCalla3ccba02010-06-04 11:21:44 +00008370 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008371 // return type. TODO: what should we do with declarators like:
8372 // ^ * { ... }
8373 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008374 if (RetTy != Context.DependentTy)
8375 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008376
John McCalla3ccba02010-06-04 11:21:44 +00008377 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008378 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008379 if (ExplicitSignature) {
8380 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8381 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008382 if (Param->getIdentifier() == 0 &&
8383 !Param->isImplicit() &&
8384 !Param->isInvalidDecl() &&
8385 !getLangOptions().CPlusPlus)
8386 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008387 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008388 }
John McCalla3ccba02010-06-04 11:21:44 +00008389
8390 // Fake up parameter variables if we have a typedef, like
8391 // ^ fntype { ... }
8392 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8393 for (FunctionProtoType::arg_type_iterator
8394 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8395 ParmVarDecl *Param =
8396 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8397 ParamInfo.getSourceRange().getBegin(),
8398 *I);
John McCall8e346702010-06-04 19:02:56 +00008399 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008400 }
Steve Naroffc540d662008-09-03 18:15:37 +00008401 }
John McCalla3ccba02010-06-04 11:21:44 +00008402
John McCall8e346702010-06-04 19:02:56 +00008403 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008404 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008405 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008406 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8407 CurBlock->TheDecl->param_end(),
8408 /*CheckParameterNames=*/false);
8409 }
8410
John McCalla3ccba02010-06-04 11:21:44 +00008411 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008412 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008413
John McCall8e346702010-06-04 19:02:56 +00008414 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008415 Diag(ParamInfo.getAttributes()->getLoc(),
8416 diag::warn_attribute_sentinel_not_variadic) << 1;
8417 // FIXME: remove the attribute.
8418 }
8419
8420 // Put the parameter variables in scope. We can bail out immediately
8421 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008422 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008423 return;
8424
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008425 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008426 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8427 (*AI)->setOwningFunction(CurBlock->TheDecl);
8428
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008429 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008430 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008431 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008432
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008433 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008434 }
John McCallf7b2fb52010-01-22 00:28:27 +00008435 }
Steve Naroffc540d662008-09-03 18:15:37 +00008436}
8437
8438/// ActOnBlockError - If there is an error parsing a block, this callback
8439/// is invoked to pop the information about the block from the action impl.
8440void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008441 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008442 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008443 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008444}
8445
8446/// ActOnBlockStmtExpr - This is called when the body of a block statement
8447/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008448ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008449 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008450 // If blocks are disabled, emit an error.
8451 if (!LangOpts.Blocks)
8452 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008453
Douglas Gregor9a28e842010-03-01 23:15:13 +00008454 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008455
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008456 PopDeclContext();
8457
Steve Naroffc540d662008-09-03 18:15:37 +00008458 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008459 if (!BSI->ReturnType.isNull())
8460 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008461
Mike Stump3bf1ab42009-07-28 22:04:01 +00008462 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008463 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008464
John McCallc63de662011-02-02 13:00:07 +00008465 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008466 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8467 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008468
John McCall8e346702010-06-04 19:02:56 +00008469 // If the user wrote a function type in some form, try to use that.
8470 if (!BSI->FunctionType.isNull()) {
8471 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8472
8473 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8474 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8475
8476 // Turn protoless block types into nullary block types.
8477 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008478 FunctionProtoType::ExtProtoInfo EPI;
8479 EPI.ExtInfo = Ext;
8480 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008481
8482 // Otherwise, if we don't need to change anything about the function type,
8483 // preserve its sugar structure.
8484 } else if (FTy->getResultType() == RetTy &&
8485 (!NoReturn || FTy->getNoReturnAttr())) {
8486 BlockTy = BSI->FunctionType;
8487
8488 // Otherwise, make the minimal modifications to the function type.
8489 } else {
8490 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008491 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8492 EPI.TypeQuals = 0; // FIXME: silently?
8493 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008494 BlockTy = Context.getFunctionType(RetTy,
8495 FPT->arg_type_begin(),
8496 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008497 EPI);
John McCall8e346702010-06-04 19:02:56 +00008498 }
8499
8500 // If we don't have a function type, just build one from nothing.
8501 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008502 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008503 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008504 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008505 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008506
John McCall8e346702010-06-04 19:02:56 +00008507 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8508 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008509 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008510
Chris Lattner45542ea2009-04-19 05:28:12 +00008511 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008512 if (getCurFunction()->NeedsScopeChecking() &&
8513 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008514 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008515
Chris Lattner60f84492011-02-17 23:58:47 +00008516 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008517
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008518 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8519 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8520 const VarDecl *variable = ci->getVariable();
8521 QualType T = variable->getType();
8522 QualType::DestructionKind destructKind = T.isDestructedType();
8523 if (destructKind != QualType::DK_none)
8524 getCurFunction()->setHasBranchProtectedScope();
8525 }
8526
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008527 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8528 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8529 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8530
Douglas Gregor9a28e842010-03-01 23:15:13 +00008531 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008532}
8533
John McCalldadc5752010-08-24 06:29:42 +00008534ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008535 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008536 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008537 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008538 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008539 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008540}
8541
John McCalldadc5752010-08-24 06:29:42 +00008542ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008543 Expr *E, TypeSourceInfo *TInfo,
8544 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008545 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008546
Eli Friedman121ba0c2008-08-09 23:32:40 +00008547 // Get the va_list type
8548 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008549 if (VaListType->isArrayType()) {
8550 // Deal with implicit array decay; for example, on x86-64,
8551 // va_list is an array, but it's supposed to decay to
8552 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008553 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008554 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008555 ExprResult Result = UsualUnaryConversions(E);
8556 if (Result.isInvalid())
8557 return ExprError();
8558 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008559 } else {
8560 // Otherwise, the va_list argument must be an l-value because
8561 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008562 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008563 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008564 return ExprError();
8565 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008566
Douglas Gregorad3150c2009-05-19 23:10:31 +00008567 if (!E->isTypeDependent() &&
8568 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008569 return ExprError(Diag(E->getLocStart(),
8570 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008571 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008572 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008573
David Majnemerc75d1a12011-06-14 05:17:32 +00008574 if (!TInfo->getType()->isDependentType()) {
8575 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8576 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8577 << TInfo->getTypeLoc().getSourceRange()))
8578 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008579
David Majnemerc75d1a12011-06-14 05:17:32 +00008580 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8581 TInfo->getType(),
8582 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8583 << TInfo->getTypeLoc().getSourceRange()))
8584 return ExprError();
8585
John McCall31168b02011-06-15 23:02:42 +00008586 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00008587 Diag(TInfo->getTypeLoc().getBeginLoc(),
8588 diag::warn_second_parameter_to_va_arg_not_pod)
8589 << TInfo->getType()
8590 << TInfo->getTypeLoc().getSourceRange();
Eli Friedman6290ae42011-07-11 21:45:59 +00008591
8592 // Check for va_arg where arguments of the given type will be promoted
8593 // (i.e. this va_arg is guaranteed to have undefined behavior).
8594 QualType PromoteType;
8595 if (TInfo->getType()->isPromotableIntegerType()) {
8596 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8597 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8598 PromoteType = QualType();
8599 }
8600 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8601 PromoteType = Context.DoubleTy;
8602 if (!PromoteType.isNull())
8603 Diag(TInfo->getTypeLoc().getBeginLoc(),
8604 diag::warn_second_parameter_to_va_arg_never_compatible)
8605 << TInfo->getType()
8606 << PromoteType
8607 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008608 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008609
Abramo Bagnara27db2392010-08-10 10:06:15 +00008610 QualType T = TInfo->getType().getNonLValueExprType(Context);
8611 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008612}
8613
John McCalldadc5752010-08-24 06:29:42 +00008614ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008615 // The type of __null will be int or long, depending on the size of
8616 // pointers on the target.
8617 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008618 unsigned pw = Context.Target.getPointerWidth(0);
8619 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008620 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008621 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008622 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008623 else if (pw == Context.Target.getLongLongWidth())
8624 Ty = Context.LongLongTy;
8625 else {
8626 assert(!"I don't know size of pointer!");
8627 Ty = Context.IntTy;
8628 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008629
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008630 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008631}
8632
Alexis Huntc46382e2010-04-28 23:02:27 +00008633static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008634 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008635 if (!SemaRef.getLangOptions().ObjC1)
8636 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008637
Anders Carlssonace5d072009-11-10 04:46:30 +00008638 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8639 if (!PT)
8640 return;
8641
8642 // Check if the destination is of type 'id'.
8643 if (!PT->isObjCIdType()) {
8644 // Check if the destination is the 'NSString' interface.
8645 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8646 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8647 return;
8648 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008649
Anders Carlssonace5d072009-11-10 04:46:30 +00008650 // Strip off any parens and casts.
8651 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008652 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008653 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008654
Douglas Gregora771f462010-03-31 17:46:05 +00008655 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008656}
8657
Chris Lattner9bad62c2008-01-04 18:04:52 +00008658bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8659 SourceLocation Loc,
8660 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008661 Expr *SrcExpr, AssignmentAction Action,
8662 bool *Complained) {
8663 if (Complained)
8664 *Complained = false;
8665
Chris Lattner9bad62c2008-01-04 18:04:52 +00008666 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008667 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008668 bool isInvalid = false;
8669 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008670 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008671
Chris Lattner9bad62c2008-01-04 18:04:52 +00008672 switch (ConvTy) {
8673 default: assert(0 && "Unknown conversion type");
8674 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008675 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008676 DiagKind = diag::ext_typecheck_convert_pointer_int;
8677 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008678 case IntToPointer:
8679 DiagKind = diag::ext_typecheck_convert_int_pointer;
8680 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008681 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008682 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008683 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008684 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8685 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +00008686 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008687 case IncompatiblePointerSign:
8688 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8689 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008690 case FunctionVoidPointer:
8691 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8692 break;
John McCall4fff8f62011-02-01 00:10:29 +00008693 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008694 // Perform array-to-pointer decay if necessary.
8695 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8696
John McCall4fff8f62011-02-01 00:10:29 +00008697 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8698 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8699 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8700 DiagKind = diag::err_typecheck_incompatible_address_space;
8701 break;
John McCall31168b02011-06-15 23:02:42 +00008702
8703
8704 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008705 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008706 break;
John McCall4fff8f62011-02-01 00:10:29 +00008707 }
8708
8709 llvm_unreachable("unknown error case for discarding qualifiers!");
8710 // fallthrough
8711 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008712 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008713 // If the qualifiers lost were because we were applying the
8714 // (deprecated) C++ conversion from a string literal to a char*
8715 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8716 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008717 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008718 // bit of refactoring (so that the second argument is an
8719 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008720 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008721 // C++ semantics.
8722 if (getLangOptions().CPlusPlus &&
8723 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8724 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008725 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8726 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008727 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008728 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008729 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008730 case IntToBlockPointer:
8731 DiagKind = diag::err_int_to_block_pointer;
8732 break;
8733 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008734 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008735 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008736 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008737 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008738 // it can give a more specific diagnostic.
8739 DiagKind = diag::warn_incompatible_qualified_id;
8740 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008741 case IncompatibleVectors:
8742 DiagKind = diag::warn_incompatible_vectors;
8743 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008744 case IncompatibleObjCWeakRef:
8745 DiagKind = diag::err_arc_weak_unavailable_assign;
8746 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008747 case Incompatible:
8748 DiagKind = diag::err_typecheck_convert_incompatible;
8749 isInvalid = true;
8750 break;
8751 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008752
Douglas Gregorc68e1402010-04-09 00:35:39 +00008753 QualType FirstType, SecondType;
8754 switch (Action) {
8755 case AA_Assigning:
8756 case AA_Initializing:
8757 // The destination type comes first.
8758 FirstType = DstType;
8759 SecondType = SrcType;
8760 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008761
Douglas Gregorc68e1402010-04-09 00:35:39 +00008762 case AA_Returning:
8763 case AA_Passing:
8764 case AA_Converting:
8765 case AA_Sending:
8766 case AA_Casting:
8767 // The source type comes first.
8768 FirstType = SrcType;
8769 SecondType = DstType;
8770 break;
8771 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008772
Douglas Gregorc68e1402010-04-09 00:35:39 +00008773 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008774 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +00008775 if (CheckInferredResultType)
8776 EmitRelatedResultTypeNote(SrcExpr);
8777
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008778 if (Complained)
8779 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008780 return isInvalid;
8781}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008782
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008783bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008784 llvm::APSInt ICEResult;
8785 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8786 if (Result)
8787 *Result = ICEResult;
8788 return false;
8789 }
8790
Anders Carlssone54e8a12008-11-30 19:50:32 +00008791 Expr::EvalResult EvalResult;
8792
Mike Stump4e1f26a2009-02-19 03:04:26 +00008793 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008794 EvalResult.HasSideEffects) {
8795 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8796
8797 if (EvalResult.Diag) {
8798 // We only show the note if it's not the usual "invalid subexpression"
8799 // or if it's actually in a subexpression.
8800 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8801 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8802 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8803 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008804
Anders Carlssone54e8a12008-11-30 19:50:32 +00008805 return true;
8806 }
8807
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008808 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8809 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008810
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008811 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008812 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8813 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008814 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008815
Anders Carlssone54e8a12008-11-30 19:50:32 +00008816 if (Result)
8817 *Result = EvalResult.Val.getInt();
8818 return false;
8819}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008820
Douglas Gregorff790f12009-11-26 00:44:06 +00008821void
Mike Stump11289f42009-09-09 15:08:12 +00008822Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008823 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008824 ExpressionEvaluationContextRecord(NewContext,
8825 ExprTemporaries.size(),
8826 ExprNeedsCleanups));
8827 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008828}
8829
Mike Stump11289f42009-09-09 15:08:12 +00008830void
Douglas Gregorff790f12009-11-26 00:44:06 +00008831Sema::PopExpressionEvaluationContext() {
8832 // Pop the current expression evaluation context off the stack.
8833 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8834 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008835
Douglas Gregorfab31f42009-12-12 07:57:52 +00008836 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8837 if (Rec.PotentiallyReferenced) {
8838 // Mark any remaining declarations in the current position of the stack
8839 // as "referenced". If they were not meant to be referenced, semantic
8840 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008841 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008842 I = Rec.PotentiallyReferenced->begin(),
8843 IEnd = Rec.PotentiallyReferenced->end();
8844 I != IEnd; ++I)
8845 MarkDeclarationReferenced(I->first, I->second);
8846 }
8847
8848 if (Rec.PotentiallyDiagnosed) {
8849 // Emit any pending diagnostics.
8850 for (PotentiallyEmittedDiagnostics::iterator
8851 I = Rec.PotentiallyDiagnosed->begin(),
8852 IEnd = Rec.PotentiallyDiagnosed->end();
8853 I != IEnd; ++I)
8854 Diag(I->first, I->second);
8855 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008856 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008857
8858 // When are coming out of an unevaluated context, clear out any
8859 // temporaries that we may have created as part of the evaluation of
8860 // the expression in that context: they aren't relevant because they
8861 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008862 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008863 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8864 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008865 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8866
8867 // Otherwise, merge the contexts together.
8868 } else {
8869 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8870 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008871
8872 // Destroy the popped expression evaluation record.
8873 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008874}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008875
John McCall31168b02011-06-15 23:02:42 +00008876void Sema::DiscardCleanupsInEvaluationContext() {
8877 ExprTemporaries.erase(
8878 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8879 ExprTemporaries.end());
8880 ExprNeedsCleanups = false;
8881}
8882
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008883/// \brief Note that the given declaration was referenced in the source code.
8884///
8885/// This routine should be invoke whenever a given declaration is referenced
8886/// in the source code, and where that reference occurred. If this declaration
8887/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8888/// C99 6.9p3), then the declaration will be marked as used.
8889///
8890/// \param Loc the location where the declaration was referenced.
8891///
8892/// \param D the declaration that has been referenced by the source code.
8893void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8894 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008895
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008896 D->setReferenced();
8897
Douglas Gregorebada0772010-06-17 23:14:26 +00008898 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008899 return;
Mike Stump11289f42009-09-09 15:08:12 +00008900
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008901 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8902 // template or not. The reason for this is that unevaluated expressions
8903 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8904 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008905 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008906 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008907 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008908 return;
8909 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008910
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008911 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8912 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008913
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008914 // Do not mark anything as "used" within a dependent context; wait for
8915 // an instantiation.
8916 if (CurContext->isDependentContext())
8917 return;
Mike Stump11289f42009-09-09 15:08:12 +00008918
Douglas Gregorff790f12009-11-26 00:44:06 +00008919 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008920 case Unevaluated:
8921 // We are in an expression that is not potentially evaluated; do nothing.
8922 return;
Mike Stump11289f42009-09-09 15:08:12 +00008923
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008924 case PotentiallyEvaluated:
8925 // We are in a potentially-evaluated expression, so this declaration is
8926 // "used"; handle this below.
8927 break;
Mike Stump11289f42009-09-09 15:08:12 +00008928
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008929 case PotentiallyPotentiallyEvaluated:
8930 // We are in an expression that may be potentially evaluated; queue this
8931 // declaration reference until we know whether the expression is
8932 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008933 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008934 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008935
8936 case PotentiallyEvaluatedIfUsed:
8937 // Referenced declarations will only be used if the construct in the
8938 // containing expression is used.
8939 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008940 }
Mike Stump11289f42009-09-09 15:08:12 +00008941
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008942 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008943 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008944 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8945 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008946 return;
8947 if (!Constructor->isUsed(false))
8948 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008949 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008950 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008951 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00008952 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008953 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008954
Douglas Gregor88d292c2010-05-13 16:44:06 +00008955 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008956 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00008957 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008958 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008959 if (Destructor->isVirtual())
8960 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008961 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00008962 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008963 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008964 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008965 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008966 } else if (MethodDecl->isVirtual())
8967 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008968 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008969 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00008970 // Recursive functions should be marked when used from another function.
8971 if (CurContext == Function) return;
8972
Mike Stump11289f42009-09-09 15:08:12 +00008973 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008974 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008975 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008976 bool AlreadyInstantiated = false;
8977 if (FunctionTemplateSpecializationInfo *SpecInfo
8978 = Function->getTemplateSpecializationInfo()) {
8979 if (SpecInfo->getPointOfInstantiation().isInvalid())
8980 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008981 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008982 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008983 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008984 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008985 = Function->getMemberSpecializationInfo()) {
8986 if (MSInfo->getPointOfInstantiation().isInvalid())
8987 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008988 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008989 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008990 AlreadyInstantiated = true;
8991 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008992
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008993 if (!AlreadyInstantiated) {
8994 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8995 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8996 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8997 Loc));
8998 else
Chandler Carruth54080172010-08-25 08:44:16 +00008999 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009000 }
John McCall83779672011-02-19 02:53:41 +00009001 } else {
9002 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009003 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9004 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009005 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009006 MarkDeclarationReferenced(Loc, *i);
9007 }
John McCall83779672011-02-19 02:53:41 +00009008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009009
John McCall83779672011-02-19 02:53:41 +00009010 // Keep track of used but undefined functions.
9011 if (!Function->isPure() && !Function->hasBody() &&
9012 Function->getLinkage() != ExternalLinkage) {
9013 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9014 if (old.isInvalid()) old = Loc;
9015 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009016
John McCall83779672011-02-19 02:53:41 +00009017 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009018 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009019 }
Mike Stump11289f42009-09-09 15:08:12 +00009020
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009021 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009022 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009023 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009024 Var->getInstantiatedFromStaticDataMember()) {
9025 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9026 assert(MSInfo && "Missing member specialization information?");
9027 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9028 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9029 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009030 // This is a modification of an existing AST node. Notify listeners.
9031 if (ASTMutationListener *L = getASTMutationListener())
9032 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009033 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009034 }
9035 }
Mike Stump11289f42009-09-09 15:08:12 +00009036
John McCall15dd4042011-02-21 19:25:48 +00009037 // Keep track of used but undefined variables. We make a hole in
9038 // the warning for static const data members with in-line
9039 // initializers.
John McCall83779672011-02-19 02:53:41 +00009040 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009041 && Var->getLinkage() != ExternalLinkage
9042 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009043 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9044 if (old.isInvalid()) old = Loc;
9045 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009046
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009047 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009048 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009049 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009050}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009051
Douglas Gregor5597ab42010-05-07 23:12:07 +00009052namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009053 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009054 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009055 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009056 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9057 Sema &S;
9058 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009059
Douglas Gregor5597ab42010-05-07 23:12:07 +00009060 public:
9061 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009062
Douglas Gregor5597ab42010-05-07 23:12:07 +00009063 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009064
9065 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9066 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009067 };
9068}
9069
Chandler Carruthaf80f662010-06-09 08:17:30 +00009070bool MarkReferencedDecls::TraverseTemplateArgument(
9071 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009072 if (Arg.getKind() == TemplateArgument::Declaration) {
9073 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9074 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009075
9076 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009077}
9078
Chandler Carruthaf80f662010-06-09 08:17:30 +00009079bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009080 if (ClassTemplateSpecializationDecl *Spec
9081 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9082 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009083 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009084 }
9085
Chandler Carruthc65667c2010-06-10 10:31:57 +00009086 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009087}
9088
9089void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9090 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009091 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009092}
9093
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009094namespace {
9095 /// \brief Helper class that marks all of the declarations referenced by
9096 /// potentially-evaluated subexpressions as "referenced".
9097 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9098 Sema &S;
9099
9100 public:
9101 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9102
9103 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9104
9105 void VisitDeclRefExpr(DeclRefExpr *E) {
9106 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9107 }
9108
9109 void VisitMemberExpr(MemberExpr *E) {
9110 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009111 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009112 }
9113
9114 void VisitCXXNewExpr(CXXNewExpr *E) {
9115 if (E->getConstructor())
9116 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9117 if (E->getOperatorNew())
9118 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9119 if (E->getOperatorDelete())
9120 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009121 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009122 }
9123
9124 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9125 if (E->getOperatorDelete())
9126 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009127 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9128 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9129 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9130 S.MarkDeclarationReferenced(E->getLocStart(),
9131 S.LookupDestructor(Record));
9132 }
9133
Douglas Gregor32b3de52010-09-11 23:32:50 +00009134 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009135 }
9136
9137 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9138 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009139 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009140 }
9141
9142 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9143 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9144 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009145
9146 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9147 Visit(E->getExpr());
9148 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009149 };
9150}
9151
9152/// \brief Mark any declarations that appear within this expression or any
9153/// potentially-evaluated subexpressions as "referenced".
9154void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9155 EvaluatedExprMarker(*this).Visit(E);
9156}
9157
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009158/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9159/// of the program being compiled.
9160///
9161/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009162/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009163/// possibility that the code will actually be executable. Code in sizeof()
9164/// expressions, code used only during overload resolution, etc., are not
9165/// potentially evaluated. This routine will suppress such diagnostics or,
9166/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009167/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009168/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009169///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009170/// This routine should be used for all diagnostics that describe the run-time
9171/// behavior of a program, such as passing a non-POD value through an ellipsis.
9172/// Failure to do so will likely result in spurious diagnostics or failures
9173/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009174bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009175 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009176 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009177 case Unevaluated:
9178 // The argument will never be evaluated, so don't complain.
9179 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009180
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009181 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009182 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009183 if (stmt && getCurFunctionOrMethodDecl()) {
9184 FunctionScopes.back()->PossiblyUnreachableDiags.
9185 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9186 }
9187 else
9188 Diag(Loc, PD);
9189
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009190 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009191
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009192 case PotentiallyPotentiallyEvaluated:
9193 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9194 break;
9195 }
9196
9197 return false;
9198}
9199
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009200bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9201 CallExpr *CE, FunctionDecl *FD) {
9202 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9203 return false;
9204
9205 PartialDiagnostic Note =
9206 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9207 << FD->getDeclName() : PDiag();
9208 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009209
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009210 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009211 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009212 PDiag(diag::err_call_function_incomplete_return)
9213 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009214 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009215 << CE->getSourceRange(),
9216 std::make_pair(NoteLoc, Note)))
9217 return true;
9218
9219 return false;
9220}
9221
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009222// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009223// will prevent this condition from triggering, which is what we want.
9224void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9225 SourceLocation Loc;
9226
John McCall0506e4a2009-11-11 02:41:58 +00009227 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009228 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009229
John McCalld5707ab2009-10-12 21:59:07 +00009230 if (isa<BinaryOperator>(E)) {
9231 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009232 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009233 return;
9234
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009235 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9236
John McCallb0e419e2009-11-12 00:06:05 +00009237 // Greylist some idioms by putting them into a warning subcategory.
9238 if (ObjCMessageExpr *ME
9239 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9240 Selector Sel = ME->getSelector();
9241
John McCallb0e419e2009-11-12 00:06:05 +00009242 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009243 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009244 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9245
9246 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009247 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009248 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9249 }
John McCall0506e4a2009-11-11 02:41:58 +00009250
John McCalld5707ab2009-10-12 21:59:07 +00009251 Loc = Op->getOperatorLoc();
9252 } else if (isa<CXXOperatorCallExpr>(E)) {
9253 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009254 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009255 return;
9256
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009257 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009258 Loc = Op->getOperatorLoc();
9259 } else {
9260 // Not an assignment.
9261 return;
9262 }
9263
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009264 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009265
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009266 SourceLocation Open = E->getSourceRange().getBegin();
9267 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9268 Diag(Loc, diag::note_condition_assign_silence)
9269 << FixItHint::CreateInsertion(Open, "(")
9270 << FixItHint::CreateInsertion(Close, ")");
9271
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009272 if (IsOrAssign)
9273 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9274 << FixItHint::CreateReplacement(Loc, "!=");
9275 else
9276 Diag(Loc, diag::note_condition_assign_to_comparison)
9277 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009278}
9279
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009280/// \brief Redundant parentheses over an equality comparison can indicate
9281/// that the user intended an assignment used as condition.
9282void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009283 // Don't warn if the parens came from a macro.
9284 SourceLocation parenLoc = parenE->getLocStart();
9285 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9286 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009287 // Don't warn for dependent expressions.
9288 if (parenE->isTypeDependent())
9289 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009290
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009291 Expr *E = parenE->IgnoreParens();
9292
9293 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009294 if (opE->getOpcode() == BO_EQ &&
9295 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9296 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009297 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009298
Ted Kremenekae022092011-02-02 02:20:30 +00009299 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009300 Diag(Loc, diag::note_equality_comparison_silence)
9301 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9302 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009303 Diag(Loc, diag::note_equality_comparison_to_assign)
9304 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009305 }
9306}
9307
John Wiegley01296292011-04-08 18:41:53 +00009308ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009309 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009310 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9311 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009312
John McCall0009fcc2011-04-26 20:42:42 +00009313 ExprResult result = CheckPlaceholderExpr(E);
9314 if (result.isInvalid()) return ExprError();
9315 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009316
John McCall0009fcc2011-04-26 20:42:42 +00009317 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009318 if (getLangOptions().CPlusPlus)
9319 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9320
John Wiegley01296292011-04-08 18:41:53 +00009321 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9322 if (ERes.isInvalid())
9323 return ExprError();
9324 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009325
9326 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009327 if (!T->isScalarType()) { // C99 6.8.4.1p1
9328 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9329 << T << E->getSourceRange();
9330 return ExprError();
9331 }
John McCalld5707ab2009-10-12 21:59:07 +00009332 }
9333
John Wiegley01296292011-04-08 18:41:53 +00009334 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009335}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009336
John McCalldadc5752010-08-24 06:29:42 +00009337ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9338 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009339 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009340 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009341
9342 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009343}
John McCall36e7fe32010-10-12 00:20:44 +00009344
John McCall31996342011-04-07 08:22:57 +00009345namespace {
John McCall2979fe02011-04-12 00:42:48 +00009346 /// A visitor for rebuilding a call to an __unknown_any expression
9347 /// to have an appropriate type.
9348 struct RebuildUnknownAnyFunction
9349 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9350
9351 Sema &S;
9352
9353 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9354
9355 ExprResult VisitStmt(Stmt *S) {
9356 llvm_unreachable("unexpected statement!");
9357 return ExprError();
9358 }
9359
9360 ExprResult VisitExpr(Expr *expr) {
9361 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9362 << expr->getSourceRange();
9363 return ExprError();
9364 }
9365
9366 /// Rebuild an expression which simply semantically wraps another
9367 /// expression which it shares the type and value kind of.
9368 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9369 ExprResult subResult = Visit(expr->getSubExpr());
9370 if (subResult.isInvalid()) return ExprError();
9371
9372 Expr *subExpr = subResult.take();
9373 expr->setSubExpr(subExpr);
9374 expr->setType(subExpr->getType());
9375 expr->setValueKind(subExpr->getValueKind());
9376 assert(expr->getObjectKind() == OK_Ordinary);
9377 return expr;
9378 }
9379
9380 ExprResult VisitParenExpr(ParenExpr *paren) {
9381 return rebuildSugarExpr(paren);
9382 }
9383
9384 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9385 return rebuildSugarExpr(op);
9386 }
9387
9388 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9389 ExprResult subResult = Visit(op->getSubExpr());
9390 if (subResult.isInvalid()) return ExprError();
9391
9392 Expr *subExpr = subResult.take();
9393 op->setSubExpr(subExpr);
9394 op->setType(S.Context.getPointerType(subExpr->getType()));
9395 assert(op->getValueKind() == VK_RValue);
9396 assert(op->getObjectKind() == OK_Ordinary);
9397 return op;
9398 }
9399
9400 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9401 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9402
9403 expr->setType(decl->getType());
9404
9405 assert(expr->getValueKind() == VK_RValue);
9406 if (S.getLangOptions().CPlusPlus &&
9407 !(isa<CXXMethodDecl>(decl) &&
9408 cast<CXXMethodDecl>(decl)->isInstance()))
9409 expr->setValueKind(VK_LValue);
9410
9411 return expr;
9412 }
9413
9414 ExprResult VisitMemberExpr(MemberExpr *mem) {
9415 return resolveDecl(mem, mem->getMemberDecl());
9416 }
9417
9418 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9419 return resolveDecl(ref, ref->getDecl());
9420 }
9421 };
9422}
9423
9424/// Given a function expression of unknown-any type, try to rebuild it
9425/// to have a function type.
9426static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9427 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9428 if (result.isInvalid()) return ExprError();
9429 return S.DefaultFunctionArrayConversion(result.take());
9430}
9431
9432namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009433 /// A visitor for rebuilding an expression of type __unknown_anytype
9434 /// into one which resolves the type directly on the referring
9435 /// expression. Strict preservation of the original source
9436 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009437 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009438 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009439
9440 Sema &S;
9441
9442 /// The current destination type.
9443 QualType DestType;
9444
9445 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9446 : S(S), DestType(castType) {}
9447
John McCall39439732011-04-09 22:50:59 +00009448 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009449 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009450 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009451 }
9452
John McCall2d2e8702011-04-11 07:02:50 +00009453 ExprResult VisitExpr(Expr *expr) {
9454 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9455 << expr->getSourceRange();
9456 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009457 }
9458
John McCall2d2e8702011-04-11 07:02:50 +00009459 ExprResult VisitCallExpr(CallExpr *call);
9460 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9461
John McCall39439732011-04-09 22:50:59 +00009462 /// Rebuild an expression which simply semantically wraps another
9463 /// expression which it shares the type and value kind of.
9464 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9465 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009466 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009467 Expr *subExpr = subResult.take();
9468 expr->setSubExpr(subExpr);
9469 expr->setType(subExpr->getType());
9470 expr->setValueKind(subExpr->getValueKind());
9471 assert(expr->getObjectKind() == OK_Ordinary);
9472 return expr;
9473 }
John McCall31996342011-04-07 08:22:57 +00009474
John McCall39439732011-04-09 22:50:59 +00009475 ExprResult VisitParenExpr(ParenExpr *paren) {
9476 return rebuildSugarExpr(paren);
9477 }
9478
9479 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9480 return rebuildSugarExpr(op);
9481 }
9482
John McCall2979fe02011-04-12 00:42:48 +00009483 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9484 const PointerType *ptr = DestType->getAs<PointerType>();
9485 if (!ptr) {
9486 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9487 << op->getSourceRange();
9488 return ExprError();
9489 }
9490 assert(op->getValueKind() == VK_RValue);
9491 assert(op->getObjectKind() == OK_Ordinary);
9492 op->setType(DestType);
9493
9494 // Build the sub-expression as if it were an object of the pointee type.
9495 DestType = ptr->getPointeeType();
9496 ExprResult subResult = Visit(op->getSubExpr());
9497 if (subResult.isInvalid()) return ExprError();
9498 op->setSubExpr(subResult.take());
9499 return op;
9500 }
9501
John McCall2d2e8702011-04-11 07:02:50 +00009502 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009503
John McCall2979fe02011-04-12 00:42:48 +00009504 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009505
John McCall2979fe02011-04-12 00:42:48 +00009506 ExprResult VisitMemberExpr(MemberExpr *mem) {
9507 return resolveDecl(mem, mem->getMemberDecl());
9508 }
John McCall39439732011-04-09 22:50:59 +00009509
9510 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009511 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009512 }
9513 };
9514}
9515
John McCall2d2e8702011-04-11 07:02:50 +00009516/// Rebuilds a call expression which yielded __unknown_anytype.
9517ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9518 Expr *callee = call->getCallee();
9519
9520 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009521 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009522 FK_FunctionPointer,
9523 FK_BlockPointer
9524 };
9525
9526 FnKind kind;
9527 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009528 if (type == S.Context.BoundMemberTy) {
9529 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9530 kind = FK_MemberFunction;
9531 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009532 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9533 type = ptr->getPointeeType();
9534 kind = FK_FunctionPointer;
9535 } else {
9536 type = type->castAs<BlockPointerType>()->getPointeeType();
9537 kind = FK_BlockPointer;
9538 }
9539 const FunctionType *fnType = type->castAs<FunctionType>();
9540
9541 // Verify that this is a legal result type of a function.
9542 if (DestType->isArrayType() || DestType->isFunctionType()) {
9543 unsigned diagID = diag::err_func_returning_array_function;
9544 if (kind == FK_BlockPointer)
9545 diagID = diag::err_block_returning_array_function;
9546
9547 S.Diag(call->getExprLoc(), diagID)
9548 << DestType->isFunctionType() << DestType;
9549 return ExprError();
9550 }
9551
9552 // Otherwise, go ahead and set DestType as the call's result.
9553 call->setType(DestType.getNonLValueExprType(S.Context));
9554 call->setValueKind(Expr::getValueKindForType(DestType));
9555 assert(call->getObjectKind() == OK_Ordinary);
9556
9557 // Rebuild the function type, replacing the result type with DestType.
9558 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9559 DestType = S.Context.getFunctionType(DestType,
9560 proto->arg_type_begin(),
9561 proto->getNumArgs(),
9562 proto->getExtProtoInfo());
9563 else
9564 DestType = S.Context.getFunctionNoProtoType(DestType,
9565 fnType->getExtInfo());
9566
9567 // Rebuild the appropriate pointer-to-function type.
9568 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009569 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009570 // Nothing to do.
9571 break;
9572
9573 case FK_FunctionPointer:
9574 DestType = S.Context.getPointerType(DestType);
9575 break;
9576
9577 case FK_BlockPointer:
9578 DestType = S.Context.getBlockPointerType(DestType);
9579 break;
9580 }
9581
9582 // Finally, we can recurse.
9583 ExprResult calleeResult = Visit(callee);
9584 if (!calleeResult.isUsable()) return ExprError();
9585 call->setCallee(calleeResult.take());
9586
9587 // Bind a temporary if necessary.
9588 return S.MaybeBindToTemporary(call);
9589}
9590
9591ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009592 // Verify that this is a legal result type of a call.
9593 if (DestType->isArrayType() || DestType->isFunctionType()) {
9594 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9595 << DestType->isFunctionType() << DestType;
9596 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009597 }
9598
John McCall3f4138c2011-07-13 17:56:40 +00009599 // Rewrite the method result type if available.
9600 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9601 assert(method->getResultType() == S.Context.UnknownAnyTy);
9602 method->setResultType(DestType);
9603 }
John McCall2979fe02011-04-12 00:42:48 +00009604
John McCall2d2e8702011-04-11 07:02:50 +00009605 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009606 msg->setType(DestType.getNonReferenceType());
9607 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009608
John McCall2979fe02011-04-12 00:42:48 +00009609 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009610}
9611
9612ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009613 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009614 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009615 assert(ice->getValueKind() == VK_RValue);
9616 assert(ice->getObjectKind() == OK_Ordinary);
9617
John McCall2979fe02011-04-12 00:42:48 +00009618 ice->setType(DestType);
9619
John McCall2d2e8702011-04-11 07:02:50 +00009620 // Rebuild the sub-expression as the pointee (function) type.
9621 DestType = DestType->castAs<PointerType>()->getPointeeType();
9622
9623 ExprResult result = Visit(ice->getSubExpr());
9624 if (!result.isUsable()) return ExprError();
9625
9626 ice->setSubExpr(result.take());
9627 return S.Owned(ice);
9628}
9629
John McCall2979fe02011-04-12 00:42:48 +00009630ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009631 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009632 QualType type = DestType;
9633
9634 // We know how to make this work for certain kinds of decls:
9635
9636 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009637 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009638 // This is true because FunctionDecls must always have function
9639 // type, so we can't be resolving the entire thing at once.
9640 assert(type->isFunctionType());
9641
John McCall4adb38c2011-04-27 00:36:17 +00009642 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9643 if (method->isInstance()) {
9644 valueKind = VK_RValue;
9645 type = S.Context.BoundMemberTy;
9646 }
9647
John McCall2d2e8702011-04-11 07:02:50 +00009648 // Function references aren't l-values in C.
9649 if (!S.getLangOptions().CPlusPlus)
9650 valueKind = VK_RValue;
9651
9652 // - variables
9653 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009654 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9655 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009656 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009657 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9658 << decl << expr->getSourceRange();
9659 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009660 }
9661
9662 // - nothing else
9663 } else {
9664 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9665 << decl << expr->getSourceRange();
9666 return ExprError();
9667 }
9668
John McCall2979fe02011-04-12 00:42:48 +00009669 decl->setType(DestType);
9670 expr->setType(type);
9671 expr->setValueKind(valueKind);
9672 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009673}
9674
John McCall31996342011-04-07 08:22:57 +00009675/// Check a cast of an unknown-any type. We intentionally only
9676/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009677ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9678 Expr *castExpr, CastKind &castKind,
9679 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009680 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009681 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9682 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009683
John McCall39439732011-04-09 22:50:59 +00009684 castExpr = result.take();
9685 VK = castExpr->getValueKind();
9686 castKind = CK_NoOp;
9687
9688 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009689}
9690
9691static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9692 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009693 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009694 while (true) {
9695 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009696 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009697 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009698 diagID = diag::err_uncasted_call_of_unknown_any;
9699 } else {
John McCall31996342011-04-07 08:22:57 +00009700 break;
John McCall2d2e8702011-04-11 07:02:50 +00009701 }
John McCall31996342011-04-07 08:22:57 +00009702 }
9703
John McCall2d2e8702011-04-11 07:02:50 +00009704 SourceLocation loc;
9705 NamedDecl *d;
9706 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9707 loc = ref->getLocation();
9708 d = ref->getDecl();
9709 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9710 loc = mem->getMemberLoc();
9711 d = mem->getMemberDecl();
9712 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9713 diagID = diag::err_uncasted_call_of_unknown_any;
9714 loc = msg->getSelectorLoc();
9715 d = msg->getMethodDecl();
9716 assert(d && "unknown method returning __unknown_any?");
9717 } else {
9718 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9719 << e->getSourceRange();
9720 return ExprError();
9721 }
9722
9723 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009724
9725 // Never recoverable.
9726 return ExprError();
9727}
9728
John McCall36e7fe32010-10-12 00:20:44 +00009729/// Check for operands with placeholder types and complain if found.
9730/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009731ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009732 // Placeholder types are always *exactly* the appropriate builtin type.
9733 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009734
John McCall31996342011-04-07 08:22:57 +00009735 // Overloaded expressions.
9736 if (type == Context.OverloadTy)
9737 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009738 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009739 QualType(),
9740 diag::err_ovl_unresolvable);
9741
John McCall0009fcc2011-04-26 20:42:42 +00009742 // Bound member functions.
9743 if (type == Context.BoundMemberTy) {
9744 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9745 << E->getSourceRange();
9746 return ExprError();
9747 }
9748
John McCall31996342011-04-07 08:22:57 +00009749 // Expressions of unknown type.
9750 if (type == Context.UnknownAnyTy)
9751 return diagnoseUnknownAnyExpr(*this, E);
9752
9753 assert(!type->isPlaceholderType());
9754 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009755}
Richard Trieu2c850c02011-04-21 21:44:26 +00009756
9757bool Sema::CheckCaseExpression(Expr *expr) {
9758 if (expr->isTypeDependent())
9759 return true;
9760 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9761 return expr->getType()->isIntegralOrEnumerationType();
9762 return false;
9763}