blob: b99076005b24dc35335c90815f229c677fdfa2fc [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.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas 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 McCall34376a62010-12-04 03:47:34 +0000313
John McCall27584242010-12-06 20:48:59 +0000314 QualType T = E->getType();
315 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000316
John McCall27584242010-12-06 20:48:59 +0000317 // Create a load out of an ObjCProperty l-value, if necessary.
318 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000319 ExprResult Res = ConvertPropertyForRValue(E);
320 if (Res.isInvalid())
321 return Owned(E);
322 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000323 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000324 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000325 }
John McCall27584242010-12-06 20:48:59 +0000326
327 // We don't want to throw lvalue-to-rvalue casts on top of
328 // expressions of certain types in C++.
329 if (getLangOptions().CPlusPlus &&
330 (E->getType() == Context.OverloadTy ||
331 T->isDependentType() ||
332 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000333 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000334
335 // The C standard is actually really unclear on this point, and
336 // DR106 tells us what the result should be but not why. It's
337 // generally best to say that void types just doesn't undergo
338 // lvalue-to-rvalue at all. Note that expressions of unqualified
339 // 'void' type are never l-values, but qualified void can be.
340 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000341 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000342
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000343 CheckForNullPointerDereference(*this, E);
344
John McCall27584242010-12-06 20:48:59 +0000345 // C++ [conv.lval]p1:
346 // [...] If T is a non-class type, the type of the prvalue is the
347 // cv-unqualified version of T. Otherwise, the type of the
348 // rvalue is T.
349 //
350 // C99 6.3.2.1p2:
351 // If the lvalue has qualified type, the value has the unqualified
352 // version of the type of the lvalue; otherwise, the value has the
353 // type of the lvalue.
354 if (T.hasQualifiers())
355 T = T.getUnqualifiedType();
356
Ted Kremenekdf26df72011-03-01 18:41:00 +0000357 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000358
John Wiegley01296292011-04-08 18:41:53 +0000359 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
360 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000361}
362
John Wiegley01296292011-04-08 18:41:53 +0000363ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
364 ExprResult Res = DefaultFunctionArrayConversion(E);
365 if (Res.isInvalid())
366 return ExprError();
367 Res = DefaultLvalueConversion(Res.take());
368 if (Res.isInvalid())
369 return ExprError();
370 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000371}
372
373
Chris Lattner513165e2008-07-25 21:10:04 +0000374/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000375/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000376/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000377/// apply if the array is an argument to the sizeof or address (&) operators.
378/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000379ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000380 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000381 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
382 if (Res.isInvalid())
383 return Owned(E);
384 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000385
386 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000387 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000388
389 // Try to perform integral promotions if the object has a theoretically
390 // promotable type.
391 if (Ty->isIntegralOrUnscopedEnumerationType()) {
392 // C99 6.3.1.1p2:
393 //
394 // The following may be used in an expression wherever an int or
395 // unsigned int may be used:
396 // - an object or expression with an integer type whose integer
397 // conversion rank is less than or equal to the rank of int
398 // and unsigned int.
399 // - A bit-field of type _Bool, int, signed int, or unsigned int.
400 //
401 // If an int can represent all values of the original type, the
402 // value is converted to an int; otherwise, it is converted to an
403 // unsigned int. These are called the integer promotions. All
404 // other types are unchanged by the integer promotions.
405
406 QualType PTy = Context.isPromotableBitField(E);
407 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
409 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000410 }
411 if (Ty->isPromotableIntegerType()) {
412 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
414 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000415 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000416 }
John Wiegley01296292011-04-08 18:41:53 +0000417 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000418}
419
Chris Lattner2ce500f2008-07-25 22:25:12 +0000420/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000421/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000422/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000423ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
424 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000425 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000426
John Wiegley01296292011-04-08 18:41:53 +0000427 ExprResult Res = UsualUnaryConversions(E);
428 if (Res.isInvalid())
429 return Owned(E);
430 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000431
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000433 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
435
436 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000437}
438
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000439/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
440/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000441/// interfaces passed by value.
442ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000443 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000444 ExprResult ExprRes = CheckPlaceholderExpr(E);
445 if (ExprRes.isInvalid())
446 return ExprError();
447
448 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000449 if (ExprRes.isInvalid())
450 return ExprError();
451 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000453 // __builtin_va_start takes the second argument as a "varargs" argument, but
454 // it doesn't actually do anything with it. It doesn't need to be non-pod
455 // etc.
456 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000457 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000458
Douglas Gregor347e0f22011-05-21 19:26:31 +0000459 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000460 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000461 DiagRuntimeBehavior(E->getLocStart(), 0,
462 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
463 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000464 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000465
John McCall31168b02011-06-15 23:02:42 +0000466 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000467 // C++0x [expr.call]p7:
468 // Passing a potentially-evaluated argument of class type (Clause 9)
469 // having a non-trivial copy constructor, a non-trivial move constructor,
470 // or a non-trivial destructor, with no corresponding parameter,
471 // is conditionally-supported with implementation-defined semantics.
472 bool TrivialEnough = false;
473 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
474 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
475 if (Record->hasTrivialCopyConstructor() &&
476 Record->hasTrivialMoveConstructor() &&
477 Record->hasTrivialDestructor())
478 TrivialEnough = true;
479 }
480 }
John McCall31168b02011-06-15 23:02:42 +0000481
482 if (!TrivialEnough &&
483 getLangOptions().ObjCAutoRefCount &&
484 E->getType()->isObjCLifetimeType())
485 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000486
487 if (TrivialEnough) {
488 // Nothing to diagnose. This is okay.
489 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000490 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000491 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000492 << CT)) {
493 // Turn this into a trap.
494 CXXScopeSpec SS;
495 UnqualifiedId Name;
496 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
497 E->getLocStart());
498 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
499 if (TrapFn.isInvalid())
500 return ExprError();
501
502 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
503 MultiExprArg(), E->getLocEnd());
504 if (Call.isInvalid())
505 return ExprError();
506
507 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
508 Call.get(), E);
509 if (Comma.isInvalid())
510 return ExprError();
511
512 E = Comma.get();
513 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000514 }
515
John Wiegley01296292011-04-08 18:41:53 +0000516 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000517}
518
Chris Lattner513165e2008-07-25 21:10:04 +0000519/// UsualArithmeticConversions - Performs various conversions that are common to
520/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000521/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000522/// responsible for emitting appropriate error diagnostics.
523/// FIXME: verify the conversion rules for "complex int" are consistent with
524/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000525QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000526 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000527 if (!isCompAssign) {
528 lhsExpr = UsualUnaryConversions(lhsExpr.take());
529 if (lhsExpr.isInvalid())
530 return QualType();
531 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000532
John Wiegley01296292011-04-08 18:41:53 +0000533 rhsExpr = UsualUnaryConversions(rhsExpr.take());
534 if (rhsExpr.isInvalid())
535 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000536
Mike Stump11289f42009-09-09 15:08:12 +0000537 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000538 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000539 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000540 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000541 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000542 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000543
544 // If both types are identical, no conversion is needed.
545 if (lhs == rhs)
546 return lhs;
547
548 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
549 // The caller can deal with this (e.g. pointer + int).
550 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
551 return lhs;
552
John McCalld005ac92010-11-13 08:17:45 +0000553 // Apply unary and bitfield promotions to the LHS's type.
554 QualType lhs_unpromoted = lhs;
555 if (lhs->isPromotableIntegerType())
556 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000557 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000558 if (!LHSBitfieldPromoteTy.isNull())
559 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000560 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000561 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000562
John McCalld005ac92010-11-13 08:17:45 +0000563 // If both types are identical, no conversion is needed.
564 if (lhs == rhs)
565 return lhs;
566
567 // At this point, we have two different arithmetic types.
568
569 // Handle complex types first (C99 6.3.1.8p1).
570 bool LHSComplexFloat = lhs->isComplexType();
571 bool RHSComplexFloat = rhs->isComplexType();
572 if (LHSComplexFloat || RHSComplexFloat) {
573 // if we have an integer operand, the result is the complex type.
574
John McCallc5e62b42010-11-13 09:02:35 +0000575 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
576 if (rhs->isIntegerType()) {
577 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000578 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
579 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000580 } else {
581 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000582 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000583 }
John McCalld005ac92010-11-13 08:17:45 +0000584 return lhs;
585 }
586
John McCallc5e62b42010-11-13 09:02:35 +0000587 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
588 if (!isCompAssign) {
589 // int -> float -> _Complex float
590 if (lhs->isIntegerType()) {
591 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000592 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
593 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000594 } else {
595 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000597 }
598 }
John McCalld005ac92010-11-13 08:17:45 +0000599 return rhs;
600 }
601
602 // This handles complex/complex, complex/float, or float/complex.
603 // When both operands are complex, the shorter operand is converted to the
604 // type of the longer, and that is the type of the result. This corresponds
605 // to what is done when combining two real floating-point operands.
606 // The fun begins when size promotion occur across type domains.
607 // From H&S 6.3.4: When one operand is complex and the other is a real
608 // floating-point type, the less precise type is converted, within it's
609 // real or complex domain, to the precision of the other type. For example,
610 // when combining a "long double" with a "double _Complex", the
611 // "double _Complex" is promoted to "long double _Complex".
612 int order = Context.getFloatingTypeOrder(lhs, rhs);
613
614 // If both are complex, just cast to the more precise type.
615 if (LHSComplexFloat && RHSComplexFloat) {
616 if (order > 0) {
617 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000618 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000619 return lhs;
620
621 } else if (order < 0) {
622 // _Complex float -> _Complex double
623 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000624 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000625 return rhs;
626 }
627 return lhs;
628 }
629
630 // If just the LHS is complex, the RHS needs to be converted,
631 // and the LHS might need to be promoted.
632 if (LHSComplexFloat) {
633 if (order > 0) { // LHS is wider
634 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000635 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000636 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
637 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000638 return lhs;
639 }
640
641 // RHS is at least as wide. Find its corresponding complex type.
642 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
643
644 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000646
647 // _Complex float -> _Complex double
648 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000649 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000650
651 return result;
652 }
653
654 // Just the RHS is complex, so the LHS needs to be converted
655 // and the RHS might need to be promoted.
656 assert(RHSComplexFloat);
657
658 if (order < 0) { // RHS is wider
659 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000660 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000661 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000662 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
663 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000664 }
John McCalld005ac92010-11-13 08:17:45 +0000665 return rhs;
666 }
667
668 // LHS is at least as wide. Find its corresponding complex type.
669 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
670
671 // double -> _Complex double
672 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000673 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000674
675 // _Complex float -> _Complex double
676 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000677 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000678
679 return result;
680 }
681
682 // Now handle "real" floating types (i.e. float, double, long double).
683 bool LHSFloat = lhs->isRealFloatingType();
684 bool RHSFloat = rhs->isRealFloatingType();
685 if (LHSFloat || RHSFloat) {
686 // If we have two real floating types, convert the smaller operand
687 // to the bigger result.
688 if (LHSFloat && RHSFloat) {
689 int order = Context.getFloatingTypeOrder(lhs, rhs);
690 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000692 return lhs;
693 }
694
695 assert(order < 0 && "illegal float comparison");
696 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000697 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000698 return rhs;
699 }
700
701 // If we have an integer operand, the result is the real floating type.
702 if (LHSFloat) {
703 if (rhs->isIntegerType()) {
704 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000705 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000706 return lhs;
707 }
708
709 // Convert both sides to the appropriate complex float.
710 assert(rhs->isComplexIntegerType());
711 QualType result = Context.getComplexType(lhs);
712
713 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000714 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000715
716 // float -> _Complex float
717 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000719
720 return result;
721 }
722
723 assert(RHSFloat);
724 if (lhs->isIntegerType()) {
725 // Convert lhs to the rhs floating point type.
726 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000727 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000728 return rhs;
729 }
730
731 // Convert both sides to the appropriate complex float.
732 assert(lhs->isComplexIntegerType());
733 QualType result = Context.getComplexType(rhs);
734
735 // _Complex int -> _Complex float
736 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000737 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000738
739 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000740 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000741
742 return result;
743 }
744
745 // Handle GCC complex int extension.
746 // FIXME: if the operands are (int, _Complex long), we currently
747 // don't promote the complex. Also, signedness?
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750 if (lhsComplexInt && rhsComplexInt) {
751 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
752 rhsComplexInt->getElementType());
753 assert(order && "inequal types with equal element ordering");
754 if (order > 0) {
755 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000756 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000757 return lhs;
758 }
759
760 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000761 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000762 return rhs;
763 } else if (lhsComplexInt) {
764 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000765 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000766 return lhs;
767 } else if (rhsComplexInt) {
768 // int -> _Complex int
769 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000770 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000771 return rhs;
772 }
773
774 // Finally, we have two differing integer types.
775 // The rules for this case are in C99 6.3.1.8
776 int compare = Context.getIntegerTypeOrder(lhs, rhs);
777 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
778 rhsSigned = rhs->hasSignedIntegerRepresentation();
779 if (lhsSigned == rhsSigned) {
780 // Same signedness; use the higher-ranked type
781 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000782 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000783 return lhs;
784 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000785 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000786 return rhs;
787 } else if (compare != (lhsSigned ? 1 : -1)) {
788 // The unsigned type has greater than or equal rank to the
789 // signed type, so use the unsigned type
790 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000791 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000792 return lhs;
793 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000795 return rhs;
796 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
797 // The two types are different widths; if we are here, that
798 // means the signed type is larger than the unsigned type, so
799 // use the signed type.
800 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000802 return lhs;
803 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000805 return rhs;
806 } else {
807 // The signed type is higher-ranked than the unsigned type,
808 // but isn't actually any bigger (like unsigned int and long
809 // on most 32-bit systems). Use the unsigned type corresponding
810 // to the signed type.
811 QualType result =
812 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000813 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000814 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000816 return result;
817 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000818}
819
Chris Lattner513165e2008-07-25 21:10:04 +0000820//===----------------------------------------------------------------------===//
821// Semantic Analysis for various Expression Types
822//===----------------------------------------------------------------------===//
823
824
Peter Collingbourne91147592011-04-15 00:35:48 +0000825ExprResult
826Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
827 SourceLocation DefaultLoc,
828 SourceLocation RParenLoc,
829 Expr *ControllingExpr,
830 MultiTypeArg types,
831 MultiExprArg exprs) {
832 unsigned NumAssocs = types.size();
833 assert(NumAssocs == exprs.size());
834
835 ParsedType *ParsedTypes = types.release();
836 Expr **Exprs = exprs.release();
837
838 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
839 for (unsigned i = 0; i < NumAssocs; ++i) {
840 if (ParsedTypes[i])
841 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
842 else
843 Types[i] = 0;
844 }
845
846 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
847 ControllingExpr, Types, Exprs,
848 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000849 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000850 return ER;
851}
852
853ExprResult
854Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
855 SourceLocation DefaultLoc,
856 SourceLocation RParenLoc,
857 Expr *ControllingExpr,
858 TypeSourceInfo **Types,
859 Expr **Exprs,
860 unsigned NumAssocs) {
861 bool TypeErrorFound = false,
862 IsResultDependent = ControllingExpr->isTypeDependent(),
863 ContainsUnexpandedParameterPack
864 = ControllingExpr->containsUnexpandedParameterPack();
865
866 for (unsigned i = 0; i < NumAssocs; ++i) {
867 if (Exprs[i]->containsUnexpandedParameterPack())
868 ContainsUnexpandedParameterPack = true;
869
870 if (Types[i]) {
871 if (Types[i]->getType()->containsUnexpandedParameterPack())
872 ContainsUnexpandedParameterPack = true;
873
874 if (Types[i]->getType()->isDependentType()) {
875 IsResultDependent = true;
876 } else {
877 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
878 // complete object type other than a variably modified type."
879 unsigned D = 0;
880 if (Types[i]->getType()->isIncompleteType())
881 D = diag::err_assoc_type_incomplete;
882 else if (!Types[i]->getType()->isObjectType())
883 D = diag::err_assoc_type_nonobject;
884 else if (Types[i]->getType()->isVariablyModifiedType())
885 D = diag::err_assoc_type_variably_modified;
886
887 if (D != 0) {
888 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
889 << Types[i]->getTypeLoc().getSourceRange()
890 << Types[i]->getType();
891 TypeErrorFound = true;
892 }
893
894 // C1X 6.5.1.1p2 "No two generic associations in the same generic
895 // selection shall specify compatible types."
896 for (unsigned j = i+1; j < NumAssocs; ++j)
897 if (Types[j] && !Types[j]->getType()->isDependentType() &&
898 Context.typesAreCompatible(Types[i]->getType(),
899 Types[j]->getType())) {
900 Diag(Types[j]->getTypeLoc().getBeginLoc(),
901 diag::err_assoc_compatible_types)
902 << Types[j]->getTypeLoc().getSourceRange()
903 << Types[j]->getType()
904 << Types[i]->getType();
905 Diag(Types[i]->getTypeLoc().getBeginLoc(),
906 diag::note_compat_assoc)
907 << Types[i]->getTypeLoc().getSourceRange()
908 << Types[i]->getType();
909 TypeErrorFound = true;
910 }
911 }
912 }
913 }
914 if (TypeErrorFound)
915 return ExprError();
916
917 // If we determined that the generic selection is result-dependent, don't
918 // try to compute the result expression.
919 if (IsResultDependent)
920 return Owned(new (Context) GenericSelectionExpr(
921 Context, KeyLoc, ControllingExpr,
922 Types, Exprs, NumAssocs, DefaultLoc,
923 RParenLoc, ContainsUnexpandedParameterPack));
924
925 llvm::SmallVector<unsigned, 1> CompatIndices;
926 unsigned DefaultIndex = -1U;
927 for (unsigned i = 0; i < NumAssocs; ++i) {
928 if (!Types[i])
929 DefaultIndex = i;
930 else if (Context.typesAreCompatible(ControllingExpr->getType(),
931 Types[i]->getType()))
932 CompatIndices.push_back(i);
933 }
934
935 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
936 // type compatible with at most one of the types named in its generic
937 // association list."
938 if (CompatIndices.size() > 1) {
939 // We strip parens here because the controlling expression is typically
940 // parenthesized in macro definitions.
941 ControllingExpr = ControllingExpr->IgnoreParens();
942 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
943 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
944 << (unsigned) CompatIndices.size();
945 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
946 E = CompatIndices.end(); I != E; ++I) {
947 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
948 diag::note_compat_assoc)
949 << Types[*I]->getTypeLoc().getSourceRange()
950 << Types[*I]->getType();
951 }
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
956 // its controlling expression shall have type compatible with exactly one of
957 // the types named in its generic association list."
958 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
959 // We strip parens here because the controlling expression is typically
960 // parenthesized in macro definitions.
961 ControllingExpr = ControllingExpr->IgnoreParens();
962 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
963 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
964 return ExprError();
965 }
966
967 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
968 // type name that is compatible with the type of the controlling expression,
969 // then the result expression of the generic selection is the expression
970 // in that generic association. Otherwise, the result expression of the
971 // generic selection is the expression in the default generic association."
972 unsigned ResultIndex =
973 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
974
975 return Owned(new (Context) GenericSelectionExpr(
976 Context, KeyLoc, ControllingExpr,
977 Types, Exprs, NumAssocs, DefaultLoc,
978 RParenLoc, ContainsUnexpandedParameterPack,
979 ResultIndex));
980}
981
Steve Naroff83895f72007-09-16 03:34:24 +0000982/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000983/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
984/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
985/// multiple tokens. However, the common case is that StringToks points to one
986/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000987///
John McCalldadc5752010-08-24 06:29:42 +0000988ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000989Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000990 assert(NumStringToks && "Must have at least one string!");
991
Chris Lattner8a24e582009-01-16 18:51:42 +0000992 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000993 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000994 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000995
Chris Lattner23b7eb62007-06-15 23:05:46 +0000996 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000997 for (unsigned i = 0; i != NumStringToks; ++i)
998 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000999
Chris Lattner36fc8792008-02-11 00:02:17 +00001000 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001001 if (Literal.AnyWide)
1002 StrTy = Context.getWCharType();
1003 else if (Literal.Pascal)
1004 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001005
1006 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001007 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001008 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001009
Chris Lattner36fc8792008-02-11 00:02:17 +00001010 // Get an array type for the string, according to C99 6.4.5. This includes
1011 // the nul terminator character as well as the string length for pascal
1012 // strings.
1013 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001014 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001015 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattner5b183d82006-11-10 05:03:26 +00001017 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001018 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Anders Carlsson75245402011-04-14 00:40:03 +00001019 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001020 &StringTokLocs[0],
1021 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001022}
1023
John McCallc63de662011-02-02 13:00:07 +00001024enum CaptureResult {
1025 /// No capture is required.
1026 CR_NoCapture,
1027
1028 /// A capture is required.
1029 CR_Capture,
1030
John McCall351762c2011-02-07 10:33:21 +00001031 /// A by-ref capture is required.
1032 CR_CaptureByRef,
1033
John McCallc63de662011-02-02 13:00:07 +00001034 /// An error occurred when trying to capture the given variable.
1035 CR_Error
1036};
1037
1038/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001039///
John McCallc63de662011-02-02 13:00:07 +00001040/// \param var - the variable referenced
1041/// \param DC - the context which we couldn't capture through
1042static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001043diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001044 VarDecl *var, DeclContext *DC) {
1045 switch (S.ExprEvalContexts.back().Context) {
1046 case Sema::Unevaluated:
1047 // The argument will never be evaluated, so don't complain.
1048 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001049
John McCallc63de662011-02-02 13:00:07 +00001050 case Sema::PotentiallyEvaluated:
1051 case Sema::PotentiallyEvaluatedIfUsed:
1052 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001053
John McCallc63de662011-02-02 13:00:07 +00001054 case Sema::PotentiallyPotentiallyEvaluated:
1055 // FIXME: delay these!
1056 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001057 }
Mike Stump11289f42009-09-09 15:08:12 +00001058
John McCallc63de662011-02-02 13:00:07 +00001059 // Don't diagnose about capture if we're not actually in code right
1060 // now; in general, there are more appropriate places that will
1061 // diagnose this.
1062 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1063
John McCall92d627e2011-03-22 23:15:50 +00001064 // Certain madnesses can happen with parameter declarations, which
1065 // we want to ignore.
1066 if (isa<ParmVarDecl>(var)) {
1067 // - If the parameter still belongs to the translation unit, then
1068 // we're actually just using one parameter in the declaration of
1069 // the next. This is useful in e.g. VLAs.
1070 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1071 return CR_NoCapture;
1072
1073 // - This particular madness can happen in ill-formed default
1074 // arguments; claim it's okay and let downstream code handle it.
1075 if (S.CurContext == var->getDeclContext()->getParent())
1076 return CR_NoCapture;
1077 }
John McCallc63de662011-02-02 13:00:07 +00001078
1079 DeclarationName functionName;
1080 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1081 functionName = fn->getDeclName();
1082 // FIXME: variable from enclosing block that we couldn't capture from!
1083
1084 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1085 << var->getIdentifier() << functionName;
1086 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1087 << var->getIdentifier();
1088
1089 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001090}
1091
John McCall351762c2011-02-07 10:33:21 +00001092/// There is a well-formed capture at a particular scope level;
1093/// propagate it through all the nested blocks.
1094static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1095 const BlockDecl::Capture &capture) {
1096 VarDecl *var = capture.getVariable();
1097
1098 // Update all the inner blocks with the capture information.
1099 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1100 i != e; ++i) {
1101 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1102 innerBlock->Captures.push_back(
1103 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1104 /*nested*/ true, capture.getCopyExpr()));
1105 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1106 }
1107
1108 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1109}
1110
1111/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001112/// given value in the current context requires a variable capture.
1113///
1114/// This also keeps the captures set in the BlockScopeInfo records
1115/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001116static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001117 ValueDecl *value) {
1118 // Only variables ever require capture.
1119 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001120 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001121
1122 // Fast path: variables from the current context never require capture.
1123 DeclContext *DC = S.CurContext;
1124 if (var->getDeclContext() == DC) return CR_NoCapture;
1125
1126 // Only variables with local storage require capture.
1127 // FIXME: What about 'const' variables in C++?
1128 if (!var->hasLocalStorage()) return CR_NoCapture;
1129
1130 // Otherwise, we need to capture.
1131
1132 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001133 do {
1134 // Only blocks (and eventually C++0x closures) can capture; other
1135 // scopes don't work.
1136 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001137 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001138
1139 BlockScopeInfo *blockScope =
1140 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1141 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1142
John McCall351762c2011-02-07 10:33:21 +00001143 // Check whether we've already captured it in this block. If so,
1144 // we're done.
1145 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1146 return propagateCapture(S, functionScopesIndex,
1147 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001148
1149 functionScopesIndex--;
1150 DC = cast<BlockDecl>(DC)->getDeclContext();
1151 } while (var->getDeclContext() != DC);
1152
John McCall351762c2011-02-07 10:33:21 +00001153 // Okay, we descended all the way to the block that defines the variable.
1154 // Actually try to capture it.
1155 QualType type = var->getType();
1156
1157 // Prohibit variably-modified types.
1158 if (type->isVariablyModifiedType()) {
1159 S.Diag(loc, diag::err_ref_vm_type);
1160 S.Diag(var->getLocation(), diag::note_declared_at);
1161 return CR_Error;
1162 }
1163
1164 // Prohibit arrays, even in __block variables, but not references to
1165 // them.
1166 if (type->isArrayType()) {
1167 S.Diag(loc, diag::err_ref_array_type);
1168 S.Diag(var->getLocation(), diag::note_declared_at);
1169 return CR_Error;
1170 }
1171
1172 S.MarkDeclarationReferenced(loc, var);
1173
1174 // The BlocksAttr indicates the variable is bound by-reference.
1175 bool byRef = var->hasAttr<BlocksAttr>();
1176
1177 // Build a copy expression.
1178 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001179 const RecordType *rtype;
1180 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1181 (rtype = type->getAs<RecordType>())) {
1182
1183 // The capture logic needs the destructor, so make sure we mark it.
1184 // Usually this is unnecessary because most local variables have
1185 // their destructors marked at declaration time, but parameters are
1186 // an exception because it's technically only the call site that
1187 // actually requires the destructor.
1188 if (isa<ParmVarDecl>(var))
1189 S.FinalizeVarWithDestructor(var, rtype);
1190
John McCall351762c2011-02-07 10:33:21 +00001191 // According to the blocks spec, the capture of a variable from
1192 // the stack requires a const copy constructor. This is not true
1193 // of the copy/move done to move a __block variable to the heap.
1194 type.addConst();
1195
1196 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1197 ExprResult result =
1198 S.PerformCopyInitialization(
1199 InitializedEntity::InitializeBlock(var->getLocation(),
1200 type, false),
1201 loc, S.Owned(declRef));
1202
1203 // Build a full-expression copy expression if initialization
1204 // succeeded and used a non-trivial constructor. Recover from
1205 // errors by pretending that the copy isn't necessary.
1206 if (!result.isInvalid() &&
1207 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1208 result = S.MaybeCreateExprWithCleanups(result);
1209 copyExpr = result.take();
1210 }
1211 }
1212
1213 // We're currently at the declarer; go back to the closure.
1214 functionScopesIndex++;
1215 BlockScopeInfo *blockScope =
1216 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1217
1218 // Build a valid capture in this scope.
1219 blockScope->Captures.push_back(
1220 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1221 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1222
1223 // Propagate that to inner captures if necessary.
1224 return propagateCapture(S, functionScopesIndex,
1225 blockScope->Captures.back());
1226}
1227
1228static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1229 const DeclarationNameInfo &NameInfo,
1230 bool byRef) {
1231 assert(isa<VarDecl>(vd) && "capturing non-variable");
1232
1233 VarDecl *var = cast<VarDecl>(vd);
1234 assert(var->hasLocalStorage() && "capturing non-local");
1235 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1236
1237 QualType exprType = var->getType().getNonReferenceType();
1238
1239 BlockDeclRefExpr *BDRE;
1240 if (!byRef) {
1241 // The variable will be bound by copy; make it const within the
1242 // closure, but record that this was done in the expression.
1243 bool constAdded = !exprType.isConstQualified();
1244 exprType.addConst();
1245
1246 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1247 NameInfo.getLoc(), false,
1248 constAdded);
1249 } else {
1250 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1251 NameInfo.getLoc(), true);
1252 }
1253
1254 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001255}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001256
John McCalldadc5752010-08-24 06:29:42 +00001257ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001258Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001259 SourceLocation Loc,
1260 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001261 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001262 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001263}
1264
John McCallf4cd4f92011-02-09 01:13:10 +00001265/// BuildDeclRefExpr - Build an expression that references a
1266/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001267ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001268Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001269 const DeclarationNameInfo &NameInfo,
1270 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001271 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001272
John McCall086a4642010-11-24 05:12:34 +00001273 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001274 SS? SS->getWithLocInContext(Context)
1275 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001276 D, NameInfo, Ty, VK);
1277
1278 // Just in case we're building an illegal pointer-to-member.
1279 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1280 E->setObjectKind(OK_BitField);
1281
1282 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001283}
1284
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001285/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001286/// possibly a list of template arguments.
1287///
1288/// If this produces template arguments, it is permitted to call
1289/// DecomposeTemplateName.
1290///
1291/// This actually loses a lot of source location information for
1292/// non-standard name kinds; we should consider preserving that in
1293/// some way.
Douglas Gregor5476205b2011-06-23 00:49:38 +00001294void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1295 TemplateArgumentListInfo &Buffer,
1296 DeclarationNameInfo &NameInfo,
1297 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001298 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1299 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1300 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1301
Douglas Gregor5476205b2011-06-23 00:49:38 +00001302 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001303 Id.TemplateId->getTemplateArgs(),
1304 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001305 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001306 TemplateArgsPtr.release();
1307
John McCall3e56fd42010-08-23 07:28:44 +00001308 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001309 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001310 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001311 TemplateArgs = &Buffer;
1312 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001313 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001314 TemplateArgs = 0;
1315 }
1316}
1317
John McCalld681c392009-12-16 08:11:27 +00001318/// Diagnose an empty lookup.
1319///
1320/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001321bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1322 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001323 DeclarationName Name = R.getLookupName();
1324
John McCalld681c392009-12-16 08:11:27 +00001325 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001326 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001327 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1328 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001329 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001330 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001331 diagnostic_suggest = diag::err_undeclared_use_suggest;
1332 }
John McCalld681c392009-12-16 08:11:27 +00001333
Douglas Gregor598b08f2009-12-31 05:20:13 +00001334 // If the original lookup was an unqualified lookup, fake an
1335 // unqualified lookup. This is useful when (for example) the
1336 // original lookup would not have found something because it was a
1337 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001338 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001339 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001340 if (isa<CXXRecordDecl>(DC)) {
1341 LookupQualifiedName(R, DC);
1342
1343 if (!R.empty()) {
1344 // Don't give errors about ambiguities in this lookup.
1345 R.suppressDiagnostics();
1346
1347 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1348 bool isInstance = CurMethod &&
1349 CurMethod->isInstance() &&
1350 DC == CurMethod->getParent();
1351
1352 // Give a code modification hint to insert 'this->'.
1353 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1354 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001355 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001356 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1357 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001358 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001359 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001360 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001361 Diag(R.getNameLoc(), diagnostic) << Name
1362 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1363 QualType DepThisType = DepMethod->getThisType(Context);
1364 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1365 R.getNameLoc(), DepThisType, false);
1366 TemplateArgumentListInfo TList;
1367 if (ULE->hasExplicitTemplateArgs())
1368 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001369
Douglas Gregore16af532011-02-28 18:50:33 +00001370 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001371 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001372 CXXDependentScopeMemberExpr *DepExpr =
1373 CXXDependentScopeMemberExpr::Create(
1374 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001375 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001376 R.getLookupNameInfo(), &TList);
1377 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001378 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001379 // FIXME: we should be able to handle this case too. It is correct
1380 // to add this-> here. This is a workaround for PR7947.
1381 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001382 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001383 } else {
John McCalld681c392009-12-16 08:11:27 +00001384 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001385 }
John McCalld681c392009-12-16 08:11:27 +00001386
1387 // Do we really want to note all of these?
1388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1389 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1390
1391 // Tell the callee to try to recover.
1392 return false;
1393 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001394
1395 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001396 }
1397 }
1398
Douglas Gregor598b08f2009-12-31 05:20:13 +00001399 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001400 TypoCorrection Corrected;
1401 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1402 S, &SS, NULL, false, CTC))) {
1403 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1404 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1405 R.setLookupName(Corrected.getCorrection());
1406
1407 if (!Corrected.isKeyword()) {
1408 NamedDecl *ND = Corrected.getCorrectionDecl();
1409 R.addDecl(ND);
1410 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001411 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001412 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1413 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001414 else
1415 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001416 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001417 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001418 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1419 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001420 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001422
1423 // Tell the callee to try to recover.
1424 return false;
1425 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001426
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001427 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001428 // FIXME: If we ended up with a typo for a type name or
1429 // Objective-C class name, we're in trouble because the parser
1430 // is in the wrong place to recover. Suggest the typo
1431 // correction, but don't make it a fix-it since we're not going
1432 // to recover well anyway.
1433 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001434 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001435 else
1436 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001437 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001438 << SS.getRange();
1439
1440 // Don't try to recover; it won't work.
1441 return true;
1442 }
1443 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001444 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001445 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001446 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001447 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001448 else
Douglas Gregor25363982010-01-01 00:15:04 +00001449 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001450 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001451 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001452 return true;
1453 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001454 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001455 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001456
1457 // Emit a special diagnostic for failed member lookups.
1458 // FIXME: computing the declaration context might fail here (?)
1459 if (!SS.isEmpty()) {
1460 Diag(R.getNameLoc(), diag::err_no_member)
1461 << Name << computeDeclContext(SS, false)
1462 << SS.getRange();
1463 return true;
1464 }
1465
John McCalld681c392009-12-16 08:11:27 +00001466 // Give up, we can't recover.
1467 Diag(R.getNameLoc(), diagnostic) << Name;
1468 return true;
1469}
1470
Douglas Gregor05fcf842010-11-02 20:36:02 +00001471ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1472 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001473 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1474 if (!IDecl)
1475 return 0;
1476 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1477 if (!ClassImpDecl)
1478 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001479 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001480 if (!property)
1481 return 0;
1482 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001483 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1484 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001485 return 0;
1486 return property;
1487}
1488
Douglas Gregor05fcf842010-11-02 20:36:02 +00001489bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1490 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1491 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1492 if (!IDecl)
1493 return false;
1494 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1495 if (!ClassImpDecl)
1496 return false;
1497 if (ObjCPropertyImplDecl *PIDecl
1498 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1499 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1500 PIDecl->getPropertyIvarDecl())
1501 return false;
1502
1503 return true;
1504}
1505
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001506ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1507 IdentifierInfo *II,
1508 SourceLocation NameLoc) {
1509 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001510 bool LookForIvars;
1511 if (Lookup.empty())
1512 LookForIvars = true;
1513 else if (CurMeth->isClassMethod())
1514 LookForIvars = false;
1515 else
1516 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001517 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1518 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001519 if (!LookForIvars)
1520 return 0;
1521
Fariborz Jahanian18722982010-07-17 00:59:30 +00001522 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1523 if (!IDecl)
1524 return 0;
1525 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001526 if (!ClassImpDecl)
1527 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001528 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001529 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001530 if (!property)
1531 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001532 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001533 DynamicImplSeen =
1534 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001535 // property implementation has a designated ivar. No need to assume a new
1536 // one.
1537 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1538 return 0;
1539 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001540 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001541 QualType PropType = Context.getCanonicalType(property->getType());
1542 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001543 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001544 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001545 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001546 (Expr *)0, true);
1547 ClassImpDecl->addDecl(Ivar);
1548 IDecl->makeDeclVisibleInContext(Ivar, false);
1549 property->setPropertyIvarDecl(Ivar);
1550 return Ivar;
1551 }
1552 return 0;
1553}
1554
John McCalldadc5752010-08-24 06:29:42 +00001555ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001556 CXXScopeSpec &SS,
1557 UnqualifiedId &Id,
1558 bool HasTrailingLParen,
1559 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001560 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1561 "cannot be direct & operand and have a trailing lparen");
1562
1563 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001564 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001565
John McCall10eae182009-11-30 22:42:35 +00001566 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001567
1568 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001569 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001570 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001571 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001572
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001573 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001574 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001575 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001576
John McCalle66edc12009-11-24 19:00:30 +00001577 // C++ [temp.dep.expr]p3:
1578 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001579 // -- an identifier that was declared with a dependent type,
1580 // (note: handled after lookup)
1581 // -- a template-id that is dependent,
1582 // (note: handled in BuildTemplateIdExpr)
1583 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001584 // -- a nested-name-specifier that contains a class-name that
1585 // names a dependent type.
1586 // Determine whether this is a member of an unknown specialization;
1587 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001588 bool DependentID = false;
1589 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1590 Name.getCXXNameType()->isDependentType()) {
1591 DependentID = true;
1592 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001593 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001594 if (RequireCompleteDeclContext(SS, DC))
1595 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001596 } else {
1597 DependentID = true;
1598 }
1599 }
1600
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001601 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001602 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001603 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001604
Fariborz Jahanian86151342010-07-22 23:33:21 +00001605 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001606 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001607 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001608 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001609 // Lookup the template name again to correctly establish the context in
1610 // which it was found. This is really unfortunate as we already did the
1611 // lookup to determine that it was a template name in the first place. If
1612 // this becomes a performance hit, we can work harder to preserve those
1613 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001614 bool MemberOfUnknownSpecialization;
1615 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1616 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001617
1618 if (MemberOfUnknownSpecialization ||
1619 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1620 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1621 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001622 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001623 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001624 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Douglas Gregora5226932011-02-04 13:35:07 +00001626 // If the result might be in a dependent base class, this is a dependent
1627 // id-expression.
1628 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1629 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1630 TemplateArgs);
1631
John McCalle66edc12009-11-24 19:00:30 +00001632 // If this reference is in an Objective-C method, then we need to do
1633 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001634 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001635 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001636 if (E.isInvalid())
1637 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001639 if (Expr *Ex = E.takeAs<Expr>())
1640 return Owned(Ex);
1641
1642 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001643 if (getLangOptions().ObjCDefaultSynthProperties &&
1644 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001645 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001646 if (const ObjCPropertyDecl *Property =
1647 canSynthesizeProvisionalIvar(II)) {
1648 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1649 Diag(Property->getLocation(), diag::note_property_declare);
1650 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001651 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1652 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001653 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001654 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001655 // for further use, this must be set to false if in class method.
1656 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001657 }
Chris Lattner59a25942008-03-31 00:36:02 +00001658 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001659
John McCalle66edc12009-11-24 19:00:30 +00001660 if (R.isAmbiguous())
1661 return ExprError();
1662
Douglas Gregor171c45a2009-02-18 21:56:37 +00001663 // Determine whether this name might be a candidate for
1664 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001665 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001666
John McCalle66edc12009-11-24 19:00:30 +00001667 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001668 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001669 // in C90, extension in C99, forbidden in C++).
1670 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1671 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1672 if (D) R.addDecl(D);
1673 }
1674
1675 // If this name wasn't predeclared and if this is not a function
1676 // call, diagnose the problem.
1677 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001678 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001679 return ExprError();
1680
1681 assert(!R.empty() &&
1682 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001683
1684 // If we found an Objective-C instance variable, let
1685 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001686 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001687 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1688 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001689 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001690 assert(E.isInvalid() || E.get());
1691 return move(E);
1692 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001693 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCalle66edc12009-11-24 19:00:30 +00001696 // This is guaranteed from this point on.
1697 assert(!R.empty() || ADL);
1698
John McCall2d74de92009-12-01 22:10:20 +00001699 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001700 // C++ [class.mfct.non-static]p3:
1701 // When an id-expression that is not part of a class member access
1702 // syntax and not used to form a pointer to member is used in the
1703 // body of a non-static member function of class X, if name lookup
1704 // resolves the name in the id-expression to a non-static non-type
1705 // member of some class C, the id-expression is transformed into a
1706 // class member access expression using (*this) as the
1707 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001708 //
1709 // But we don't actually need to do this for '&' operands if R
1710 // resolved to a function or overloaded function set, because the
1711 // expression is ill-formed if it actually works out to be a
1712 // non-static member function:
1713 //
1714 // C++ [expr.ref]p4:
1715 // Otherwise, if E1.E2 refers to a non-static member function. . .
1716 // [t]he expression can be used only as the left-hand operand of a
1717 // member function call.
1718 //
1719 // There are other safeguards against such uses, but it's important
1720 // to get this right here so that we don't end up making a
1721 // spuriously dependent expression if we're inside a dependent
1722 // instance method.
John McCall57500772009-12-16 12:17:52 +00001723 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001724 bool MightBeImplicitMember;
1725 if (!isAddressOfOperand)
1726 MightBeImplicitMember = true;
1727 else if (!SS.isEmpty())
1728 MightBeImplicitMember = false;
1729 else if (R.isOverloadedResult())
1730 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001731 else if (R.isUnresolvableResult())
1732 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001733 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001734 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1735 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001736
1737 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001738 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001739 }
1740
John McCalle66edc12009-11-24 19:00:30 +00001741 if (TemplateArgs)
1742 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001743
John McCalle66edc12009-11-24 19:00:30 +00001744 return BuildDeclarationNameExpr(SS, R, ADL);
1745}
1746
John McCall10eae182009-11-30 22:42:35 +00001747/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1748/// declaration name, generally during template instantiation.
1749/// There's a large number of things which don't need to be done along
1750/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001751ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001752Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001753 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001754 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001755 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001756 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001757
John McCall0b66eb32010-05-01 00:40:08 +00001758 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001759 return ExprError();
1760
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001761 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001762 LookupQualifiedName(R, DC);
1763
1764 if (R.isAmbiguous())
1765 return ExprError();
1766
1767 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001768 Diag(NameInfo.getLoc(), diag::err_no_member)
1769 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001770 return ExprError();
1771 }
1772
1773 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1774}
1775
1776/// LookupInObjCMethod - The parser has read a name in, and Sema has
1777/// detected that we're currently inside an ObjC method. Perform some
1778/// additional lookup.
1779///
1780/// Ideally, most of this would be done by lookup, but there's
1781/// actually quite a lot of extra work involved.
1782///
1783/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001784ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001785Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001786 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001787 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001788 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001789
John McCalle66edc12009-11-24 19:00:30 +00001790 // There are two cases to handle here. 1) scoped lookup could have failed,
1791 // in which case we should look for an ivar. 2) scoped lookup could have
1792 // found a decl, but that decl is outside the current instance method (i.e.
1793 // a global variable). In these two cases, we do a lookup for an ivar with
1794 // this name, if the lookup sucedes, we replace it our current decl.
1795
1796 // If we're in a class method, we don't normally want to look for
1797 // ivars. But if we don't find anything else, and there's an
1798 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001799 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001800
1801 bool LookForIvars;
1802 if (Lookup.empty())
1803 LookForIvars = true;
1804 else if (IsClassMethod)
1805 LookForIvars = false;
1806 else
1807 LookForIvars = (Lookup.isSingleResult() &&
1808 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001809 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001810 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001811 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001812 ObjCInterfaceDecl *ClassDeclared;
1813 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1814 // Diagnose using an ivar in a class method.
1815 if (IsClassMethod)
1816 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1817 << IV->getDeclName());
1818
1819 // If we're referencing an invalid decl, just return this as a silent
1820 // error node. The error diagnostic was already emitted on the decl.
1821 if (IV->isInvalidDecl())
1822 return ExprError();
1823
1824 // Check if referencing a field with __attribute__((deprecated)).
1825 if (DiagnoseUseOfDecl(IV, Loc))
1826 return ExprError();
1827
1828 // Diagnose the use of an ivar outside of the declaring class.
1829 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1830 ClassDeclared != IFace)
1831 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1832
1833 // FIXME: This should use a new expr for a direct reference, don't
1834 // turn this into Self->ivar, just return a BareIVarExpr or something.
1835 IdentifierInfo &II = Context.Idents.get("self");
1836 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001837 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001838 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001839 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001840 SelfName, false, false);
1841 if (SelfExpr.isInvalid())
1842 return ExprError();
1843
John Wiegley01296292011-04-08 18:41:53 +00001844 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1845 if (SelfExpr.isInvalid())
1846 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001847
John McCalle66edc12009-11-24 19:00:30 +00001848 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00001849 Expr *base = SelfExpr.take();
1850 base = base->IgnoreParenImpCasts();
1851 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
1852 const NamedDecl *ND = DE->getDecl();
1853 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00001854 // relax the rule such that it is allowed to have a shadow 'self'
1855 // where stand-alone ivar can be found in this 'self' object.
1856 // This is to match gcc's behavior.
1857 ObjCInterfaceDecl *selfIFace = 0;
1858 if (const ObjCObjectPointerType *OPT =
1859 base->getType()->getAsObjCInterfacePointerType())
1860 selfIFace = OPT->getInterfaceDecl();
1861 if (!selfIFace ||
1862 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00001863 Diag(Loc, diag::error_implicit_ivar_access)
1864 << IV->getDeclName();
1865 Diag(ND->getLocation(), diag::note_declared_at);
1866 return ExprError();
1867 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00001868 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00001869 }
John McCalle66edc12009-11-24 19:00:30 +00001870 return Owned(new (Context)
1871 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001872 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001873 }
Chris Lattner87313662010-04-12 05:10:17 +00001874 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001875 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001877 ObjCInterfaceDecl *ClassDeclared;
1878 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1879 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1880 IFace == ClassDeclared)
1881 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1882 }
1883 }
1884
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001885 if (Lookup.empty() && II && AllowBuiltinCreation) {
1886 // FIXME. Consolidate this with similar code in LookupName.
1887 if (unsigned BuiltinID = II->getBuiltinID()) {
1888 if (!(getLangOptions().CPlusPlus &&
1889 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1890 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1891 S, Lookup.isForRedeclaration(),
1892 Lookup.getNameLoc());
1893 if (D) Lookup.addDecl(D);
1894 }
1895 }
1896 }
John McCalle66edc12009-11-24 19:00:30 +00001897 // Sentinel value saying that we didn't do anything special.
1898 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001899}
John McCalld14a8642009-11-21 08:51:07 +00001900
John McCall16df1e52010-03-30 21:47:33 +00001901/// \brief Cast a base object to a member's actual type.
1902///
1903/// Logically this happens in three phases:
1904///
1905/// * First we cast from the base type to the naming class.
1906/// The naming class is the class into which we were looking
1907/// when we found the member; it's the qualifier type if a
1908/// qualifier was provided, and otherwise it's the base type.
1909///
1910/// * Next we cast from the naming class to the declaring class.
1911/// If the member we found was brought into a class's scope by
1912/// a using declaration, this is that class; otherwise it's
1913/// the class declaring the member.
1914///
1915/// * Finally we cast from the declaring class to the "true"
1916/// declaring class of the member. This conversion does not
1917/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001918ExprResult
1919Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001920 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001921 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001922 NamedDecl *Member) {
1923 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1924 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001925 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001926
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001927 QualType DestRecordType;
1928 QualType DestType;
1929 QualType FromRecordType;
1930 QualType FromType = From->getType();
1931 bool PointerConversions = false;
1932 if (isa<FieldDecl>(Member)) {
1933 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001934
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001935 if (FromType->getAs<PointerType>()) {
1936 DestType = Context.getPointerType(DestRecordType);
1937 FromRecordType = FromType->getPointeeType();
1938 PointerConversions = true;
1939 } else {
1940 DestType = DestRecordType;
1941 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001942 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001943 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1944 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001945 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001946
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001947 DestType = Method->getThisType(Context);
1948 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001949
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 if (FromType->getAs<PointerType>()) {
1951 FromRecordType = FromType->getPointeeType();
1952 PointerConversions = true;
1953 } else {
1954 FromRecordType = FromType;
1955 DestType = DestRecordType;
1956 }
1957 } else {
1958 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001959 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001961
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001962 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001963 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001964
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 // If the unqualified types are the same, no conversion is necessary.
1966 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001967 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001968
John McCall16df1e52010-03-30 21:47:33 +00001969 SourceRange FromRange = From->getSourceRange();
1970 SourceLocation FromLoc = FromRange.getBegin();
1971
John McCall2536c6d2010-08-25 10:28:54 +00001972 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001973
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001975 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001976 // class name.
1977 //
1978 // If the member was a qualified name and the qualified referred to a
1979 // specific base subobject type, we'll cast to that intermediate type
1980 // first and then to the object in which the member is declared. That allows
1981 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1982 //
1983 // class Base { public: int x; };
1984 // class Derived1 : public Base { };
1985 // class Derived2 : public Base { };
1986 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1987 //
1988 // void VeryDerived::f() {
1989 // x = 17; // error: ambiguous base subobjects
1990 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1991 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001992 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001993 QualType QType = QualType(Qualifier->getAsType(), 0);
1994 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1995 assert(QType->isRecordType() && "lookup done with non-record type");
1996
1997 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1998
1999 // In C++98, the qualifier type doesn't actually have to be a base
2000 // type of the object type, in which case we just ignore it.
2001 // Otherwise build the appropriate casts.
2002 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002003 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002004 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002005 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002006 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002007
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002008 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002009 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002010 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2011 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002012
2013 FromType = QType;
2014 FromRecordType = QRecordType;
2015
2016 // If the qualifier type was the same as the destination type,
2017 // we're done.
2018 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002019 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002020 }
2021 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002022
John McCall16df1e52010-03-30 21:47:33 +00002023 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002024
John McCall16df1e52010-03-30 21:47:33 +00002025 // If we actually found the member through a using declaration, cast
2026 // down to the using declaration's type.
2027 //
2028 // Pointer equality is fine here because only one declaration of a
2029 // class ever has member declarations.
2030 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2031 assert(isa<UsingShadowDecl>(FoundDecl));
2032 QualType URecordType = Context.getTypeDeclType(
2033 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2034
2035 // We only need to do this if the naming-class to declaring-class
2036 // conversion is non-trivial.
2037 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2038 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002039 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002040 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002041 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002042 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002043
John McCall16df1e52010-03-30 21:47:33 +00002044 QualType UType = URecordType;
2045 if (PointerConversions)
2046 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002047 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2048 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002049 FromType = UType;
2050 FromRecordType = URecordType;
2051 }
2052
2053 // We don't do access control for the conversion from the
2054 // declaring class to the true declaring class.
2055 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002056 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002057
John McCallcf142162010-08-07 06:22:56 +00002058 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2060 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002061 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002062 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002063
John Wiegley01296292011-04-08 18:41:53 +00002064 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2065 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002066}
Douglas Gregor3256d042009-06-30 15:47:41 +00002067
John McCalle66edc12009-11-24 19:00:30 +00002068bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002069 const LookupResult &R,
2070 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002071 // Only when used directly as the postfix-expression of a call.
2072 if (!HasTrailingLParen)
2073 return false;
2074
2075 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002076 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002077 return false;
2078
2079 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002080 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002081 return false;
2082
2083 // Turn off ADL when we find certain kinds of declarations during
2084 // normal lookup:
2085 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2086 NamedDecl *D = *I;
2087
2088 // C++0x [basic.lookup.argdep]p3:
2089 // -- a declaration of a class member
2090 // Since using decls preserve this property, we check this on the
2091 // original decl.
John McCall57500772009-12-16 12:17:52 +00002092 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002093 return false;
2094
2095 // C++0x [basic.lookup.argdep]p3:
2096 // -- a block-scope function declaration that is not a
2097 // using-declaration
2098 // NOTE: we also trigger this for function templates (in fact, we
2099 // don't check the decl type at all, since all other decl types
2100 // turn off ADL anyway).
2101 if (isa<UsingShadowDecl>(D))
2102 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2103 else if (D->getDeclContext()->isFunctionOrMethod())
2104 return false;
2105
2106 // C++0x [basic.lookup.argdep]p3:
2107 // -- a declaration that is neither a function or a function
2108 // template
2109 // And also for builtin functions.
2110 if (isa<FunctionDecl>(D)) {
2111 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2112
2113 // But also builtin functions.
2114 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2115 return false;
2116 } else if (!isa<FunctionTemplateDecl>(D))
2117 return false;
2118 }
2119
2120 return true;
2121}
2122
2123
John McCalld14a8642009-11-21 08:51:07 +00002124/// Diagnoses obvious problems with the use of the given declaration
2125/// as an expression. This is only actually called for lookups that
2126/// were not overloaded, and it doesn't promise that the declaration
2127/// will in fact be used.
2128static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002129 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002130 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2131 return true;
2132 }
2133
2134 if (isa<ObjCInterfaceDecl>(D)) {
2135 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2136 return true;
2137 }
2138
2139 if (isa<NamespaceDecl>(D)) {
2140 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2141 return true;
2142 }
2143
2144 return false;
2145}
2146
John McCalldadc5752010-08-24 06:29:42 +00002147ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002148Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002149 LookupResult &R,
2150 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002151 // If this is a single, fully-resolved result and we don't need ADL,
2152 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002153 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002154 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2155 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002156
2157 // We only need to check the declaration if there's exactly one
2158 // result, because in the overloaded case the results can only be
2159 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002160 if (R.isSingleResult() &&
2161 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002162 return ExprError();
2163
John McCall58cc69d2010-01-27 01:50:18 +00002164 // Otherwise, just build an unresolved lookup expression. Suppress
2165 // any lookup-related diagnostics; we'll hash these out later, when
2166 // we've picked a target.
2167 R.suppressDiagnostics();
2168
John McCalld14a8642009-11-21 08:51:07 +00002169 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002170 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002171 SS.getWithLocInContext(Context),
2172 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002173 NeedsADL, R.isOverloadedResult(),
2174 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002175
2176 return Owned(ULE);
2177}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002178
John McCalld14a8642009-11-21 08:51:07 +00002179/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002180ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002181Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002182 const DeclarationNameInfo &NameInfo,
2183 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002184 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002185 assert(!isa<FunctionTemplateDecl>(D) &&
2186 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002187
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002188 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002189 if (CheckDeclInExpr(*this, Loc, D))
2190 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002191
Douglas Gregore7488b92009-12-01 16:58:18 +00002192 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2193 // Specifically diagnose references to class templates that are missing
2194 // a template argument list.
2195 Diag(Loc, diag::err_template_decl_ref)
2196 << Template << SS.getRange();
2197 Diag(Template->getLocation(), diag::note_template_decl_here);
2198 return ExprError();
2199 }
2200
2201 // Make sure that we're referring to a value.
2202 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2203 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002204 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002205 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002206 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002207 return ExprError();
2208 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002209
Douglas Gregor171c45a2009-02-18 21:56:37 +00002210 // Check whether this declaration can be used. Note that we suppress
2211 // this check when we're going to perform argument-dependent lookup
2212 // on this function name, because this might not be the function
2213 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002214 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002215 return ExprError();
2216
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002217 // Only create DeclRefExpr's for valid Decl's.
2218 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002219 return ExprError();
2220
John McCallf3a88602011-02-03 08:15:49 +00002221 // Handle members of anonymous structs and unions. If we got here,
2222 // and the reference is to a class member indirect field, then this
2223 // must be the subject of a pointer-to-member expression.
2224 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2225 if (!indirectField->isCXXClassMember())
2226 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2227 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002228
Chris Lattner2a9d9892008-10-20 05:16:36 +00002229 // If the identifier reference is inside a block, and it refers to a value
2230 // that is outside the block, create a BlockDeclRefExpr instead of a
2231 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2232 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002233 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002234 // We do not do this for things like enum constants, global variables, etc,
2235 // as they do not get snapshotted.
2236 //
John McCall351762c2011-02-07 10:33:21 +00002237 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002238 case CR_Error:
2239 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002240
John McCallc63de662011-02-02 13:00:07 +00002241 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002242 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2243 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2244
2245 case CR_CaptureByRef:
2246 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2247 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002248
2249 case CR_NoCapture: {
2250 // If this reference is not in a block or if the referenced
2251 // variable is within the block, create a normal DeclRefExpr.
2252
2253 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002254 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002255
2256 switch (D->getKind()) {
2257 // Ignore all the non-ValueDecl kinds.
2258#define ABSTRACT_DECL(kind)
2259#define VALUE(type, base)
2260#define DECL(type, base) \
2261 case Decl::type:
2262#include "clang/AST/DeclNodes.inc"
2263 llvm_unreachable("invalid value decl kind");
2264 return ExprError();
2265
2266 // These shouldn't make it here.
2267 case Decl::ObjCAtDefsField:
2268 case Decl::ObjCIvar:
2269 llvm_unreachable("forming non-member reference to ivar?");
2270 return ExprError();
2271
2272 // Enum constants are always r-values and never references.
2273 // Unresolved using declarations are dependent.
2274 case Decl::EnumConstant:
2275 case Decl::UnresolvedUsingValue:
2276 valueKind = VK_RValue;
2277 break;
2278
2279 // Fields and indirect fields that got here must be for
2280 // pointer-to-member expressions; we just call them l-values for
2281 // internal consistency, because this subexpression doesn't really
2282 // exist in the high-level semantics.
2283 case Decl::Field:
2284 case Decl::IndirectField:
2285 assert(getLangOptions().CPlusPlus &&
2286 "building reference to field in C?");
2287
2288 // These can't have reference type in well-formed programs, but
2289 // for internal consistency we do this anyway.
2290 type = type.getNonReferenceType();
2291 valueKind = VK_LValue;
2292 break;
2293
2294 // Non-type template parameters are either l-values or r-values
2295 // depending on the type.
2296 case Decl::NonTypeTemplateParm: {
2297 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2298 type = reftype->getPointeeType();
2299 valueKind = VK_LValue; // even if the parameter is an r-value reference
2300 break;
2301 }
2302
2303 // For non-references, we need to strip qualifiers just in case
2304 // the template parameter was declared as 'const int' or whatever.
2305 valueKind = VK_RValue;
2306 type = type.getUnqualifiedType();
2307 break;
2308 }
2309
2310 case Decl::Var:
2311 // In C, "extern void blah;" is valid and is an r-value.
2312 if (!getLangOptions().CPlusPlus &&
2313 !type.hasQualifiers() &&
2314 type->isVoidType()) {
2315 valueKind = VK_RValue;
2316 break;
2317 }
2318 // fallthrough
2319
2320 case Decl::ImplicitParam:
2321 case Decl::ParmVar:
2322 // These are always l-values.
2323 valueKind = VK_LValue;
2324 type = type.getNonReferenceType();
2325 break;
2326
2327 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002328 const FunctionType *fty = type->castAs<FunctionType>();
2329
2330 // If we're referring to a function with an __unknown_anytype
2331 // result type, make the entire expression __unknown_anytype.
2332 if (fty->getResultType() == Context.UnknownAnyTy) {
2333 type = Context.UnknownAnyTy;
2334 valueKind = VK_RValue;
2335 break;
2336 }
2337
John McCallf4cd4f92011-02-09 01:13:10 +00002338 // Functions are l-values in C++.
2339 if (getLangOptions().CPlusPlus) {
2340 valueKind = VK_LValue;
2341 break;
2342 }
2343
2344 // C99 DR 316 says that, if a function type comes from a
2345 // function definition (without a prototype), that type is only
2346 // used for checking compatibility. Therefore, when referencing
2347 // the function, we pretend that we don't have the full function
2348 // type.
John McCall2979fe02011-04-12 00:42:48 +00002349 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2350 isa<FunctionProtoType>(fty))
2351 type = Context.getFunctionNoProtoType(fty->getResultType(),
2352 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002353
2354 // Functions are r-values in C.
2355 valueKind = VK_RValue;
2356 break;
2357 }
2358
2359 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002360 // If we're referring to a method with an __unknown_anytype
2361 // result type, make the entire expression __unknown_anytype.
2362 // This should only be possible with a type written directly.
2363 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2364 if (proto->getResultType() == Context.UnknownAnyTy) {
2365 type = Context.UnknownAnyTy;
2366 valueKind = VK_RValue;
2367 break;
2368 }
2369
John McCallf4cd4f92011-02-09 01:13:10 +00002370 // C++ methods are l-values if static, r-values if non-static.
2371 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2372 valueKind = VK_LValue;
2373 break;
2374 }
2375 // fallthrough
2376
2377 case Decl::CXXConversion:
2378 case Decl::CXXDestructor:
2379 case Decl::CXXConstructor:
2380 valueKind = VK_RValue;
2381 break;
2382 }
2383
2384 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2385 }
2386
John McCallc63de662011-02-02 13:00:07 +00002387 }
John McCall7decc9e2010-11-18 06:31:45 +00002388
John McCall351762c2011-02-07 10:33:21 +00002389 llvm_unreachable("unknown capture result");
2390 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002391}
Chris Lattnere168f762006-11-10 05:29:30 +00002392
John McCall2979fe02011-04-12 00:42:48 +00002393ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002394 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002395
Chris Lattnere168f762006-11-10 05:29:30 +00002396 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002397 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002398 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2399 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2400 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002401 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002402
Chris Lattnera81a0272008-01-12 08:14:25 +00002403 // Pre-defined identifiers are of type char[x], where x is the length of the
2404 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002405
Anders Carlsson2fb08242009-09-08 18:24:21 +00002406 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002407 if (!currentDecl && getCurBlock())
2408 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002409 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002410 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002411 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002412 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002413
Anders Carlsson0b209a82009-09-11 01:22:35 +00002414 QualType ResTy;
2415 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2416 ResTy = Context.DependentTy;
2417 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002418 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002419
Anders Carlsson0b209a82009-09-11 01:22:35 +00002420 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002421 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002422 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2423 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002424 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002425}
2426
John McCalldadc5752010-08-24 06:29:42 +00002427ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002428 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002429 bool Invalid = false;
2430 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2431 if (Invalid)
2432 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002433
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002434 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2435 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002436 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002437 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002438
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002439 QualType Ty;
2440 if (!getLangOptions().CPlusPlus)
2441 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2442 else if (Literal.isWide())
2443 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002444 else if (Literal.isMultiChar())
2445 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002446 else
2447 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002448
Sebastian Redl20614a72009-01-20 22:23:13 +00002449 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2450 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002451 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002452}
2453
John McCalldadc5752010-08-24 06:29:42 +00002454ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002455 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002456 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2457 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002458 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002459 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002460 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002461 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002462 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002463
Chris Lattner23b7eb62007-06-15 23:05:46 +00002464 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002465 // Add padding so that NumericLiteralParser can overread by one character.
2466 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002467 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002468
Chris Lattner67ca9252007-05-21 01:08:44 +00002469 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002470 bool Invalid = false;
2471 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2472 if (Invalid)
2473 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002474
Mike Stump11289f42009-09-09 15:08:12 +00002475 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002476 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002477 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002478 return ExprError();
2479
Chris Lattner1c20a172007-08-26 03:42:43 +00002480 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002481
Chris Lattner1c20a172007-08-26 03:42:43 +00002482 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002483 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002484 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002485 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002486 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002487 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002488 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002489 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002490
2491 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2492
John McCall53b93a02009-12-24 09:08:04 +00002493 using llvm::APFloat;
2494 APFloat Val(Format);
2495
2496 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002497
2498 // Overflow is always an error, but underflow is only an error if
2499 // we underflowed to zero (APFloat reports denormals as underflow).
2500 if ((result & APFloat::opOverflow) ||
2501 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002502 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002503 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002504 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002505 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002506 APFloat::getLargest(Format).toString(buffer);
2507 } else {
John McCall62abc942010-02-26 23:35:57 +00002508 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002509 APFloat::getSmallest(Format).toString(buffer);
2510 }
2511
2512 Diag(Tok.getLocation(), diagnostic)
2513 << Ty
2514 << llvm::StringRef(buffer.data(), buffer.size());
2515 }
2516
2517 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002518 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002519
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002520 if (Ty == Context.DoubleTy) {
2521 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002522 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002523 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2524 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002525 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002526 }
2527 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002528 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002530 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002531 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002532
Neil Boothac582c52007-08-29 22:00:19 +00002533 // long long is a C99 feature.
2534 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002535 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002536 Diag(Tok.getLocation(), diag::ext_longlong);
2537
Chris Lattner67ca9252007-05-21 01:08:44 +00002538 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002539 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002540
Chris Lattner67ca9252007-05-21 01:08:44 +00002541 if (Literal.GetIntegerValue(ResultVal)) {
2542 // If this value didn't fit into uintmax_t, warn and force to ull.
2543 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002544 Ty = Context.UnsignedLongLongTy;
2545 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002546 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002547 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002548 // If this value fits into a ULL, try to figure out what else it fits into
2549 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550
Chris Lattner67ca9252007-05-21 01:08:44 +00002551 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2552 // be an unsigned int.
2553 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2554
2555 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002556 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002557 if (!Literal.isLong && !Literal.isLongLong) {
2558 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002559 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002560
Chris Lattner67ca9252007-05-21 01:08:44 +00002561 // Does it fit in a unsigned int?
2562 if (ResultVal.isIntN(IntSize)) {
2563 // Does it fit in a signed int?
2564 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002565 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002566 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002567 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002568 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002569 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002570 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002573 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002574 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002575
Chris Lattner67ca9252007-05-21 01:08:44 +00002576 // Does it fit in a unsigned long?
2577 if (ResultVal.isIntN(LongSize)) {
2578 // Does it fit in a signed long?
2579 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002580 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002581 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002582 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002583 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002584 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002585 }
2586
Chris Lattner67ca9252007-05-21 01:08:44 +00002587 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002588 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002589 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002590
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 // Does it fit in a unsigned long long?
2592 if (ResultVal.isIntN(LongLongSize)) {
2593 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002594 // To be compatible with MSVC, hex integer literals ending with the
2595 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002596 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2597 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002598 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002599 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002600 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002601 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 }
2603 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002604
Chris Lattner67ca9252007-05-21 01:08:44 +00002605 // If we still couldn't decide a type, we probably have something that
2606 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002607 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002608 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002609 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002610 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002611 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002612
Chris Lattner55258cf2008-05-09 05:59:00 +00002613 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002614 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002615 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002616 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002617 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002618
Chris Lattner1c20a172007-08-26 03:42:43 +00002619 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2620 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002621 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002622 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002623
2624 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002625}
2626
John McCalldadc5752010-08-24 06:29:42 +00002627ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002628 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002629 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002630 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002631}
2632
Chandler Carruth62da79c2011-05-26 08:53:12 +00002633static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2634 SourceLocation Loc,
2635 SourceRange ArgRange) {
2636 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2637 // scalar or vector data type argument..."
2638 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2639 // type (C99 6.2.5p18) or void.
2640 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2641 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2642 << T << ArgRange;
2643 return true;
2644 }
2645
2646 assert((T->isVoidType() || !T->isIncompleteType()) &&
2647 "Scalar types should always be complete");
2648 return false;
2649}
2650
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002651static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2652 SourceLocation Loc,
2653 SourceRange ArgRange,
2654 UnaryExprOrTypeTrait TraitKind) {
2655 // C99 6.5.3.4p1:
2656 if (T->isFunctionType()) {
2657 // alignof(function) is allowed as an extension.
2658 if (TraitKind == UETT_SizeOf)
2659 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2660 return false;
2661 }
2662
2663 // Allow sizeof(void)/alignof(void) as an extension.
2664 if (T->isVoidType()) {
2665 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2666 return false;
2667 }
2668
2669 return true;
2670}
2671
2672static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2673 SourceLocation Loc,
2674 SourceRange ArgRange,
2675 UnaryExprOrTypeTrait TraitKind) {
2676 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2677 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2678 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2679 << T << (TraitKind == UETT_SizeOf)
2680 << ArgRange;
2681 return true;
2682 }
2683
2684 return false;
2685}
2686
Chandler Carruth14502c22011-05-26 08:53:10 +00002687/// \brief Check the constrains on expression operands to unary type expression
2688/// and type traits.
2689///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002690/// Completes any types necessary and validates the constraints on the operand
2691/// expression. The logic mostly mirrors the type-based overload, but may modify
2692/// the expression as it completes the type for that expression through template
2693/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002694bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2695 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002696 QualType ExprTy = Op->getType();
2697
2698 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2699 // the result is the size of the referenced type."
2700 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2701 // result shall be the alignment of the referenced type."
2702 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2703 ExprTy = Ref->getPointeeType();
2704
2705 if (ExprKind == UETT_VecStep)
2706 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2707 Op->getSourceRange());
2708
2709 // Whitelist some types as extensions
2710 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2711 Op->getSourceRange(), ExprKind))
2712 return false;
2713
2714 if (RequireCompleteExprType(Op,
2715 PDiag(diag::err_sizeof_alignof_incomplete_type)
2716 << ExprKind << Op->getSourceRange(),
2717 std::make_pair(SourceLocation(), PDiag(0))))
2718 return true;
2719
2720 // Completeing the expression's type may have changed it.
2721 ExprTy = Op->getType();
2722 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2723 ExprTy = Ref->getPointeeType();
2724
2725 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2726 Op->getSourceRange(), ExprKind))
2727 return true;
2728
Nico Weber0870deb2011-06-15 02:47:03 +00002729 if (ExprKind == UETT_SizeOf) {
2730 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2731 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2732 QualType OType = PVD->getOriginalType();
2733 QualType Type = PVD->getType();
2734 if (Type->isPointerType() && OType->isArrayType()) {
2735 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2736 << Type << OType;
2737 Diag(PVD->getLocation(), diag::note_declared_at);
2738 }
2739 }
2740 }
2741 }
2742
Chandler Carruth7c430c02011-05-27 01:33:31 +00002743 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002744}
2745
2746/// \brief Check the constraints on operands to unary expression and type
2747/// traits.
2748///
2749/// This will complete any types necessary, and validate the various constraints
2750/// on those operands.
2751///
Steve Naroff71b59a92007-06-04 22:22:31 +00002752/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002753/// C99 6.3.2.1p[2-4] all state:
2754/// Except when it is the operand of the sizeof operator ...
2755///
2756/// C++ [expr.sizeof]p4
2757/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2758/// standard conversions are not applied to the operand of sizeof.
2759///
2760/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002761bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2762 SourceLocation OpLoc,
2763 SourceRange ExprRange,
2764 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002765 if (exprType->isDependentType())
2766 return false;
2767
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002768 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2769 // the result is the size of the referenced type."
2770 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2771 // result shall be the alignment of the referenced type."
2772 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2773 exprType = Ref->getPointeeType();
2774
Chandler Carruth62da79c2011-05-26 08:53:12 +00002775 if (ExprKind == UETT_VecStep)
2776 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002777
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002778 // Whitelist some types as extensions
2779 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2780 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002781 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002782
Chris Lattner62975a72009-04-24 00:30:45 +00002783 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002784 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002785 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002786 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002788 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2789 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002790 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Chris Lattner62975a72009-04-24 00:30:45 +00002792 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002793}
2794
Chandler Carruth14502c22011-05-26 08:53:10 +00002795static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002796 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002797
Mike Stump11289f42009-09-09 15:08:12 +00002798 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002799 if (isa<DeclRefExpr>(E))
2800 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002801
2802 // Cannot know anything else if the expression is dependent.
2803 if (E->isTypeDependent())
2804 return false;
2805
Douglas Gregor71235ec2009-05-02 02:18:30 +00002806 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002807 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2808 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002809 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002810 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002811
2812 // Alignment of a field access is always okay, so long as it isn't a
2813 // bit-field.
2814 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002815 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002816 return false;
2817
Chandler Carruth14502c22011-05-26 08:53:10 +00002818 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002819}
2820
Chandler Carruth14502c22011-05-26 08:53:10 +00002821bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002822 E = E->IgnoreParens();
2823
2824 // Cannot know anything else if the expression is dependent.
2825 if (E->isTypeDependent())
2826 return false;
2827
Chandler Carruth14502c22011-05-26 08:53:10 +00002828 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002829}
2830
Douglas Gregor0950e412009-03-13 21:01:28 +00002831/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002832ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002833Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2834 SourceLocation OpLoc,
2835 UnaryExprOrTypeTrait ExprKind,
2836 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002837 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002838 return ExprError();
2839
John McCallbcd03502009-12-07 02:54:59 +00002840 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002841
Douglas Gregor0950e412009-03-13 21:01:28 +00002842 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002843 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002844 return ExprError();
2845
2846 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002847 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2848 Context.getSizeType(),
2849 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002850}
2851
2852/// \brief Build a sizeof or alignof expression given an expression
2853/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002854ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002855Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2856 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002857 ExprResult PE = CheckPlaceholderExpr(E);
2858 if (PE.isInvalid())
2859 return ExprError();
2860
2861 E = PE.get();
2862
Douglas Gregor0950e412009-03-13 21:01:28 +00002863 // Verify that the operand is valid.
2864 bool isInvalid = false;
2865 if (E->isTypeDependent()) {
2866 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002867 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002868 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002869 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002870 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002871 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002872 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002873 isInvalid = true;
2874 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002875 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002876 }
2877
2878 if (isInvalid)
2879 return ExprError();
2880
2881 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002882 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002883 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002884 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002885}
2886
Peter Collingbournee190dee2011-03-11 19:24:49 +00002887/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2888/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002889/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002890ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002891Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2892 UnaryExprOrTypeTrait ExprKind, bool isType,
2893 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002894 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002895 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002896
Sebastian Redl6f282892008-11-11 17:56:53 +00002897 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002898 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002899 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002900 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002901 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002902
Douglas Gregor0950e412009-03-13 21:01:28 +00002903 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002904 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002905 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002906}
2907
John Wiegley01296292011-04-08 18:41:53 +00002908static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002909 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002910 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002911 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002912
John McCall34376a62010-12-04 03:47:34 +00002913 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002914 if (V.get()->getObjectKind() != OK_Ordinary) {
2915 V = S.DefaultLvalueConversion(V.take());
2916 if (V.isInvalid())
2917 return QualType();
2918 }
John McCall34376a62010-12-04 03:47:34 +00002919
Chris Lattnere267f5d2007-08-26 05:39:26 +00002920 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002921 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002922 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002923
Chris Lattnere267f5d2007-08-26 05:39:26 +00002924 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002925 if (V.get()->getType()->isArithmeticType())
2926 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002927
John McCall36226622010-10-12 02:09:17 +00002928 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002929 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002930 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002931 if (PR.get() != V.get()) {
2932 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002933 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002934 }
2935
Chris Lattnere267f5d2007-08-26 05:39:26 +00002936 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002937 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002938 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002939 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002940}
2941
2942
Chris Lattnere168f762006-11-10 05:29:30 +00002943
John McCalldadc5752010-08-24 06:29:42 +00002944ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002945Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002946 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002947 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002948 switch (Kind) {
2949 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002950 case tok::plusplus: Opc = UO_PostInc; break;
2951 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002952 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002953
John McCallb268a282010-08-23 23:25:46 +00002954 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002955}
2956
John McCalldadc5752010-08-24 06:29:42 +00002957ExprResult
John McCallb268a282010-08-23 23:25:46 +00002958Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2959 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002960 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002961 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002962 if (Result.isInvalid()) return ExprError();
2963 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002964
John McCallb268a282010-08-23 23:25:46 +00002965 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002966
Douglas Gregor40412ac2008-11-19 17:17:41 +00002967 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002968 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002969 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002970 Context.DependentTy,
2971 VK_LValue, OK_Ordinary,
2972 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002973 }
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002976 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002977 LHSExp->getType()->isEnumeralType() ||
2978 RHSExp->getType()->isRecordType() ||
2979 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002980 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002981 }
2982
John McCallb268a282010-08-23 23:25:46 +00002983 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002984}
2985
2986
John McCalldadc5752010-08-24 06:29:42 +00002987ExprResult
John McCallb268a282010-08-23 23:25:46 +00002988Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2989 Expr *Idx, SourceLocation RLoc) {
2990 Expr *LHSExp = Base;
2991 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002992
Chris Lattner36d572b2007-07-16 00:14:47 +00002993 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00002994 if (!LHSExp->getType()->getAs<VectorType>()) {
2995 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2996 if (Result.isInvalid())
2997 return ExprError();
2998 LHSExp = Result.take();
2999 }
3000 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3001 if (Result.isInvalid())
3002 return ExprError();
3003 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003004
Chris Lattner36d572b2007-07-16 00:14:47 +00003005 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003006 ExprValueKind VK = VK_LValue;
3007 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003008
Steve Naroffc1aadb12007-03-28 21:49:40 +00003009 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003010 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003011 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003012 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003013 Expr *BaseExpr, *IndexExpr;
3014 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003015 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3016 BaseExpr = LHSExp;
3017 IndexExpr = RHSExp;
3018 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003019 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003020 BaseExpr = LHSExp;
3021 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003022 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003023 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003024 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003025 BaseExpr = RHSExp;
3026 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003027 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003028 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003029 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003030 BaseExpr = LHSExp;
3031 IndexExpr = RHSExp;
3032 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003033 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003034 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003035 // Handle the uncommon case of "123[Ptr]".
3036 BaseExpr = RHSExp;
3037 IndexExpr = LHSExp;
3038 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003039 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003040 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003041 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003042 VK = LHSExp->getValueKind();
3043 if (VK != VK_RValue)
3044 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003045
Chris Lattner36d572b2007-07-16 00:14:47 +00003046 // FIXME: need to deal with const...
3047 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003048 } else if (LHSTy->isArrayType()) {
3049 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003050 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003051 // wasn't promoted because of the C90 rule that doesn't
3052 // allow promoting non-lvalue arrays. Warn, then
3053 // force the promotion here.
3054 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3055 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003056 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3057 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003058 LHSTy = LHSExp->getType();
3059
3060 BaseExpr = LHSExp;
3061 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003062 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003063 } else if (RHSTy->isArrayType()) {
3064 // Same as previous, except for 123[f().a] case
3065 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3066 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003067 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3068 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003069 RHSTy = RHSExp->getType();
3070
3071 BaseExpr = RHSExp;
3072 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003073 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003074 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003075 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3076 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003077 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003078 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003079 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003080 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3081 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003082
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003083 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003084 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3085 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003086 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3087
Douglas Gregorac1fb652009-03-24 19:52:54 +00003088 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003089 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3090 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003091 // incomplete types are not object types.
3092 if (ResultType->isFunctionType()) {
3093 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3094 << ResultType << BaseExpr->getSourceRange();
3095 return ExprError();
3096 }
Mike Stump11289f42009-09-09 15:08:12 +00003097
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003098 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3099 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003100 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3101 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003102
3103 // C forbids expressions of unqualified void type from being l-values.
3104 // See IsCForbiddenLValueType.
3105 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003106 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003107 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003108 PDiag(diag::err_subscript_incomplete_type)
3109 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003110 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003111
Chris Lattner62975a72009-04-24 00:30:45 +00003112 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003113 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003114 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3115 << ResultType << BaseExpr->getSourceRange();
3116 return ExprError();
3117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
John McCall4bc41ae2010-11-18 19:01:18 +00003119 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003120 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003121
Mike Stump4e1f26a2009-02-19 03:04:26 +00003122 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003123 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003124}
3125
John McCalldadc5752010-08-24 06:29:42 +00003126ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003127 FunctionDecl *FD,
3128 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003129 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003130 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003131 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003132 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003133 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003134 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003135 return ExprError();
3136 }
3137
3138 if (Param->hasUninstantiatedDefaultArg()) {
3139 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003140
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003141 // Instantiate the expression.
3142 MultiLevelTemplateArgumentList ArgList
3143 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003144
Nico Weber44887f62010-11-29 18:19:25 +00003145 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003146 = ArgList.getInnermost();
3147 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3148 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003149
Nico Weber44887f62010-11-29 18:19:25 +00003150 ExprResult Result;
3151 {
3152 // C++ [dcl.fct.default]p5:
3153 // The names in the [default argument] expression are bound, and
3154 // the semantic constraints are checked, at the point where the
3155 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003156 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003157 Result = SubstExpr(UninstExpr, ArgList);
3158 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003159 if (Result.isInvalid())
3160 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003162 // Check the expression as an initializer for the parameter.
3163 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003164 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003165 InitializationKind Kind
3166 = InitializationKind::CreateCopy(Param->getLocation(),
3167 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3168 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003169
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003170 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3171 Result = InitSeq.Perform(*this, Entity, Kind,
3172 MultiExprArg(*this, &ResultE, 1));
3173 if (Result.isInvalid())
3174 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003175
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003176 // Build the default argument expression.
3177 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3178 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003179 }
3180
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003181 // If the default expression creates temporaries, we need to
3182 // push them to the current stack of expression temporaries so they'll
3183 // be properly destroyed.
3184 // FIXME: We should really be rebuilding the default argument with new
3185 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003186 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3187 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3188 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3189 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3190 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003191 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003192 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003193
3194 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003195 // Just mark all of the declarations in this potentially-evaluated expression
3196 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003197 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003198 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003199}
3200
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003201/// ConvertArgumentsForCall - Converts the arguments specified in
3202/// Args/NumArgs to the parameter types of the function FDecl with
3203/// function prototype Proto. Call is the call expression itself, and
3204/// Fn is the function expression. For a C++ member function, this
3205/// routine does not attempt to convert the object argument. Returns
3206/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003207bool
3208Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003209 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003210 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003211 Expr **Args, unsigned NumArgs,
3212 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003213 // Bail out early if calling a builtin with custom typechecking.
3214 // We don't need to do this in the
3215 if (FDecl)
3216 if (unsigned ID = FDecl->getBuiltinID())
3217 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3218 return false;
3219
Mike Stump4e1f26a2009-02-19 03:04:26 +00003220 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003221 // assignment, to the types of the corresponding parameter, ...
3222 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003223 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003224
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003225 // If too few arguments are available (and we don't have default
3226 // arguments for the remaining parameters), don't make the call.
3227 if (NumArgs < NumArgsInProto) {
3228 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3229 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003230 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003231 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003232 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003233 }
3234
3235 // If too many are passed and not variadic, error on the extras and drop
3236 // them.
3237 if (NumArgs > NumArgsInProto) {
3238 if (!Proto->isVariadic()) {
3239 Diag(Args[NumArgsInProto]->getLocStart(),
3240 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003241 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003242 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003243 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3244 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003245
3246 // Emit the location of the prototype.
3247 if (FDecl && !FDecl->getBuiltinID())
3248 Diag(FDecl->getLocStart(),
3249 diag::note_typecheck_call_too_many_args)
3250 << FDecl;
3251
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003252 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003253 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003254 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003255 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003256 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003257 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003258 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003259 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3260 if (Fn->getType()->isBlockPointerType())
3261 CallType = VariadicBlock; // Block
3262 else if (isa<MemberExpr>(Fn))
3263 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003264 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003265 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003266 if (Invalid)
3267 return true;
3268 unsigned TotalNumArgs = AllArgs.size();
3269 for (unsigned i = 0; i < TotalNumArgs; ++i)
3270 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003271
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003272 return false;
3273}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003274
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003275bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3276 FunctionDecl *FDecl,
3277 const FunctionProtoType *Proto,
3278 unsigned FirstProtoArg,
3279 Expr **Args, unsigned NumArgs,
3280 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003281 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003282 unsigned NumArgsInProto = Proto->getNumArgs();
3283 unsigned NumArgsToCheck = NumArgs;
3284 bool Invalid = false;
3285 if (NumArgs != NumArgsInProto)
3286 // Use default arguments for missing arguments
3287 NumArgsToCheck = NumArgsInProto;
3288 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003289 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003290 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003291 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003292
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003293 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003294 if (ArgIx < NumArgs) {
3295 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003296
Eli Friedman3164fb12009-03-22 22:00:50 +00003297 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3298 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003299 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003300 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003301 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003302
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003303 // Pass the argument
3304 ParmVarDecl *Param = 0;
3305 if (FDecl && i < FDecl->getNumParams())
3306 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003307
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003308 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003309 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003310 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3311 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003312 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003313 SourceLocation(),
3314 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003315 if (ArgE.isInvalid())
3316 return true;
3317
3318 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003319 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003320 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003321
John McCalldadc5752010-08-24 06:29:42 +00003322 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003323 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003324 if (ArgExpr.isInvalid())
3325 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003326
Anders Carlsson355933d2009-08-25 03:49:14 +00003327 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003328 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003330 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003331
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003332 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003333 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003334
3335 // Assume that extern "C" functions with variadic arguments that
3336 // return __unknown_anytype aren't *really* variadic.
3337 if (Proto->getResultType() == Context.UnknownAnyTy &&
3338 FDecl && FDecl->isExternC()) {
3339 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3340 ExprResult arg;
3341 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3342 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3343 else
3344 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3345 Invalid |= arg.isInvalid();
3346 AllArgs.push_back(arg.take());
3347 }
3348
3349 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3350 } else {
3351 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3352 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3353 Invalid |= Arg.isInvalid();
3354 AllArgs.push_back(Arg.take());
3355 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003356 }
3357 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003358 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003359}
3360
John McCall2979fe02011-04-12 00:42:48 +00003361/// Given a function expression of unknown-any type, try to rebuild it
3362/// to have a function type.
3363static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3364
Steve Naroff83895f72007-09-16 03:34:24 +00003365/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003366/// This provides the location of the left/right parens and a list of comma
3367/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003368ExprResult
John McCallb268a282010-08-23 23:25:46 +00003369Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003370 MultiExprArg args, SourceLocation RParenLoc,
3371 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003372 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003373
3374 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003375 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003376 if (Result.isInvalid()) return ExprError();
3377 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003378
John McCallb268a282010-08-23 23:25:46 +00003379 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003380
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003381 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003382 // If this is a pseudo-destructor expression, build the call immediately.
3383 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3384 if (NumArgs > 0) {
3385 // Pseudo-destructor calls should not have any arguments.
3386 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003387 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003388 SourceRange(Args[0]->getLocStart(),
3389 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003390
Douglas Gregorad8a3362009-09-04 17:36:40 +00003391 NumArgs = 0;
3392 }
Mike Stump11289f42009-09-09 15:08:12 +00003393
Douglas Gregorad8a3362009-09-04 17:36:40 +00003394 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003395 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003396 }
Mike Stump11289f42009-09-09 15:08:12 +00003397
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003398 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003399 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003400 // FIXME: Will need to cache the results of name lookup (including ADL) in
3401 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003402 bool Dependent = false;
3403 if (Fn->isTypeDependent())
3404 Dependent = true;
3405 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3406 Dependent = true;
3407
Peter Collingbourne41f85462011-02-09 21:07:24 +00003408 if (Dependent) {
3409 if (ExecConfig) {
3410 return Owned(new (Context) CUDAKernelCallExpr(
3411 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3412 Context.DependentTy, VK_RValue, RParenLoc));
3413 } else {
3414 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3415 Context.DependentTy, VK_RValue,
3416 RParenLoc));
3417 }
3418 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003419
3420 // Determine whether this is a call to an object (C++ [over.call.object]).
3421 if (Fn->getType()->isRecordType())
3422 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003423 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003424
John McCall2979fe02011-04-12 00:42:48 +00003425 if (Fn->getType() == Context.UnknownAnyTy) {
3426 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3427 if (result.isInvalid()) return ExprError();
3428 Fn = result.take();
3429 }
3430
John McCall0009fcc2011-04-26 20:42:42 +00003431 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003432 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003433 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003434 }
John McCall0009fcc2011-04-26 20:42:42 +00003435 }
John McCall10eae182009-11-30 22:42:35 +00003436
John McCall0009fcc2011-04-26 20:42:42 +00003437 // Check for overloaded calls. This can happen even in C due to extensions.
3438 if (Fn->getType() == Context.OverloadTy) {
3439 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3440
3441 // We aren't supposed to apply this logic if there's an '&' involved.
3442 if (!find.IsAddressOfOperand) {
3443 OverloadExpr *ovl = find.Expression;
3444 if (isa<UnresolvedLookupExpr>(ovl)) {
3445 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3446 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3447 RParenLoc, ExecConfig);
3448 } else {
John McCall2d74de92009-12-01 22:10:20 +00003449 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003450 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003451 }
3452 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003453 }
3454
Douglas Gregore254f902009-02-04 00:32:51 +00003455 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003456
Eli Friedmane14b1992009-12-26 03:35:45 +00003457 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003458
John McCall57500772009-12-16 12:17:52 +00003459 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003460 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3461 if (UnOp->getOpcode() == UO_AddrOf)
3462 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3463
John McCall57500772009-12-16 12:17:52 +00003464 if (isa<DeclRefExpr>(NakedFn))
3465 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003466 else if (isa<MemberExpr>(NakedFn))
3467 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003468
Peter Collingbourne41f85462011-02-09 21:07:24 +00003469 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3470 ExecConfig);
3471}
3472
3473ExprResult
3474Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3475 MultiExprArg execConfig, SourceLocation GGGLoc) {
3476 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3477 if (!ConfigDecl)
3478 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3479 << "cudaConfigureCall");
3480 QualType ConfigQTy = ConfigDecl->getType();
3481
3482 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3483 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3484
3485 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003486}
3487
Tanya Lattner55808c12011-06-04 00:47:47 +00003488/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3489///
3490/// __builtin_astype( value, dst type )
3491///
3492ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3493 SourceLocation BuiltinLoc,
3494 SourceLocation RParenLoc) {
3495 ExprValueKind VK = VK_RValue;
3496 ExprObjectKind OK = OK_Ordinary;
3497 QualType DstTy = GetTypeFromParser(destty);
3498 QualType SrcTy = expr->getType();
3499 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3500 return ExprError(Diag(BuiltinLoc,
3501 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003502 << DstTy
3503 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003504 << expr->getSourceRange());
3505 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3506}
3507
John McCall57500772009-12-16 12:17:52 +00003508/// BuildResolvedCallExpr - Build a call to a resolved expression,
3509/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003510/// unary-convert to an expression of function-pointer or
3511/// block-pointer type.
3512///
3513/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003514ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003515Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3516 SourceLocation LParenLoc,
3517 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003518 SourceLocation RParenLoc,
3519 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003520 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3521
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003522 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003523 ExprResult Result = UsualUnaryConversions(Fn);
3524 if (Result.isInvalid())
3525 return ExprError();
3526 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003527
Chris Lattner08464942007-12-28 05:29:59 +00003528 // Make the call expr early, before semantic checks. This guarantees cleanup
3529 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003530 CallExpr *TheCall;
3531 if (Config) {
3532 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3533 cast<CallExpr>(Config),
3534 Args, NumArgs,
3535 Context.BoolTy,
3536 VK_RValue,
3537 RParenLoc);
3538 } else {
3539 TheCall = new (Context) CallExpr(Context, Fn,
3540 Args, NumArgs,
3541 Context.BoolTy,
3542 VK_RValue,
3543 RParenLoc);
3544 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003545
John McCallbebede42011-02-26 05:39:39 +00003546 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3547
3548 // Bail out early if calling a builtin with custom typechecking.
3549 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3550 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3551
John McCall31996342011-04-07 08:22:57 +00003552 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003553 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003554 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003555 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3556 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003557 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003558 if (FuncT == 0)
3559 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3560 << Fn->getType() << Fn->getSourceRange());
3561 } else if (const BlockPointerType *BPT =
3562 Fn->getType()->getAs<BlockPointerType>()) {
3563 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3564 } else {
John McCall31996342011-04-07 08:22:57 +00003565 // Handle calls to expressions of unknown-any type.
3566 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003567 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003568 if (rewrite.isInvalid()) return ExprError();
3569 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003570 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003571 goto retry;
3572 }
3573
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003574 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3575 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003576 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003577
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003578 if (getLangOptions().CUDA) {
3579 if (Config) {
3580 // CUDA: Kernel calls must be to global functions
3581 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3582 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3583 << FDecl->getName() << Fn->getSourceRange());
3584
3585 // CUDA: Kernel function must have 'void' return type
3586 if (!FuncT->getResultType()->isVoidType())
3587 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3588 << Fn->getType() << Fn->getSourceRange());
3589 }
3590 }
3591
Eli Friedman3164fb12009-03-22 22:00:50 +00003592 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003593 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003594 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003595 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003596 return ExprError();
3597
Chris Lattner08464942007-12-28 05:29:59 +00003598 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003599 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003600 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003601
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003602 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003603 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003604 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003605 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003606 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003607 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003608
Douglas Gregord8e97de2009-04-02 15:37:10 +00003609 if (FDecl) {
3610 // Check if we have too few/too many template arguments, based
3611 // on our knowledge of the function definition.
3612 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003613 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003614 const FunctionProtoType *Proto
3615 = Def->getType()->getAs<FunctionProtoType>();
3616 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003617 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3618 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003619 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003620
3621 // If the function we're calling isn't a function prototype, but we have
3622 // a function prototype from a prior declaratiom, use that prototype.
3623 if (!FDecl->hasPrototype())
3624 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003625 }
3626
Steve Naroff0b661582007-08-28 23:30:39 +00003627 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003628 for (unsigned i = 0; i != NumArgs; i++) {
3629 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003630
3631 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003632 InitializedEntity Entity
3633 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003634 Proto->getArgType(i),
3635 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003636 ExprResult ArgE = PerformCopyInitialization(Entity,
3637 SourceLocation(),
3638 Owned(Arg));
3639 if (ArgE.isInvalid())
3640 return true;
3641
3642 Arg = ArgE.takeAs<Expr>();
3643
3644 } else {
John Wiegley01296292011-04-08 18:41:53 +00003645 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3646
3647 if (ArgE.isInvalid())
3648 return true;
3649
3650 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003651 }
3652
Douglas Gregor83025412010-10-26 05:45:40 +00003653 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3654 Arg->getType(),
3655 PDiag(diag::err_call_incomplete_argument)
3656 << Arg->getSourceRange()))
3657 return ExprError();
3658
Chris Lattner08464942007-12-28 05:29:59 +00003659 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003660 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003661 }
Chris Lattner08464942007-12-28 05:29:59 +00003662
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003663 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3664 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003665 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3666 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003667
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003668 // Check for sentinels
3669 if (NDecl)
3670 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003671
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003672 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003673 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003674 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003675 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003676
John McCallbebede42011-02-26 05:39:39 +00003677 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003678 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003679 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003680 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003681 return ExprError();
3682 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003683
John McCallb268a282010-08-23 23:25:46 +00003684 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003685}
3686
John McCalldadc5752010-08-24 06:29:42 +00003687ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003688Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003689 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003690 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003691 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003692 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003693
3694 TypeSourceInfo *TInfo;
3695 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3696 if (!TInfo)
3697 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3698
John McCallb268a282010-08-23 23:25:46 +00003699 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003700}
3701
John McCalldadc5752010-08-24 06:29:42 +00003702ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003703Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003704 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003705 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003706
Eli Friedman37a186d2008-05-20 05:22:08 +00003707 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003708 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3709 PDiag(diag::err_illegal_decl_array_incomplete_type)
3710 << SourceRange(LParenLoc,
3711 literalExpr->getSourceRange().getEnd())))
3712 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003713 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003714 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3715 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003716 } else if (!literalType->isDependentType() &&
3717 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003718 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003719 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003720 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003721 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003722
Douglas Gregor85dabae2009-12-16 01:38:02 +00003723 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003724 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003725 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003726 = InitializationKind::CreateCStyleCast(LParenLoc,
3727 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003728 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003729 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003730 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003731 &literalType);
3732 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003733 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003734 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003735
Chris Lattner79413952008-12-04 23:50:19 +00003736 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003737 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003738 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003739 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003740 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003741
John McCall7decc9e2010-11-18 06:31:45 +00003742 // In C, compound literals are l-values for some reason.
3743 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3744
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003745 return MaybeBindToTemporary(
3746 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3747 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003748}
3749
John McCalldadc5752010-08-24 06:29:42 +00003750ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003751Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003752 SourceLocation RBraceLoc) {
3753 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003754 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003755
Steve Naroff30d242c2007-09-15 18:49:24 +00003756 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003757 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003758
Ted Kremenekac034612010-04-13 23:39:13 +00003759 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3760 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003761 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003762 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003763}
3764
John McCalld7646252010-11-14 08:17:51 +00003765/// Prepares for a scalar cast, performing all the necessary stages
3766/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003767static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003768 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3769 // Also, callers should have filtered out the invalid cases with
3770 // pointers. Everything else should be possible.
3771
John Wiegley01296292011-04-08 18:41:53 +00003772 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003773 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003774 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003775
John McCall8cb679e2010-11-15 09:13:47 +00003776 switch (SrcTy->getScalarTypeKind()) {
3777 case Type::STK_MemberPointer:
3778 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003779
John McCall8cb679e2010-11-15 09:13:47 +00003780 case Type::STK_Pointer:
3781 switch (DestTy->getScalarTypeKind()) {
3782 case Type::STK_Pointer:
3783 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003784 CK_AnyPointerToObjCPointerCast :
3785 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003786 case Type::STK_Bool:
3787 return CK_PointerToBoolean;
3788 case Type::STK_Integral:
3789 return CK_PointerToIntegral;
3790 case Type::STK_Floating:
3791 case Type::STK_FloatingComplex:
3792 case Type::STK_IntegralComplex:
3793 case Type::STK_MemberPointer:
3794 llvm_unreachable("illegal cast from pointer");
3795 }
3796 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003797
John McCall8cb679e2010-11-15 09:13:47 +00003798 case Type::STK_Bool: // casting from bool is like casting from an integer
3799 case Type::STK_Integral:
3800 switch (DestTy->getScalarTypeKind()) {
3801 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003802 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003803 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003804 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003805 case Type::STK_Bool:
3806 return CK_IntegralToBoolean;
3807 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003808 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003809 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003810 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003811 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003812 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3813 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003814 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003815 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003816 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3817 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003818 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003819 case Type::STK_MemberPointer:
3820 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003821 }
3822 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003823
John McCall8cb679e2010-11-15 09:13:47 +00003824 case Type::STK_Floating:
3825 switch (DestTy->getScalarTypeKind()) {
3826 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003827 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003828 case Type::STK_Bool:
3829 return CK_FloatingToBoolean;
3830 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003831 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003832 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003833 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3834 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003835 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003836 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003837 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3838 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003839 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003840 case Type::STK_Pointer:
3841 llvm_unreachable("valid float->pointer cast?");
3842 case Type::STK_MemberPointer:
3843 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003844 }
3845 break;
3846
John McCall8cb679e2010-11-15 09:13:47 +00003847 case Type::STK_FloatingComplex:
3848 switch (DestTy->getScalarTypeKind()) {
3849 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003850 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003851 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003852 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003853 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003854 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003855 if (S.Context.hasSameType(ET, DestTy))
3856 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003857 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003858 return CK_FloatingCast;
3859 }
John McCall8cb679e2010-11-15 09:13:47 +00003860 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003861 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003862 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003863 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3864 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003865 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003866 case Type::STK_Pointer:
3867 llvm_unreachable("valid complex float->pointer cast?");
3868 case Type::STK_MemberPointer:
3869 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003870 }
3871 break;
3872
John McCall8cb679e2010-11-15 09:13:47 +00003873 case Type::STK_IntegralComplex:
3874 switch (DestTy->getScalarTypeKind()) {
3875 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003876 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003877 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003878 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003879 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003880 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003881 if (S.Context.hasSameType(ET, DestTy))
3882 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003883 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003884 return CK_IntegralCast;
3885 }
John McCall8cb679e2010-11-15 09:13:47 +00003886 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003887 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003888 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003889 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3890 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003891 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003892 case Type::STK_Pointer:
3893 llvm_unreachable("valid complex int->pointer cast?");
3894 case Type::STK_MemberPointer:
3895 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003896 }
3897 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003898 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003899
John McCalld7646252010-11-14 08:17:51 +00003900 llvm_unreachable("Unhandled scalar cast");
3901 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003902}
3903
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003904/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003905ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3906 QualType castType, Expr *castExpr,
3907 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003908 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003909 if (castExpr->getType() == Context.UnknownAnyTy)
3910 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3911
Sebastian Redl9f831db2009-07-25 15:41:38 +00003912 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003913 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003914 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003915 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003916 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003917
John McCall3aef3d82011-04-10 19:13:55 +00003918 assert(!castExpr->getType()->isPlaceholderType());
3919
John McCall7decc9e2010-11-18 06:31:45 +00003920 // We only support r-value casts in C.
3921 VK = VK_RValue;
3922
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003923 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3924 // type needs to be scalar.
3925 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003926 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003927 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3928 if (castExprRes.isInvalid())
3929 return ExprError();
3930 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003931
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003932 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003933 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003934 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003935 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003936
John Wiegley01296292011-04-08 18:41:53 +00003937 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3938 if (castExprRes.isInvalid())
3939 return ExprError();
3940 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003941
Eli Friedmane98194d2010-07-17 20:43:49 +00003942 if (RequireCompleteType(TyR.getBegin(), castType,
3943 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003944 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003945
Anders Carlssonef918ac2009-10-16 02:35:04 +00003946 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003947 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003948 (castType->isStructureType() || castType->isUnionType())) {
3949 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003950 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003951 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3952 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003953 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003954 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003955 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003956
Anders Carlsson525b76b2009-10-16 02:48:28 +00003957 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003958 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003959 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003960 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003961 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003962 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003963 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003964 castExpr->getType()) &&
3965 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003966 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3967 << castExpr->getSourceRange();
3968 break;
3969 }
3970 }
John Wiegley01296292011-04-08 18:41:53 +00003971 if (Field == FieldEnd) {
3972 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003973 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003974 return ExprError();
3975 }
John McCalle3027922010-08-25 11:45:40 +00003976 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00003977 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003978 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
Anders Carlsson525b76b2009-10-16 02:48:28 +00003980 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00003981 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00003982 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003983 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003985
John McCalld7646252010-11-14 08:17:51 +00003986 // The type we're casting to is known to be a scalar or vector.
3987
3988 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003989 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003990 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00003991 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003992 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003993 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003994 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003995 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003996
3997 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00003998 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003999
Anton Yartsev28ccef72011-03-27 09:32:40 +00004000 if (castType->isVectorType()) {
4001 if (castType->getAs<VectorType>()->getVectorKind() ==
4002 VectorType::AltiVecVector &&
4003 (castExpr->getType()->isIntegerType() ||
4004 castExpr->getType()->isFloatingType())) {
4005 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004006 return Owned(castExpr);
4007 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4008 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004009 } else
John Wiegley01296292011-04-08 18:41:53 +00004010 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004011 }
John Wiegley01296292011-04-08 18:41:53 +00004012 if (castExpr->getType()->isVectorType()) {
4013 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4014 return ExprError();
4015 else
4016 return Owned(castExpr);
4017 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004018
John McCalld7646252010-11-14 08:17:51 +00004019 // The source and target types are both scalars, i.e.
4020 // - arithmetic types (fundamental, enum, and complex)
4021 // - all kinds of pointers
4022 // Note that member pointers were filtered out with C++, above.
4023
John Wiegley01296292011-04-08 18:41:53 +00004024 if (isa<ObjCSelectorExpr>(castExpr)) {
4025 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4026 return ExprError();
4027 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004028
John McCalld7646252010-11-14 08:17:51 +00004029 // If either type is a pointer, the other type has to be either an
4030 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004031 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004032 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004033 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004034 castExprType->isArithmeticType()) {
4035 Diag(castExpr->getLocStart(),
4036 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004037 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004038 return ExprError();
4039 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004040 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004041 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4042 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004043 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004044 return ExprError();
4045 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004046 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004047
John McCall31168b02011-06-15 23:02:42 +00004048 if (getLangOptions().ObjCAutoRefCount) {
4049 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4050 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4051 castType, castExpr, CCK_CStyleCast);
4052
4053 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4054 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4055 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4056 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4057 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4058 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4059 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4060 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004061 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004062 << castExprType << castType << AA_Casting
4063 << castExpr->getSourceRange();
4064
4065 return ExprError();
4066 }
4067 }
4068 }
4069 }
4070
John Wiegley01296292011-04-08 18:41:53 +00004071 castExprRes = Owned(castExpr);
4072 Kind = PrepareScalarCast(*this, castExprRes, castType);
4073 if (castExprRes.isInvalid())
4074 return ExprError();
4075 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004076
John McCalld7646252010-11-14 08:17:51 +00004077 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004078 CheckCastAlign(castExpr, castType, TyR);
4079
John Wiegley01296292011-04-08 18:41:53 +00004080 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004081}
4082
Anders Carlsson525b76b2009-10-16 02:48:28 +00004083bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004084 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004085 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004086
Anders Carlssonde71adf2007-11-27 05:51:55 +00004087 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004088 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004089 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004090 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004091 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004092 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004093 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004094 } else
4095 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004096 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004097 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004098
John McCalle3027922010-08-25 11:45:40 +00004099 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004100 return false;
4101}
4102
John Wiegley01296292011-04-08 18:41:53 +00004103ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4104 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004105 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004106
Anders Carlsson43d70f82009-10-16 05:23:41 +00004107 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004108
Nate Begemanc8961a42009-06-27 22:05:55 +00004109 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4110 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004111 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004112 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4113 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004114 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004115 return ExprError();
4116 }
John McCalle3027922010-08-25 11:45:40 +00004117 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004118 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004119 }
4120
Nate Begemanbd956c42009-06-28 02:36:38 +00004121 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004122 // conversion will take place first from scalar to elt type, and then
4123 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004124 if (SrcTy->isPointerType())
4125 return Diag(R.getBegin(),
4126 diag::err_invalid_conversion_between_vector_and_scalar)
4127 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004128
4129 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004130 ExprResult CastExprRes = Owned(CastExpr);
4131 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4132 if (CastExprRes.isInvalid())
4133 return ExprError();
4134 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004135
John McCalle3027922010-08-25 11:45:40 +00004136 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004137 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004138}
4139
John McCalldadc5752010-08-24 06:29:42 +00004140ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004141Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004142 SourceLocation RParenLoc, Expr *castExpr) {
4143 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004144 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004145
John McCall97513962010-01-15 18:39:57 +00004146 TypeSourceInfo *castTInfo;
4147 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4148 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004149 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004150
Nate Begeman5ec4b312009-08-10 23:49:36 +00004151 // If the Expr being casted is a ParenListExpr, handle it specially.
4152 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004153 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004154 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004155
John McCallb268a282010-08-23 23:25:46 +00004156 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004157}
4158
John McCalldadc5752010-08-24 06:29:42 +00004159ExprResult
John McCallebe54742010-01-15 18:56:44 +00004160Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004161 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004162 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004163 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004164 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004165 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004166 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4167 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004168 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004169 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004170 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004171
John McCallcf142162010-08-07 06:22:56 +00004172 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004173 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004174 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004175 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004176}
4177
Nate Begeman5ec4b312009-08-10 23:49:36 +00004178/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4179/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004180ExprResult
John McCallb268a282010-08-23 23:25:46 +00004181Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004182 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4183 if (!E)
4184 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCalldadc5752010-08-24 06:29:42 +00004186 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004187
Nate Begeman5ec4b312009-08-10 23:49:36 +00004188 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004189 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4190 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004191
John McCallb268a282010-08-23 23:25:46 +00004192 if (Result.isInvalid()) return ExprError();
4193
4194 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004195}
4196
John McCalldadc5752010-08-24 06:29:42 +00004197ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004198Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004199 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004200 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004201 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004202 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004203 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004204
Anton Yartsev28ccef72011-03-27 09:32:40 +00004205 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00004206 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004207 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4208 if (PE->getNumExprs() == 0) {
4209 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4210 return ExprError();
4211 }
John Thompson781ad172010-06-30 22:55:51 +00004212 if (PE->getNumExprs() == 1) {
4213 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00004214 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00004215 }
4216 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00004217 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00004218 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004219
Anton Yartsev28ccef72011-03-27 09:32:40 +00004220 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00004221 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00004222 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004223 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00004224 // '(...)' form of vector initialization in AltiVec: the number of
4225 // initializers must be one or must match the size of the vector.
4226 // If a single value is specified in the initializer then it will be
4227 // replicated to all the components of the vector
4228 if (Ty->getAs<VectorType>()->getVectorKind() ==
4229 VectorType::AltiVecVector) {
4230 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4231 // The number of initializers must be one or must match the size of the
4232 // vector. If a single value is specified in the initializer then it will
4233 // be replicated to all the components of the vector
4234 if (PE->getNumExprs() == 1) {
4235 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004236 ExprResult Literal = Owned(PE->getExpr(0));
4237 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4238 PrepareScalarCast(*this, Literal, ElemTy));
4239 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00004240 }
4241 else if (PE->getNumExprs() < numElems) {
4242 Diag(PE->getExprLoc(),
4243 diag::err_incorrect_number_of_vector_initializers);
4244 return ExprError();
4245 }
4246 else
4247 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4248 initExprs.push_back(PE->getExpr(i));
4249 }
4250 else
4251 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4252 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004253
4254 // FIXME: This means that pretty-printing the final AST will produce curly
4255 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004256 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4257 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004258 initExprs.size(), RParenLoc);
4259 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004260 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004261 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004262 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004263 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004264 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004265 if (Result.isInvalid()) return ExprError();
4266 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004267 }
4268}
4269
John McCalldadc5752010-08-24 06:29:42 +00004270ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004271 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004272 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004273 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004274 unsigned nexprs = Val.size();
4275 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004276 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4277 Expr *expr;
4278 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4279 expr = new (Context) ParenExpr(L, R, exprs[0]);
4280 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004281 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4282 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004283 return Owned(expr);
4284}
4285
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004286/// \brief Emit a specialized diagnostic when one expression is a null pointer
4287/// constant and the other is not a pointer.
4288bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4289 SourceLocation QuestionLoc) {
4290 Expr *NullExpr = LHS;
4291 Expr *NonPointerExpr = RHS;
4292 Expr::NullPointerConstantKind NullKind =
4293 NullExpr->isNullPointerConstant(Context,
4294 Expr::NPC_ValueDependentIsNotNull);
4295
4296 if (NullKind == Expr::NPCK_NotNull) {
4297 NullExpr = RHS;
4298 NonPointerExpr = LHS;
4299 NullKind =
4300 NullExpr->isNullPointerConstant(Context,
4301 Expr::NPC_ValueDependentIsNotNull);
4302 }
4303
4304 if (NullKind == Expr::NPCK_NotNull)
4305 return false;
4306
4307 if (NullKind == Expr::NPCK_ZeroInteger) {
4308 // In this case, check to make sure that we got here from a "NULL"
4309 // string in the source code.
4310 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004311 SourceLocation loc = NullExpr->getExprLoc();
4312 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004313 return false;
4314 }
4315
4316 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4317 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4318 << NonPointerExpr->getType() << DiagType
4319 << NonPointerExpr->getSourceRange();
4320 return true;
4321}
4322
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004323/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4324/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004325/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004326QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004327 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004328 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004329
John McCall3aef3d82011-04-10 19:13:55 +00004330 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004331 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004332 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004333
John McCall3aef3d82011-04-10 19:13:55 +00004334 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004335 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004336 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004337
Sebastian Redl1a99f442009-04-16 17:51:27 +00004338 // C++ is sufficiently different to merit its own checker.
4339 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004340 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004341
4342 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004343 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004344
John Wiegley01296292011-04-08 18:41:53 +00004345 Cond = UsualUnaryConversions(Cond.take());
4346 if (Cond.isInvalid())
4347 return QualType();
4348 LHS = UsualUnaryConversions(LHS.take());
4349 if (LHS.isInvalid())
4350 return QualType();
4351 RHS = UsualUnaryConversions(RHS.take());
4352 if (RHS.isInvalid())
4353 return QualType();
4354
4355 QualType CondTy = Cond.get()->getType();
4356 QualType LHSTy = LHS.get()->getType();
4357 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004358
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004359 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004360 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004361 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4362 // Throw an error if its not either.
4363 if (getLangOptions().OpenCL) {
4364 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004365 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004366 diag::err_typecheck_cond_expect_scalar_or_vector)
4367 << CondTy;
4368 return QualType();
4369 }
4370 }
4371 else {
John Wiegley01296292011-04-08 18:41:53 +00004372 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004373 << CondTy;
4374 return QualType();
4375 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004376 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004377
Chris Lattnere2949f42008-01-06 22:42:25 +00004378 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004379 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004380 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004381
Nate Begemanabb5a732010-09-20 22:41:17 +00004382 // OpenCL: If the condition is a vector, and both operands are scalar,
4383 // attempt to implicity convert them to the vector type to act like the
4384 // built in select.
4385 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4386 // Both operands should be of scalar type.
4387 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004388 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004389 << CondTy;
4390 return QualType();
4391 }
4392 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004393 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004394 << CondTy;
4395 return QualType();
4396 }
4397 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004398 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4399 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004400 }
4401
Chris Lattnere2949f42008-01-06 22:42:25 +00004402 // If both operands have arithmetic type, do the usual arithmetic conversions
4403 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004404 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4405 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004406 if (LHS.isInvalid() || RHS.isInvalid())
4407 return QualType();
4408 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004409 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004410
Chris Lattnere2949f42008-01-06 22:42:25 +00004411 // If both operands are the same structure or union type, the result is that
4412 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004413 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4414 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004415 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004416 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004417 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004418 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004419 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004420 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004421
Chris Lattnere2949f42008-01-06 22:42:25 +00004422 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004423 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004424 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4425 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004426 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4427 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004428 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004429 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4430 << LHS.get()->getSourceRange();
4431 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4432 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004433 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004434 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004435 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4436 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004437 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004438 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004439 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004440 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004441 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004442 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004443 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004444 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4445 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004446 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004447 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004448
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004449 // All objective-c pointer type analysis is done here.
4450 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4451 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004452 if (LHS.isInvalid() || RHS.isInvalid())
4453 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004454 if (!compositeType.isNull())
4455 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004456
4457
Steve Naroff05efa972009-07-01 14:36:47 +00004458 // Handle block pointer types.
4459 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4460 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4461 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4462 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004463 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4464 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004465 return destType;
4466 }
4467 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004468 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004469 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004470 }
Steve Naroff05efa972009-07-01 14:36:47 +00004471 // We have 2 block pointer types.
4472 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4473 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004474 return LHSTy;
4475 }
Steve Naroff05efa972009-07-01 14:36:47 +00004476 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004477 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4478 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004479
Steve Naroff05efa972009-07-01 14:36:47 +00004480 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4481 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004482 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004483 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004484 // In this situation, we assume void* type. No especially good
4485 // reason, but this is what gcc does, and we do have to pick
4486 // to get a consistent AST.
4487 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004488 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4489 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004490 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004491 }
Steve Naroff05efa972009-07-01 14:36:47 +00004492 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004493 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4494 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004495 return LHSTy;
4496 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004497
Steve Naroff05efa972009-07-01 14:36:47 +00004498 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4499 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4500 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004501 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4502 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004503
4504 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4505 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4506 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004507 QualType destPointee
4508 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004509 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004510 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004511 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004512 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004513 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004514 return destType;
4515 }
4516 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004517 QualType destPointee
4518 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004519 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004520 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004521 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004522 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004523 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004524 return destType;
4525 }
4526
4527 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4528 // Two identical pointer types are always compatible.
4529 return LHSTy;
4530 }
4531 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4532 rhptee.getUnqualifiedType())) {
4533 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004534 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004535 // In this situation, we assume void* type. No especially good
4536 // reason, but this is what gcc does, and we do have to pick
4537 // to get a consistent AST.
4538 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004539 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4540 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004541 return incompatTy;
4542 }
4543 // The pointer types are compatible.
4544 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4545 // differently qualified versions of compatible types, the result type is
4546 // a pointer to an appropriately qualified version of the *composite*
4547 // type.
4548 // FIXME: Need to calculate the composite type.
4549 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004550 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4551 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004552 return LHSTy;
4553 }
Mike Stump11289f42009-09-09 15:08:12 +00004554
John McCalle84af4e2010-11-13 01:35:44 +00004555 // GCC compatibility: soften pointer/integer mismatch. Note that
4556 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004557 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4558 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004559 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4560 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004561 return RHSTy;
4562 }
4563 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4564 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004565 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4566 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004567 return LHSTy;
4568 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004569
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004570 // Emit a better diagnostic if one of the expressions is a null pointer
4571 // constant and the other is not a pointer type. In this case, the user most
4572 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004573 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004574 return QualType();
4575
Chris Lattnere2949f42008-01-06 22:42:25 +00004576 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004577 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004578 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004579 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004580}
4581
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004582/// FindCompositeObjCPointerType - Helper method to find composite type of
4583/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004584QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004585 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004586 QualType LHSTy = LHS.get()->getType();
4587 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004588
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004589 // Handle things like Class and struct objc_class*. Here we case the result
4590 // to the pseudo-builtin, because that will be implicitly cast back to the
4591 // redefinition type if an attempt is made to access its fields.
4592 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004593 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004594 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004595 return LHSTy;
4596 }
4597 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004598 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004599 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004600 return RHSTy;
4601 }
4602 // And the same for struct objc_object* / id
4603 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004604 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004605 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004606 return LHSTy;
4607 }
4608 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004609 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004610 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004611 return RHSTy;
4612 }
4613 // And the same for struct objc_selector* / SEL
4614 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004615 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004616 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004617 return LHSTy;
4618 }
4619 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004620 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004621 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004622 return RHSTy;
4623 }
4624 // Check constraints for Objective-C object pointers types.
4625 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004626
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004627 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4628 // Two identical object pointer types are always compatible.
4629 return LHSTy;
4630 }
4631 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4632 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4633 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004634
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004635 // If both operands are interfaces and either operand can be
4636 // assigned to the other, use that type as the composite
4637 // type. This allows
4638 // xxx ? (A*) a : (B*) b
4639 // where B is a subclass of A.
4640 //
4641 // Additionally, as for assignment, if either type is 'id'
4642 // allow silent coercion. Finally, if the types are
4643 // incompatible then make sure to use 'id' as the composite
4644 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004645
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004646 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4647 // It could return the composite type.
4648 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4649 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4650 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4651 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4652 } else if ((LHSTy->isObjCQualifiedIdType() ||
4653 RHSTy->isObjCQualifiedIdType()) &&
4654 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4655 // Need to handle "id<xx>" explicitly.
4656 // GCC allows qualified id and any Objective-C type to devolve to
4657 // id. Currently localizing to here until clear this should be
4658 // part of ObjCQualifiedIdTypesAreCompatible.
4659 compositeType = Context.getObjCIdType();
4660 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4661 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004662 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004663 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4664 ;
4665 else {
4666 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4667 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004669 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004670 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4671 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004672 return incompatTy;
4673 }
4674 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004675 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4676 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004677 return compositeType;
4678 }
4679 // Check Objective-C object pointer types and 'void *'
4680 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4681 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4682 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4683 QualType destPointee
4684 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4685 QualType destType = Context.getPointerType(destPointee);
4686 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004687 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004688 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004689 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004690 return destType;
4691 }
4692 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4693 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4694 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4695 QualType destPointee
4696 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4697 QualType destType = Context.getPointerType(destPointee);
4698 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004699 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004700 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004701 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004702 return destType;
4703 }
4704 return QualType();
4705}
4706
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004707/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004708/// ParenRange in parentheses.
4709static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004710 const PartialDiagnostic &Note,
4711 SourceRange ParenRange) {
4712 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4713 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4714 EndLoc.isValid()) {
4715 Self.Diag(Loc, Note)
4716 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4717 << FixItHint::CreateInsertion(EndLoc, ")");
4718 } else {
4719 // We can't display the parentheses, so just show the bare note.
4720 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004721 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004722}
4723
4724static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4725 return Opc >= BO_Mul && Opc <= BO_Shr;
4726}
4727
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004728/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4729/// expression, either using a built-in or overloaded operator,
4730/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4731static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4732 Expr **RHS) {
4733 E = E->IgnoreParenImpCasts();
4734 E = E->IgnoreConversionOperator();
4735 E = E->IgnoreParenImpCasts();
4736
4737 // Built-in binary operator.
4738 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4739 if (IsArithmeticOp(OP->getOpcode())) {
4740 *Opcode = OP->getOpcode();
4741 *RHS = OP->getRHS();
4742 return true;
4743 }
4744 }
4745
4746 // Overloaded operator.
4747 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4748 if (Call->getNumArgs() != 2)
4749 return false;
4750
4751 // Make sure this is really a binary operator that is safe to pass into
4752 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4753 OverloadedOperatorKind OO = Call->getOperator();
4754 if (OO < OO_Plus || OO > OO_Arrow)
4755 return false;
4756
4757 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4758 if (IsArithmeticOp(OpKind)) {
4759 *Opcode = OpKind;
4760 *RHS = Call->getArg(1);
4761 return true;
4762 }
4763 }
4764
4765 return false;
4766}
4767
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004768static bool IsLogicOp(BinaryOperatorKind Opc) {
4769 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4770}
4771
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004772/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4773/// or is a logical expression such as (x==y) which has int type, but is
4774/// commonly interpreted as boolean.
4775static bool ExprLooksBoolean(Expr *E) {
4776 E = E->IgnoreParenImpCasts();
4777
4778 if (E->getType()->isBooleanType())
4779 return true;
4780 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4781 return IsLogicOp(OP->getOpcode());
4782 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4783 return OP->getOpcode() == UO_LNot;
4784
4785 return false;
4786}
4787
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004788/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4789/// and binary operator are mixed in a way that suggests the programmer assumed
4790/// the conditional operator has higher precedence, for example:
4791/// "int x = a + someBinaryCondition ? 1 : 2".
4792static void DiagnoseConditionalPrecedence(Sema &Self,
4793 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004794 Expr *Condition,
4795 Expr *LHS,
4796 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004797 BinaryOperatorKind CondOpcode;
4798 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004799
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004800 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004801 return;
4802 if (!ExprLooksBoolean(CondRHS))
4803 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004804
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004805 // The condition is an arithmetic binary expression, with a right-
4806 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004807
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004808 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004809 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004810 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004811
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004812 SuggestParentheses(Self, OpLoc,
4813 Self.PDiag(diag::note_precedence_conditional_silence)
4814 << BinaryOperator::getOpcodeStr(CondOpcode),
4815 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004816
4817 SuggestParentheses(Self, OpLoc,
4818 Self.PDiag(diag::note_precedence_conditional_first),
4819 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004820}
4821
Steve Naroff83895f72007-09-16 03:34:24 +00004822/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004823/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004824ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004825 SourceLocation ColonLoc,
4826 Expr *CondExpr, Expr *LHSExpr,
4827 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004828 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4829 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004830 OpaqueValueExpr *opaqueValue = 0;
4831 Expr *commonExpr = 0;
4832 if (LHSExpr == 0) {
4833 commonExpr = CondExpr;
4834
4835 // We usually want to apply unary conversions *before* saving, except
4836 // in the special case of a C++ l-value conditional.
4837 if (!(getLangOptions().CPlusPlus
4838 && !commonExpr->isTypeDependent()
4839 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4840 && commonExpr->isGLValue()
4841 && commonExpr->isOrdinaryOrBitFieldObject()
4842 && RHSExpr->isOrdinaryOrBitFieldObject()
4843 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004844 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4845 if (commonRes.isInvalid())
4846 return ExprError();
4847 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004848 }
4849
4850 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4851 commonExpr->getType(),
4852 commonExpr->getValueKind(),
4853 commonExpr->getObjectKind());
4854 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004855 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004856
John McCall7decc9e2010-11-18 06:31:45 +00004857 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004858 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004859 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4860 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004861 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004862 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4863 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004864 return ExprError();
4865
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004866 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4867 RHS.get());
4868
John McCallc07a0c72011-02-17 10:25:35 +00004869 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004870 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4871 LHS.take(), ColonLoc,
4872 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004873
4874 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004875 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4876 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004877}
4878
John McCallaba90822011-01-31 23:13:11 +00004879// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004880// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004881// routine is it effectively iqnores the qualifiers on the top level pointee.
4882// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4883// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004884static Sema::AssignConvertType
4885checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4886 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4887 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004888
Steve Naroff1f4d7272007-05-11 04:00:31 +00004889 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004890 const Type *lhptee, *rhptee;
4891 Qualifiers lhq, rhq;
4892 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4893 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004894
John McCallaba90822011-01-31 23:13:11 +00004895 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004896
4897 // C99 6.5.16.1p1: This following citation is common to constraints
4898 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4899 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004900 Qualifiers lq;
4901
John McCall31168b02011-06-15 23:02:42 +00004902 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4903 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4904 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4905 // Ignore lifetime for further calculation.
4906 lhq.removeObjCLifetime();
4907 rhq.removeObjCLifetime();
4908 }
4909
John McCall4fff8f62011-02-01 00:10:29 +00004910 if (!lhq.compatiblyIncludes(rhq)) {
4911 // Treat address-space mismatches as fatal. TODO: address subspaces
4912 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4913 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4914
John McCall31168b02011-06-15 23:02:42 +00004915 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004916 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004917 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4918 .compatiblyIncludes(
4919 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004920 && (lhptee->isVoidType() || rhptee->isVoidType()))
4921 ; // keep old
4922
John McCall31168b02011-06-15 23:02:42 +00004923 // Treat lifetime mismatches as fatal.
4924 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4925 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4926
John McCall4fff8f62011-02-01 00:10:29 +00004927 // For GCC compatibility, other qualifier mismatches are treated
4928 // as still compatible in C.
4929 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4930 }
Steve Naroff3f597292007-05-11 22:18:03 +00004931
Mike Stump4e1f26a2009-02-19 03:04:26 +00004932 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4933 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004934 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004935 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004936 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004937 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004938
Chris Lattner0a788432008-01-03 22:56:36 +00004939 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004940 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004941 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004942 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004943
Chris Lattner0a788432008-01-03 22:56:36 +00004944 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004945 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004946 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004947
4948 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004949 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004950 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004951 }
John McCall4fff8f62011-02-01 00:10:29 +00004952
Mike Stump4e1f26a2009-02-19 03:04:26 +00004953 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004954 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00004955 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
4956 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004957 // Check if the pointee types are compatible ignoring the sign.
4958 // We explicitly check for char so that we catch "char" vs
4959 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004960 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004961 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004962 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004963 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004964
Chris Lattnerec3a1562009-10-17 20:33:28 +00004965 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004966 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004967 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004968 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004969
John McCall4fff8f62011-02-01 00:10:29 +00004970 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004971 // Types are compatible ignoring the sign. Qualifier incompatibility
4972 // takes priority over sign incompatibility because the sign
4973 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00004974 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00004975 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00004976
John McCallaba90822011-01-31 23:13:11 +00004977 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00004978 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004979
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004980 // If we are a multi-level pointer, it's possible that our issue is simply
4981 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4982 // the eventual target type is the same and the pointers have the same
4983 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00004984 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004985 do {
John McCall4fff8f62011-02-01 00:10:29 +00004986 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
4987 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00004988 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004989
John McCall4fff8f62011-02-01 00:10:29 +00004990 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00004991 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004992 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004993
Eli Friedman80160bd2009-03-22 23:59:44 +00004994 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00004995 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004996 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004997 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004998}
4999
John McCallaba90822011-01-31 23:13:11 +00005000/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005001/// block pointer types are compatible or whether a block and normal pointer
5002/// are compatible. It is more restrict than comparing two function pointer
5003// types.
John McCallaba90822011-01-31 23:13:11 +00005004static Sema::AssignConvertType
5005checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5006 QualType rhsType) {
5007 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5008 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5009
Steve Naroff081c7422008-09-04 15:10:53 +00005010 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005011
Steve Naroff081c7422008-09-04 15:10:53 +00005012 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005013 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5014 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005015
John McCallaba90822011-01-31 23:13:11 +00005016 // In C++, the types have to match exactly.
5017 if (S.getLangOptions().CPlusPlus)
5018 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005019
John McCallaba90822011-01-31 23:13:11 +00005020 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021
Steve Naroff081c7422008-09-04 15:10:53 +00005022 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005023 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5024 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005025
John McCallaba90822011-01-31 23:13:11 +00005026 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5027 return Sema::IncompatibleBlockPointer;
5028
Steve Naroff081c7422008-09-04 15:10:53 +00005029 return ConvTy;
5030}
5031
John McCallaba90822011-01-31 23:13:11 +00005032/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005033/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005034static Sema::AssignConvertType
5035checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5036 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5037 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5038
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005039 if (lhsType->isObjCBuiltinType()) {
5040 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005041 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5042 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005043 return Sema::IncompatiblePointer;
5044 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005045 }
5046 if (rhsType->isObjCBuiltinType()) {
5047 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005048 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5049 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005050 return Sema::IncompatiblePointer;
5051 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005052 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005053 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005054 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005055 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005056 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005057
John McCallaba90822011-01-31 23:13:11 +00005058 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5059 return Sema::CompatiblePointerDiscardsQualifiers;
5060
5061 if (S.Context.typesAreCompatible(lhsType, rhsType))
5062 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005063 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005064 return Sema::IncompatibleObjCQualifiedId;
5065 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005066}
5067
John McCall29600e12010-11-16 02:32:08 +00005068Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005069Sema::CheckAssignmentConstraints(SourceLocation Loc,
5070 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005071 // Fake up an opaque expression. We don't actually care about what
5072 // cast operations are required, so if CheckAssignmentConstraints
5073 // adds casts to this they'll be wasted, but fortunately that doesn't
5074 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005075 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005076 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005077 CastKind K = CK_Invalid;
5078
5079 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5080}
5081
Mike Stump4e1f26a2009-02-19 03:04:26 +00005082/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5083/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005084/// pointers. Here are some objectionable examples that GCC considers warnings:
5085///
5086/// int a, *pint;
5087/// short *pshort;
5088/// struct foo *pfoo;
5089///
5090/// pint = pshort; // warning: assignment from incompatible pointer type
5091/// a = pint; // warning: assignment makes integer from pointer without a cast
5092/// pint = a; // warning: assignment makes pointer from integer without a cast
5093/// pint = pfoo; // warning: assignment from incompatible pointer type
5094///
5095/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005096/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005097///
John McCall8cb679e2010-11-15 09:13:47 +00005098/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005099Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005100Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005101 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005102 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00005103
Chris Lattnera52c2f22008-01-04 23:18:45 +00005104 // Get canonical types. We're not formatting these types, just comparing
5105 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005106 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5107 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005108
John McCalle5255932011-01-31 22:28:28 +00005109 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005110 if (lhsType == rhsType) {
5111 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005112 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005113 }
5114
Douglas Gregor6b754842008-10-28 00:22:11 +00005115 // If the left-hand side is a reference type, then we are in a
5116 // (rare!) case where we've allowed the use of references in C,
5117 // e.g., as a parameter type in a built-in function. In this case,
5118 // just make sure that the type referenced is compatible with the
5119 // right-hand side type. The caller is responsible for adjusting
5120 // lhsType so that the resulting expression does not have reference
5121 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005122 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005123 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5124 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005125 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005126 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005127 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005128 }
John McCalle5255932011-01-31 22:28:28 +00005129
Nate Begemanbd956c42009-06-28 02:36:38 +00005130 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5131 // to the same ExtVector type.
5132 if (lhsType->isExtVectorType()) {
5133 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005134 return Incompatible;
5135 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005136 // CK_VectorSplat does T -> vector T, so first cast to the
5137 // element type.
5138 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5139 if (elType != rhsType) {
5140 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005141 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005142 }
5143 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005144 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005145 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005146 }
Mike Stump11289f42009-09-09 15:08:12 +00005147
John McCalle5255932011-01-31 22:28:28 +00005148 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005149 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005150 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005151 // Allow assignments of an AltiVec vector type to an equivalent GCC
5152 // vector type and vice versa
5153 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5154 Kind = CK_BitCast;
5155 return Compatible;
5156 }
5157
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005158 // If we are allowing lax vector conversions, and LHS and RHS are both
5159 // vectors, the total size only needs to be the same. This is a bitcast;
5160 // no bits are changed but the result type is different.
5161 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005162 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005163 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005164 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005165 }
Chris Lattner881a2122008-01-04 23:32:24 +00005166 }
5167 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005168 }
Eli Friedman3360d892008-05-30 18:07:22 +00005169
John McCalle5255932011-01-31 22:28:28 +00005170 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005171 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005172 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005173 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005174 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005175 }
Eli Friedman3360d892008-05-30 18:07:22 +00005176
John McCalle5255932011-01-31 22:28:28 +00005177 // Conversions to normal pointers.
5178 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5179 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005180 if (isa<PointerType>(rhsType)) {
5181 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005182 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005183 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005184
John McCalle5255932011-01-31 22:28:28 +00005185 // int -> T*
5186 if (rhsType->isIntegerType()) {
5187 Kind = CK_IntegralToPointer; // FIXME: null?
5188 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005189 }
John McCalle5255932011-01-31 22:28:28 +00005190
5191 // C pointers are not compatible with ObjC object pointers,
5192 // with two exceptions:
5193 if (isa<ObjCObjectPointerType>(rhsType)) {
5194 // - conversions to void*
5195 if (lhsPointer->getPointeeType()->isVoidType()) {
5196 Kind = CK_AnyPointerToObjCPointerCast;
5197 return Compatible;
5198 }
5199
5200 // - conversions from 'Class' to the redefinition type
5201 if (rhsType->isObjCClassType() &&
5202 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005203 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005204 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005205 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005206
John McCalle5255932011-01-31 22:28:28 +00005207 Kind = CK_BitCast;
5208 return IncompatiblePointer;
5209 }
5210
5211 // U^ -> void*
5212 if (rhsType->getAs<BlockPointerType>()) {
5213 if (lhsPointer->getPointeeType()->isVoidType()) {
5214 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005215 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005216 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005217 }
John McCalle5255932011-01-31 22:28:28 +00005218
Steve Naroff081c7422008-09-04 15:10:53 +00005219 return Incompatible;
5220 }
5221
John McCalle5255932011-01-31 22:28:28 +00005222 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005223 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005224 // U^ -> T^
5225 if (rhsType->isBlockPointerType()) {
5226 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005227 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005228 }
5229
5230 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005231 if (rhsType->isIntegerType()) {
5232 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005233 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005234 }
5235
John McCalle5255932011-01-31 22:28:28 +00005236 // id -> T^
5237 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5238 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005239 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005240 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005241
John McCalle5255932011-01-31 22:28:28 +00005242 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005243 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005244 if (RHSPT->getPointeeType()->isVoidType()) {
5245 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005246 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005247 }
John McCall8cb679e2010-11-15 09:13:47 +00005248
Chris Lattnera52c2f22008-01-04 23:18:45 +00005249 return Incompatible;
5250 }
5251
John McCalle5255932011-01-31 22:28:28 +00005252 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005253 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005254 // A* -> B*
5255 if (rhsType->isObjCObjectPointerType()) {
5256 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005257 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005258 }
5259
5260 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005261 if (rhsType->isIntegerType()) {
5262 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005263 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005264 }
5265
John McCalle5255932011-01-31 22:28:28 +00005266 // In general, C pointers are not compatible with ObjC object pointers,
5267 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005268 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005269 // - conversions from 'void*'
5270 if (rhsType->isVoidPointerType()) {
5271 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005272 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005273 }
5274
5275 // - conversions to 'Class' from its redefinition type
5276 if (lhsType->isObjCClassType() &&
5277 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5278 Kind = CK_BitCast;
5279 return Compatible;
5280 }
5281
5282 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005283 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005284 }
John McCalle5255932011-01-31 22:28:28 +00005285
5286 // T^ -> A*
5287 if (rhsType->isBlockPointerType()) {
5288 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005289 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005290 }
5291
Steve Naroff7cae42b2009-07-10 23:34:53 +00005292 return Incompatible;
5293 }
John McCalle5255932011-01-31 22:28:28 +00005294
5295 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005296 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005297 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005298 if (lhsType == Context.BoolTy) {
5299 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005300 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005301 }
Eli Friedman3360d892008-05-30 18:07:22 +00005302
John McCalle5255932011-01-31 22:28:28 +00005303 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005304 if (lhsType->isIntegerType()) {
5305 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005306 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005307 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005308
Chris Lattnera52c2f22008-01-04 23:18:45 +00005309 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005310 }
John McCalle5255932011-01-31 22:28:28 +00005311
5312 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005313 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005314 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005315 if (lhsType == Context.BoolTy) {
5316 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005317 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005318 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005319
John McCalle5255932011-01-31 22:28:28 +00005320 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005321 if (lhsType->isIntegerType()) {
5322 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005323 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005324 }
5325
Steve Naroff7cae42b2009-07-10 23:34:53 +00005326 return Incompatible;
5327 }
Eli Friedman3360d892008-05-30 18:07:22 +00005328
John McCalle5255932011-01-31 22:28:28 +00005329 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005330 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005331 if (Context.typesAreCompatible(lhsType, rhsType)) {
5332 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005333 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005334 }
Bill Wendling216423b2007-05-30 06:30:29 +00005335 }
John McCalle5255932011-01-31 22:28:28 +00005336
Steve Naroff98cf3e92007-06-06 18:38:38 +00005337 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005338}
5339
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005340/// \brief Constructs a transparent union from an expression that is
5341/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005342static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005343 QualType UnionType, FieldDecl *Field) {
5344 // Build an initializer list that designates the appropriate member
5345 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005346 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005347 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005348 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005349 SourceLocation());
5350 Initializer->setType(UnionType);
5351 Initializer->setInitializedFieldInUnion(Field);
5352
5353 // Build a compound literal constructing a value of the transparent
5354 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005355 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005356 EResult = S.Owned(
5357 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5358 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005359}
5360
5361Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005362Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5363 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005364
Mike Stump11289f42009-09-09 15:08:12 +00005365 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005366 // transparent_union GCC extension.
5367 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005368 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005369 return Incompatible;
5370
5371 // The field to initialize within the transparent union.
5372 RecordDecl *UD = UT->getDecl();
5373 FieldDecl *InitField = 0;
5374 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005375 for (RecordDecl::field_iterator it = UD->field_begin(),
5376 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005377 it != itend; ++it) {
5378 if (it->getType()->isPointerType()) {
5379 // If the transparent union contains a pointer type, we allow:
5380 // 1) void pointer
5381 // 2) null pointer constant
5382 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005383 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005384 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005385 InitField = *it;
5386 break;
5387 }
Mike Stump11289f42009-09-09 15:08:12 +00005388
John Wiegley01296292011-04-08 18:41:53 +00005389 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005390 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005391 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005392 InitField = *it;
5393 break;
5394 }
5395 }
5396
John McCall8cb679e2010-11-15 09:13:47 +00005397 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005398 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005399 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005400 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005401 InitField = *it;
5402 break;
5403 }
5404 }
5405
5406 if (!InitField)
5407 return Incompatible;
5408
John Wiegley01296292011-04-08 18:41:53 +00005409 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005410 return Compatible;
5411}
5412
Chris Lattner9bad62c2008-01-04 18:04:52 +00005413Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005414Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005415 if (getLangOptions().CPlusPlus) {
5416 if (!lhsType->isRecordType()) {
5417 // C++ 5.17p3: If the left operand is not of class type, the
5418 // expression is implicitly converted (C++ 4) to the
5419 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005420 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5421 lhsType.getUnqualifiedType(),
5422 AA_Assigning);
5423 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005424 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00005425 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00005426 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005427 }
5428
5429 // FIXME: Currently, we fall through and treat C++ classes like C
5430 // structures.
John McCall34376a62010-12-04 03:47:34 +00005431 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005432
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005433 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5434 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005435 if ((lhsType->isPointerType() ||
5436 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005437 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005438 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005439 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005440 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005441 return Compatible;
5442 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005443
Chris Lattnere6dcd502007-10-16 02:55:40 +00005444 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005445 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005446 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005447 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005448 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005449 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005450 if (!lhsType->isReferenceType()) {
5451 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5452 if (rExpr.isInvalid())
5453 return Incompatible;
5454 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005455
John McCall8cb679e2010-11-15 09:13:47 +00005456 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005457 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005458 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005459
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005460 // C99 6.5.16.1p2: The value of the right operand is converted to the
5461 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005462 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5463 // so that we can use references in built-in functions even in C.
5464 // The getNonReferenceType() call makes sure that the resulting expression
5465 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005466 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5467 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005468 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005469}
5470
John Wiegley01296292011-04-08 18:41:53 +00005471QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005472 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005473 << lex.get()->getType() << rex.get()->getType()
5474 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005475 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005476}
5477
Eli Friedman1408bc92011-06-23 18:10:35 +00005478QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5479 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005480 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005481 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005482 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005483 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005484 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005485 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486
Nate Begeman191a6b12008-07-14 18:02:46 +00005487 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005488 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005489 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005490
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005491 // Handle the case of equivalent AltiVec and GCC vector types
5492 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5493 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005494 if (lhsType->isExtVectorType()) {
5495 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5496 return lhsType;
5497 }
5498
5499 if (!isCompAssign)
5500 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005501 return rhsType;
5502 }
5503
Eli Friedman1408bc92011-06-23 18:10:35 +00005504 if (getLangOptions().LaxVectorConversions &&
5505 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5506 // If we are allowing lax vector conversions, and LHS and RHS are both
5507 // vectors, the total size only needs to be the same. This is a
5508 // bitcast; no bits are changed but the result type is different.
5509 // FIXME: Should we really be allowing this?
5510 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5511 return lhsType;
5512 }
5513
Nate Begemanbd956c42009-06-28 02:36:38 +00005514 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5515 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5516 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005517 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005518 swapped = true;
5519 std::swap(rex, lex);
5520 std::swap(rhsType, lhsType);
5521 }
Mike Stump11289f42009-09-09 15:08:12 +00005522
Nate Begeman886448d2009-06-28 19:12:57 +00005523 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005524 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005525 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005526 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005527 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5528 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005529 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005530 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005531 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005532 if (swapped) std::swap(rex, lex);
5533 return lhsType;
5534 }
5535 }
5536 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5537 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005538 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5539 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005540 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005541 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005542 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005543 if (swapped) std::swap(rex, lex);
5544 return lhsType;
5545 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005546 }
5547 }
Mike Stump11289f42009-09-09 15:08:12 +00005548
Nate Begeman886448d2009-06-28 19:12:57 +00005549 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005550 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005551 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005552 << lex.get()->getType() << rex.get()->getType()
5553 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005554 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005555}
5556
Chris Lattnerfaa54172010-01-12 21:23:57 +00005557QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005558 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5559 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005560 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005561
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005562 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005563 if (lex.isInvalid() || rex.isInvalid())
5564 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005565
John Wiegley01296292011-04-08 18:41:53 +00005566 if (!lex.get()->getType()->isArithmeticType() ||
5567 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005568 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005569
Chris Lattnerfaa54172010-01-12 21:23:57 +00005570 // Check for division by zero.
5571 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005572 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5573 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5574 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005575
Chris Lattnerfaa54172010-01-12 21:23:57 +00005576 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005577}
5578
Chris Lattnerfaa54172010-01-12 21:23:57 +00005579QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005580 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5581 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5582 if (lex.get()->getType()->hasIntegerRepresentation() &&
5583 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005584 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005585 return InvalidOperands(Loc, lex, rex);
5586 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005587
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005588 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005589 if (lex.isInvalid() || rex.isInvalid())
5590 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005591
John Wiegley01296292011-04-08 18:41:53 +00005592 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005593 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005594
Chris Lattnerfaa54172010-01-12 21:23:57 +00005595 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005596 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5597 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5598 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005599
Chris Lattnerfaa54172010-01-12 21:23:57 +00005600 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005601}
5602
Chandler Carruthc9332212011-06-27 08:02:19 +00005603/// \brief Diagnose invalid arithmetic on two void pointers.
5604static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5605 Expr *LHS, Expr *RHS) {
5606 S.Diag(Loc, S.getLangOptions().CPlusPlus
5607 ? diag::err_typecheck_pointer_arith_void_type
5608 : diag::ext_gnu_void_ptr)
5609 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5610}
5611
5612/// \brief Diagnose invalid arithmetic on a void pointer.
5613static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5614 Expr *Pointer) {
5615 S.Diag(Loc, S.getLangOptions().CPlusPlus
5616 ? diag::err_typecheck_pointer_arith_void_type
5617 : diag::ext_gnu_void_ptr)
5618 << 0 /* one pointer */ << Pointer->getSourceRange();
5619}
5620
5621/// \brief Diagnose invalid arithmetic on two function pointers.
5622static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5623 Expr *LHS, Expr *RHS) {
5624 assert(LHS->getType()->isAnyPointerType());
5625 assert(RHS->getType()->isAnyPointerType());
5626 S.Diag(Loc, S.getLangOptions().CPlusPlus
5627 ? diag::err_typecheck_pointer_arith_function_type
5628 : diag::ext_gnu_ptr_func_arith)
5629 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5630 // We only show the second type if it differs from the first.
5631 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5632 RHS->getType())
5633 << RHS->getType()->getPointeeType()
5634 << LHS->getSourceRange() << RHS->getSourceRange();
5635}
5636
5637/// \brief Diagnose invalid arithmetic on a function pointer.
5638static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5639 Expr *Pointer) {
5640 assert(Pointer->getType()->isAnyPointerType());
5641 S.Diag(Loc, S.getLangOptions().CPlusPlus
5642 ? diag::err_typecheck_pointer_arith_function_type
5643 : diag::ext_gnu_ptr_func_arith)
5644 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5645 << 0 /* one pointer, so only one type */
5646 << Pointer->getSourceRange();
5647}
5648
5649/// \brief Check the validity of an arithmetic pointer operand.
5650///
5651/// If the operand has pointer type, this code will check for pointer types
5652/// which are invalid in arithmetic operations. These will be diagnosed
5653/// appropriately, including whether or not the use is supported as an
5654/// extension.
5655///
5656/// \returns True when the operand is valid to use (even if as an extension).
5657static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5658 Expr *Operand) {
5659 if (!Operand->getType()->isAnyPointerType()) return true;
5660
5661 QualType PointeeTy = Operand->getType()->getPointeeType();
5662 if (PointeeTy->isVoidType()) {
5663 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5664 return !S.getLangOptions().CPlusPlus;
5665 }
5666 if (PointeeTy->isFunctionType()) {
5667 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5668 return !S.getLangOptions().CPlusPlus;
5669 }
5670
5671 if ((Operand->getType()->isPointerType() &&
5672 !Operand->getType()->isDependentType()) ||
5673 Operand->getType()->isObjCObjectPointerType()) {
5674 QualType PointeeTy = Operand->getType()->getPointeeType();
5675 if (S.RequireCompleteType(
5676 Loc, PointeeTy,
5677 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5678 << PointeeTy << Operand->getSourceRange()))
5679 return false;
5680 }
5681
5682 return true;
5683}
5684
5685/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5686/// operands.
5687///
5688/// This routine will diagnose any invalid arithmetic on pointer operands much
5689/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5690/// for emitting a single diagnostic even for operations where both LHS and RHS
5691/// are (potentially problematic) pointers.
5692///
5693/// \returns True when the operand is valid to use (even if as an extension).
5694static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5695 Expr *LHS, Expr *RHS) {
5696 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5697 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5698 if (!isLHSPointer && !isRHSPointer) return true;
5699
5700 QualType LHSPointeeTy, RHSPointeeTy;
5701 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5702 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5703
5704 // Check for arithmetic on pointers to incomplete types.
5705 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5706 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5707 if (isLHSVoidPtr || isRHSVoidPtr) {
5708 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5709 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5710 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5711
5712 return !S.getLangOptions().CPlusPlus;
5713 }
5714
5715 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5716 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5717 if (isLHSFuncPtr || isRHSFuncPtr) {
5718 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5719 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5720 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5721
5722 return !S.getLangOptions().CPlusPlus;
5723 }
5724
5725 Expr *Operands[] = { LHS, RHS };
5726 for (unsigned i = 0; i < 2; ++i) {
5727 Expr *Operand = Operands[i];
5728 if ((Operand->getType()->isPointerType() &&
5729 !Operand->getType()->isDependentType()) ||
5730 Operand->getType()->isObjCObjectPointerType()) {
5731 QualType PointeeTy = Operand->getType()->getPointeeType();
5732 if (S.RequireCompleteType(
5733 Loc, PointeeTy,
5734 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5735 << PointeeTy << Operand->getSourceRange()))
5736 return false;
5737 }
5738 }
5739 return true;
5740}
5741
Chris Lattnerfaa54172010-01-12 21:23:57 +00005742QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005743 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5744 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005745 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005746 if (CompLHSTy) *CompLHSTy = compType;
5747 return compType;
5748 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005749
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005750 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005751 if (lex.isInvalid() || rex.isInvalid())
5752 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005753
Steve Naroffe4718892007-04-27 18:30:00 +00005754 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005755 if (lex.get()->getType()->isArithmeticType() &&
5756 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005757 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005758 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005759 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005760
Eli Friedman8e122982008-05-18 18:08:51 +00005761 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005762 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005763 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005764 std::swap(PExp, IExp);
5765
Steve Naroff6b712a72009-07-14 18:25:06 +00005766 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005767 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005768 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5769 return QualType();
5770
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005771 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005772
Chris Lattner12bdebb2009-04-24 23:50:08 +00005773 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005774 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005775 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5776 << PointeeTy << PExp->getSourceRange();
5777 return QualType();
5778 }
Mike Stump11289f42009-09-09 15:08:12 +00005779
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005780 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005781 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005782 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005783 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005784 if (LHSTy->isPromotableIntegerType())
5785 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005786 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005787 *CompLHSTy = LHSTy;
5788 }
Eli Friedman8e122982008-05-18 18:08:51 +00005789 return PExp->getType();
5790 }
5791 }
5792
Chris Lattner326f7572008-11-18 01:30:42 +00005793 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005794}
5795
Chris Lattner2a3569b2008-04-07 05:30:13 +00005796// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005797QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005798 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005799 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005800 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005801 if (CompLHSTy) *CompLHSTy = compType;
5802 return compType;
5803 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005804
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005805 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005806 if (lex.isInvalid() || rex.isInvalid())
5807 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005808
Chris Lattner4d62f422007-12-09 21:53:25 +00005809 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005810
Chris Lattner4d62f422007-12-09 21:53:25 +00005811 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005812 if (lex.get()->getType()->isArithmeticType() &&
5813 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005814 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005815 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005816 }
Mike Stump11289f42009-09-09 15:08:12 +00005817
Chris Lattner4d62f422007-12-09 21:53:25 +00005818 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005819 if (lex.get()->getType()->isAnyPointerType()) {
5820 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005821
Chris Lattner12bdebb2009-04-24 23:50:08 +00005822 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005823 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005824 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005825 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005826 return QualType();
5827 }
Mike Stump11289f42009-09-09 15:08:12 +00005828
Chris Lattner4d62f422007-12-09 21:53:25 +00005829 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005830 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005831 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5832 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005833
John Wiegley01296292011-04-08 18:41:53 +00005834 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5835 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005836 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005837
Chris Lattner4d62f422007-12-09 21:53:25 +00005838 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005839 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005840 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005841
Eli Friedman168fe152009-05-16 13:54:38 +00005842 if (getLangOptions().CPlusPlus) {
5843 // Pointee types must be the same: C++ [expr.add]
5844 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5845 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005846 << lex.get()->getType() << rex.get()->getType()
5847 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005848 return QualType();
5849 }
5850 } else {
5851 // Pointee types must be compatible C99 6.5.6p3
5852 if (!Context.typesAreCompatible(
5853 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5854 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5855 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005856 << lex.get()->getType() << rex.get()->getType()
5857 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005858 return QualType();
5859 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005860 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005861
Chandler Carruthc9332212011-06-27 08:02:19 +00005862 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5863 lex.get(), rex.get()))
5864 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005865
John Wiegley01296292011-04-08 18:41:53 +00005866 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005867 return Context.getPointerDiffType();
5868 }
5869 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005870
Chris Lattner326f7572008-11-18 01:30:42 +00005871 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005872}
5873
Douglas Gregor0bf31402010-10-08 23:50:27 +00005874static bool isScopedEnumerationType(QualType T) {
5875 if (const EnumType *ET = dyn_cast<EnumType>(T))
5876 return ET->getDecl()->isScoped();
5877 return false;
5878}
5879
John Wiegley01296292011-04-08 18:41:53 +00005880static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005881 SourceLocation Loc, unsigned Opc,
5882 QualType LHSTy) {
5883 llvm::APSInt Right;
5884 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005885 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005886 return;
5887
5888 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005889 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005890 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005891 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005892 return;
5893 }
5894 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005895 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005896 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005897 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005898 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005899 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005900 return;
5901 }
5902 if (Opc != BO_Shl)
5903 return;
5904
5905 // When left shifting an ICE which is signed, we can check for overflow which
5906 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5907 // integers have defined behavior modulo one more than the maximum value
5908 // representable in the result type, so never warn for those.
5909 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005910 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005911 LHSTy->hasUnsignedIntegerRepresentation())
5912 return;
5913 llvm::APInt ResultBits =
5914 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5915 if (LeftBits.uge(ResultBits))
5916 return;
5917 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5918 Result = Result.shl(Right);
5919
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005920 // Print the bit representation of the signed integer as an unsigned
5921 // hexadecimal number.
5922 llvm::SmallString<40> HexResult;
5923 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5924
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005925 // If we are only missing a sign bit, this is less likely to result in actual
5926 // bugs -- if the result is cast back to an unsigned type, it will have the
5927 // expected value. Thus we place this behind a different warning that can be
5928 // turned off separately if needed.
5929 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005930 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5931 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005932 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005933 return;
5934 }
5935
5936 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005937 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005938 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005939}
5940
Chris Lattner2a3569b2008-04-07 05:30:13 +00005941// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00005942QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005943 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005944 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00005945 if (!lex.get()->getType()->hasIntegerRepresentation() ||
5946 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005947 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005948
Douglas Gregor0bf31402010-10-08 23:50:27 +00005949 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5950 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00005951 if (isScopedEnumerationType(lex.get()->getType()) ||
5952 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00005953 return InvalidOperands(Loc, lex, rex);
5954 }
5955
Nate Begemane46ee9a2009-10-25 02:26:48 +00005956 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00005957 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005958 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00005959
Chris Lattner5c11c412007-12-12 05:47:28 +00005960 // Shifts don't perform usual arithmetic conversions, they just do integer
5961 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005962
John McCall57cdd882010-12-16 19:28:59 +00005963 // For the LHS, do usual unary conversions, but then reset them away
5964 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00005965 ExprResult old_lex = lex;
5966 lex = UsualUnaryConversions(lex.take());
5967 if (lex.isInvalid())
5968 return QualType();
5969 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00005970 if (isCompAssign) lex = old_lex;
5971
5972 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00005973 rex = UsualUnaryConversions(rex.take());
5974 if (rex.isInvalid())
5975 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005976
Ryan Flynnf53fab82009-08-07 16:20:20 +00005977 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005978 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00005979
Chris Lattner5c11c412007-12-12 05:47:28 +00005980 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005981 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005982}
5983
Chandler Carruth17773fc2010-07-10 12:30:03 +00005984static bool IsWithinTemplateSpecialization(Decl *D) {
5985 if (DeclContext *DC = D->getDeclContext()) {
5986 if (isa<ClassTemplateSpecializationDecl>(DC))
5987 return true;
5988 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5989 return FD->isFunctionTemplateSpecialization();
5990 }
5991 return false;
5992}
5993
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005994// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00005995QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005996 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00005997 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005998
Chris Lattner9a152e22009-12-05 05:40:13 +00005999 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006000 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006001 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
John Wiegley01296292011-04-08 18:41:53 +00006003 QualType lType = lex.get()->getType();
6004 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006005
John Wiegley01296292011-04-08 18:41:53 +00006006 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6007 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006008 QualType LHSStrippedType = LHSStripped->getType();
6009 QualType RHSStrippedType = RHSStripped->getType();
6010
Douglas Gregor1beec452011-03-12 01:48:56 +00006011
6012
Chandler Carruth712563b2011-02-17 08:37:06 +00006013 // Two different enums will raise a warning when compared.
6014 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6015 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6016 if (LHSEnumType->getDecl()->getIdentifier() &&
6017 RHSEnumType->getDecl()->getIdentifier() &&
6018 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6019 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6020 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006021 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006022 }
6023 }
6024 }
6025
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006026 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006027 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006028 !lex.get()->getLocStart().isMacroID() &&
6029 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006030 // For non-floating point types, check for self-comparisons of the form
6031 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6032 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006033 //
6034 // NOTE: Don't warn about comparison expressions resulting from macro
6035 // expansion. Also don't warn about comparisons which are only self
6036 // comparisons within a template specialization. The warnings should catch
6037 // obvious cases in the definition of the template anyways. The idea is to
6038 // warn when the typed comparison operator will always evaluate to the same
6039 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006040 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006041 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006042 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006043 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006044 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006045 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006046 << (Opc == BO_EQ
6047 || Opc == BO_LE
6048 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006049 } else if (lType->isArrayType() && rType->isArrayType() &&
6050 !DRL->getDecl()->getType()->isReferenceType() &&
6051 !DRR->getDecl()->getType()->isReferenceType()) {
6052 // what is it always going to eval to?
6053 char always_evals_to;
6054 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006055 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006056 always_evals_to = 0; // false
6057 break;
John McCalle3027922010-08-25 11:45:40 +00006058 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006059 always_evals_to = 1; // true
6060 break;
6061 default:
6062 // best we can say is 'a constant'
6063 always_evals_to = 2; // e.g. array1 <= array2
6064 break;
6065 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006066 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006067 << 1 // array
6068 << always_evals_to);
6069 }
6070 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006071 }
Mike Stump11289f42009-09-09 15:08:12 +00006072
Chris Lattner222b8bd2009-03-08 19:39:53 +00006073 if (isa<CastExpr>(LHSStripped))
6074 LHSStripped = LHSStripped->IgnoreParenCasts();
6075 if (isa<CastExpr>(RHSStripped))
6076 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006077
Chris Lattner222b8bd2009-03-08 19:39:53 +00006078 // Warn about comparisons against a string constant (unless the other
6079 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006080 Expr *literalString = 0;
6081 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006082 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006083 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006084 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006085 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006086 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006087 } else if ((isa<StringLiteral>(RHSStripped) ||
6088 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006089 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006090 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006091 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006092 literalStringStripped = RHSStripped;
6093 }
6094
6095 if (literalString) {
6096 std::string resultComparison;
6097 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006098 case BO_LT: resultComparison = ") < 0"; break;
6099 case BO_GT: resultComparison = ") > 0"; break;
6100 case BO_LE: resultComparison = ") <= 0"; break;
6101 case BO_GE: resultComparison = ") >= 0"; break;
6102 case BO_EQ: resultComparison = ") == 0"; break;
6103 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006104 default: assert(false && "Invalid comparison operator");
6105 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006106
Ted Kremenek3427fac2011-02-23 01:52:04 +00006107 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006108 PDiag(diag::warn_stringcompare)
6109 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006110 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006111 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006112 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006113
Douglas Gregorec170db2010-06-08 19:50:34 +00006114 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006115 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006116 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006117 if (lex.isInvalid() || rex.isInvalid())
6118 return QualType();
6119 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006120 else {
John Wiegley01296292011-04-08 18:41:53 +00006121 lex = UsualUnaryConversions(lex.take());
6122 if (lex.isInvalid())
6123 return QualType();
6124
6125 rex = UsualUnaryConversions(rex.take());
6126 if (rex.isInvalid())
6127 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006128 }
6129
John Wiegley01296292011-04-08 18:41:53 +00006130 lType = lex.get()->getType();
6131 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006132
Douglas Gregorca63811b2008-11-19 03:25:36 +00006133 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006134 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006135
Chris Lattnerb620c342007-08-26 01:18:55 +00006136 if (isRelational) {
6137 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006138 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006139 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006140 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006141 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006142 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006143
Chris Lattnerb620c342007-08-26 01:18:55 +00006144 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006145 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006146 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006147
John Wiegley01296292011-04-08 18:41:53 +00006148 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006149 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006150 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006151 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006152
Douglas Gregorf267edd2010-06-15 21:38:40 +00006153 // All of the following pointer-related warnings are GCC extensions, except
6154 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006155 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006156 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006157 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006158 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006159 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006160
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006161 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006162 if (LCanPointeeTy == RCanPointeeTy)
6163 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006164 if (!isRelational &&
6165 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6166 // Valid unless comparison between non-null pointer and function pointer
6167 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006168 // In a SFINAE context, we treat this as a hard error to maintain
6169 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006170 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6171 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006172 Diag(Loc,
6173 isSFINAEContext()?
6174 diag::err_typecheck_comparison_of_fptr_to_void
6175 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006176 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006177
6178 if (isSFINAEContext())
6179 return QualType();
6180
John Wiegley01296292011-04-08 18:41:53 +00006181 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006182 return ResultTy;
6183 }
6184 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006185
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006186 // C++ [expr.rel]p2:
6187 // [...] Pointer conversions (4.10) and qualification
6188 // conversions (4.4) are performed on pointer operands (or on
6189 // a pointer operand and a null pointer constant) to bring
6190 // them to their composite pointer type. [...]
6191 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006192 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006193 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006194 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006195 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006196 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006197 if (T.isNull()) {
6198 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006199 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006200 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006201 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006202 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006203 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006204 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006205 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006206 }
6207
John Wiegley01296292011-04-08 18:41:53 +00006208 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6209 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006210 return ResultTy;
6211 }
Eli Friedman16c209612009-08-23 00:27:47 +00006212 // C99 6.5.9p2 and C99 6.5.8p2
6213 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6214 RCanPointeeTy.getUnqualifiedType())) {
6215 // Valid unless a relational comparison of function pointers
6216 if (isRelational && LCanPointeeTy->isFunctionType()) {
6217 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006218 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006219 }
6220 } else if (!isRelational &&
6221 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6222 // Valid unless comparison between non-null pointer and function pointer
6223 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6224 && !LHSIsNull && !RHSIsNull) {
6225 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006226 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006227 }
6228 } else {
6229 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006230 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006231 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006232 }
John McCall7684dde2011-03-11 04:25:25 +00006233 if (LCanPointeeTy != RCanPointeeTy) {
6234 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006235 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006236 else
John Wiegley01296292011-04-08 18:41:53 +00006237 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006238 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006239 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006240 }
Mike Stump11289f42009-09-09 15:08:12 +00006241
Sebastian Redl576fd422009-05-10 18:38:11 +00006242 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006243 // Comparison of nullptr_t with itself.
6244 if (lType->isNullPtrType() && rType->isNullPtrType())
6245 return ResultTy;
6246
Mike Stump11289f42009-09-09 15:08:12 +00006247 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006248 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006249 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006250 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006251 (!isRelational &&
6252 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006253 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006254 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006255 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006256 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006257 return ResultTy;
6258 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006259 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006260 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006261 (!isRelational &&
6262 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006263 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006264 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006265 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006266 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006267 return ResultTy;
6268 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006269
6270 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006271 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006272 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6273 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006274 // In addition, pointers to members can be compared, or a pointer to
6275 // member and a null pointer constant. Pointer to member conversions
6276 // (4.11) and qualification conversions (4.4) are performed to bring
6277 // them to a common type. If one operand is a null pointer constant,
6278 // the common type is the type of the other operand. Otherwise, the
6279 // common type is a pointer to member type similar (4.4) to the type
6280 // of one of the operands, with a cv-qualification signature (4.4)
6281 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006282 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006283 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006284 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006285 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006286 if (T.isNull()) {
6287 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006288 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006289 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006290 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006291 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006292 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006293 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006294 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006295 }
Mike Stump11289f42009-09-09 15:08:12 +00006296
John Wiegley01296292011-04-08 18:41:53 +00006297 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6298 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006299 return ResultTy;
6300 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006301
6302 // Handle scoped enumeration types specifically, since they don't promote
6303 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006304 if (lex.get()->getType()->isEnumeralType() &&
6305 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006306 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
Steve Naroff081c7422008-09-04 15:10:53 +00006309 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006310 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006311 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6312 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006313
Steve Naroff081c7422008-09-04 15:10:53 +00006314 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006315 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006316 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006317 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006318 }
John Wiegley01296292011-04-08 18:41:53 +00006319 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006320 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006321 }
John Wiegley01296292011-04-08 18:41:53 +00006322
Steve Naroffe18f94c2008-09-28 01:11:11 +00006323 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006324 if (!isRelational
6325 && ((lType->isBlockPointerType() && rType->isPointerType())
6326 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006327 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006328 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006329 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006330 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006331 ->getPointeeType()->isVoidType())))
6332 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006333 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006334 }
John McCall7684dde2011-03-11 04:25:25 +00006335 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006336 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006337 else
John Wiegley01296292011-04-08 18:41:53 +00006338 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006339 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006340 }
Steve Naroff081c7422008-09-04 15:10:53 +00006341
John McCall7684dde2011-03-11 04:25:25 +00006342 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6343 const PointerType *LPT = lType->getAs<PointerType>();
6344 const PointerType *RPT = rType->getAs<PointerType>();
6345 if (LPT || RPT) {
6346 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6347 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Steve Naroff753567f2008-11-17 19:49:16 +00006349 if (!LPtrToVoid && !RPtrToVoid &&
6350 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006351 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006352 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006353 }
John McCall7684dde2011-03-11 04:25:25 +00006354 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006355 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006356 else
John Wiegley01296292011-04-08 18:41:53 +00006357 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006358 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006359 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006360 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006361 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006362 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006363 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006364 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006365 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006366 else
John Wiegley01296292011-04-08 18:41:53 +00006367 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006368 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006369 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006370 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006371 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6372 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006373 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006374 bool isError = false;
6375 if ((LHSIsNull && lType->isIntegerType()) ||
6376 (RHSIsNull && rType->isIntegerType())) {
6377 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006378 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006379 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006380 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006381 else if (getLangOptions().CPlusPlus) {
6382 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6383 isError = true;
6384 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006385 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006386
Chris Lattnerd99bd522009-08-23 00:03:44 +00006387 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006388 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006389 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006390 if (isError)
6391 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006392 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006393
6394 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006395 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006396 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006397 else
John Wiegley01296292011-04-08 18:41:53 +00006398 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006399 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006400 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006401 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006402
Steve Naroff4b191572008-09-04 16:56:14 +00006403 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006404 if (!isRelational && RHSIsNull
6405 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006406 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006407 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006408 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006409 if (!isRelational && LHSIsNull
6410 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006411 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006412 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006413 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006414
Chris Lattner326f7572008-11-18 01:30:42 +00006415 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006416}
6417
Nate Begeman191a6b12008-07-14 18:02:46 +00006418/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006419/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006420/// like a scalar comparison, a vector comparison produces a vector of integer
6421/// types.
John Wiegley01296292011-04-08 18:41:53 +00006422QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006423 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006424 bool isRelational) {
6425 // Check to make sure we're operating on vectors of the same type and width,
6426 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006427 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006428 if (vType.isNull())
6429 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006430
John Wiegley01296292011-04-08 18:41:53 +00006431 QualType lType = lex.get()->getType();
6432 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006433
Anton Yartsev530deb92011-03-27 15:36:07 +00006434 // If AltiVec, the comparison results in a numeric type, i.e.
6435 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006436 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006437 return Context.getLogicalOperationType();
6438
Nate Begeman191a6b12008-07-14 18:02:46 +00006439 // For non-floating point types, check for self-comparisons of the form
6440 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6441 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006442 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006443 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6444 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006445 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006446 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006447 PDiag(diag::warn_comparison_always)
6448 << 0 // self-
6449 << 2 // "a constant"
6450 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006451 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006452
Nate Begeman191a6b12008-07-14 18:02:46 +00006453 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006454 if (!isRelational && lType->hasFloatingRepresentation()) {
6455 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006456 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006457 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006458
Nate Begeman191a6b12008-07-14 18:02:46 +00006459 // Return the type for the comparison, which is the same as vector type for
6460 // integer vectors, or an integer type of identical size and number of
6461 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006462 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006463 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006464
John McCall9dd450b2009-09-21 23:43:11 +00006465 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006466 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006467 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006468 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006469 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006470 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6471
Mike Stump4e1f26a2009-02-19 03:04:26 +00006472 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006473 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006474 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6475}
6476
Steve Naroff218bc2b2007-05-04 21:54:46 +00006477inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006478 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6479 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6480 if (lex.get()->getType()->hasIntegerRepresentation() &&
6481 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006482 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006483
6484 return InvalidOperands(Loc, lex, rex);
6485 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006486
John Wiegley01296292011-04-08 18:41:53 +00006487 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6488 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6489 if (lexResult.isInvalid() || rexResult.isInvalid())
6490 return QualType();
6491 lex = lexResult.take();
6492 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
John Wiegley01296292011-04-08 18:41:53 +00006494 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6495 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006496 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006497 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006498}
6499
Steve Naroff218bc2b2007-05-04 21:54:46 +00006500inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006501 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006502
6503 // Diagnose cases where the user write a logical and/or but probably meant a
6504 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6505 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006506 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6507 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006508 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006509 !Loc.isMacroID()) {
6510 // If the RHS can be constant folded, and if it constant folds to something
6511 // that isn't 0 or 1 (which indicate a potential logical operation that
6512 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006513 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006514 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006515 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6516 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6517 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6518 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6519 << rex.get()->getSourceRange()
6520 << (Opc == BO_LAnd ? "&&" : "||")
6521 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006522 }
6523 }
Chris Lattner8406c512010-07-13 19:41:32 +00006524
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006525 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006526 lex = UsualUnaryConversions(lex.take());
6527 if (lex.isInvalid())
6528 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
John Wiegley01296292011-04-08 18:41:53 +00006530 rex = UsualUnaryConversions(rex.take());
6531 if (rex.isInvalid())
6532 return QualType();
6533
6534 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006535 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006536
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006537 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006538 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006539
John McCall4a2429a2010-06-04 00:29:51 +00006540 // The following is safe because we only use this method for
6541 // non-overloadable operands.
6542
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006543 // C++ [expr.log.and]p1
6544 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006545 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006546 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6547 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006548 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006549 lex = move(lexRes);
6550
6551 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6552 if (rexRes.isInvalid())
6553 return InvalidOperands(Loc, lex, rex);
6554 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006555
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006556 // C++ [expr.log.and]p2
6557 // C++ [expr.log.or]p2
6558 // The result is a bool.
6559 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006560}
6561
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006562/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6563/// is a read-only property; return true if so. A readonly property expression
6564/// depends on various declarations and thus must be treated specially.
6565///
Mike Stump11289f42009-09-09 15:08:12 +00006566static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006567 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6568 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006569 if (PropExpr->isImplicitProperty()) return false;
6570
6571 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6572 QualType BaseType = PropExpr->isSuperReceiver() ?
6573 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006574 PropExpr->getBase()->getType();
6575
John McCallb7bd14f2010-12-02 01:19:52 +00006576 if (const ObjCObjectPointerType *OPT =
6577 BaseType->getAsObjCInterfacePointerType())
6578 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6579 if (S.isPropertyReadonly(PDecl, IFace))
6580 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006581 }
6582 return false;
6583}
6584
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006585static bool IsConstProperty(Expr *E, Sema &S) {
6586 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6587 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6588 if (PropExpr->isImplicitProperty()) return false;
6589
6590 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6591 QualType T = PDecl->getType();
6592 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006593 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006594 CanQualType CT = S.Context.getCanonicalType(T);
6595 return CT.isConstQualified();
6596 }
6597 return false;
6598}
6599
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006600static bool IsReadonlyMessage(Expr *E, Sema &S) {
6601 if (E->getStmtClass() != Expr::MemberExprClass)
6602 return false;
6603 const MemberExpr *ME = cast<MemberExpr>(E);
6604 NamedDecl *Member = ME->getMemberDecl();
6605 if (isa<FieldDecl>(Member)) {
6606 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6607 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6608 return false;
6609 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6610 }
6611 return false;
6612}
6613
Chris Lattner30bd3272008-11-18 01:22:49 +00006614/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6615/// emit an error and return true. If so, return false.
6616static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006617 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006618 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006619 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006620 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6621 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006622 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6623 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006624 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6625 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006626 if (IsLV == Expr::MLV_Valid)
6627 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006628
Chris Lattner30bd3272008-11-18 01:22:49 +00006629 unsigned Diag = 0;
6630 bool NeedType = false;
6631 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006632 case Expr::MLV_ConstQualified:
6633 Diag = diag::err_typecheck_assign_const;
6634
John McCalld4631322011-06-17 06:42:21 +00006635 // In ARC, use some specialized diagnostics for occasions where we
6636 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006637 if (S.getLangOptions().ObjCAutoRefCount) {
6638 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6639 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6640 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6641
John McCalld4631322011-06-17 06:42:21 +00006642 // Use the normal diagnostic if it's pseudo-__strong but the
6643 // user actually wrote 'const'.
6644 if (var->isARCPseudoStrong() &&
6645 (!var->getTypeSourceInfo() ||
6646 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6647 // There are two pseudo-strong cases:
6648 // - self
John McCall31168b02011-06-15 23:02:42 +00006649 ObjCMethodDecl *method = S.getCurMethodDecl();
6650 if (method && var == method->getSelfDecl())
6651 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006652
6653 // - fast enumeration variables
6654 else
John McCall31168b02011-06-15 23:02:42 +00006655 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006656
John McCall31168b02011-06-15 23:02:42 +00006657 SourceRange Assign;
6658 if (Loc != OrigLoc)
6659 Assign = SourceRange(OrigLoc, OrigLoc);
6660 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6661 // We need to preserve the AST regardless, so migration tool
6662 // can do its job.
6663 return false;
6664 }
6665 }
6666 }
6667
6668 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006669 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006670 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6671 NeedType = true;
6672 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006673 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006674 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6675 NeedType = true;
6676 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006677 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006678 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6679 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006680 case Expr::MLV_Valid:
6681 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006682 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006683 case Expr::MLV_MemberFunction:
6684 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006685 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6686 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006687 case Expr::MLV_IncompleteType:
6688 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006689 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006690 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006691 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006692 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006693 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6694 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006695 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006696 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6697 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006698 case Expr::MLV_ReadonlyProperty:
6699 Diag = diag::error_readonly_property_assignment;
6700 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006701 case Expr::MLV_NoSetterProperty:
6702 Diag = diag::error_nosetter_property_assignment;
6703 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006704 case Expr::MLV_InvalidMessageExpression:
6705 Diag = diag::error_readonly_message_assignment;
6706 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006707 case Expr::MLV_SubObjCPropertySetting:
6708 Diag = diag::error_no_subobject_property_setting;
6709 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006710 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006711
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006712 SourceRange Assign;
6713 if (Loc != OrigLoc)
6714 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006715 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006716 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006717 else
Mike Stump11289f42009-09-09 15:08:12 +00006718 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006719 return true;
6720}
6721
6722
6723
6724// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006725QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006726 SourceLocation Loc,
6727 QualType CompoundType) {
6728 // Verify that LHS is a modifiable lvalue, and emit error if not.
6729 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006730 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006731
6732 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006733 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006734 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006735 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006736 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006737 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006738 if (LHS->getObjectKind() == OK_ObjCProperty) {
6739 ExprResult LHSResult = Owned(LHS);
6740 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6741 if (LHSResult.isInvalid())
6742 return QualType();
6743 LHS = LHSResult.take();
6744 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006745 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006746 if (RHS.isInvalid())
6747 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006748 // Special case of NSObject attributes on c-style pointer types.
6749 if (ConvTy == IncompatiblePointer &&
6750 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006751 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006752 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006753 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006754 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006755
John McCall7decc9e2010-11-18 06:31:45 +00006756 if (ConvTy == Compatible &&
6757 getLangOptions().ObjCNonFragileABI &&
6758 LHSType->isObjCObjectType())
6759 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6760 << LHSType;
6761
Chris Lattnerea714382008-08-21 18:04:13 +00006762 // If the RHS is a unary plus or minus, check to see if they = and + are
6763 // right next to each other. If so, the user may have typo'd "x =+ 4"
6764 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006765 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6767 RHSCheck = ICE->getSubExpr();
6768 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006769 if ((UO->getOpcode() == UO_Plus ||
6770 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006771 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006772 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006773 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6774 // And there is a space or other character before the subexpr of the
6775 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006776 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6777 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006778 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006779 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006780 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006781 }
Chris Lattnerea714382008-08-21 18:04:13 +00006782 }
John McCall31168b02011-06-15 23:02:42 +00006783
6784 if (ConvTy == Compatible) {
6785 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6786 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006787 else if (getLangOptions().ObjCAutoRefCount)
6788 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006789 }
Chris Lattnerea714382008-08-21 18:04:13 +00006790 } else {
6791 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006792 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006793 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006794
Chris Lattner326f7572008-11-18 01:30:42 +00006795 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006796 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006797 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006798
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006799 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006800 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006801 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006802
Steve Naroff98cf3e92007-06-06 18:38:38 +00006803 // C99 6.5.16p3: The type of an assignment expression is the type of the
6804 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006805 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006806 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6807 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006808 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006809 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006810 return (getLangOptions().CPlusPlus
6811 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006812}
6813
Chris Lattner326f7572008-11-18 01:30:42 +00006814// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006815static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006816 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006817 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006818
John McCall3aef3d82011-04-10 19:13:55 +00006819 LHS = S.CheckPlaceholderExpr(LHS.take());
6820 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006821 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006822 return QualType();
6823
John McCall73d36182010-10-12 07:14:40 +00006824 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6825 // operands, but not unary promotions.
6826 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006827
John McCall34376a62010-12-04 03:47:34 +00006828 // So we treat the LHS as a ignored value, and in C++ we allow the
6829 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006830 LHS = S.IgnoredValueConversions(LHS.take());
6831 if (LHS.isInvalid())
6832 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006833
6834 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006835 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6836 if (RHS.isInvalid())
6837 return QualType();
6838 if (!RHS.get()->getType()->isVoidType())
6839 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006840 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006841
John Wiegley01296292011-04-08 18:41:53 +00006842 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006843}
6844
Steve Naroff7a5af782007-07-13 16:58:59 +00006845/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6846/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006847static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6848 ExprValueKind &VK,
6849 SourceLocation OpLoc,
6850 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006851 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006852 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006853
Chris Lattner6b0cf142008-11-21 07:05:48 +00006854 QualType ResType = Op->getType();
6855 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006856
John McCall4bc41ae2010-11-18 19:01:18 +00006857 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006858 // Decrement of bool is not allowed.
6859 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006860 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006861 return QualType();
6862 }
6863 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006864 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006865 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006866 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006867 } else if (ResType->isAnyPointerType()) {
6868 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006869
Chris Lattner6b0cf142008-11-21 07:05:48 +00006870 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006871 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006872 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006873
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006874 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006875 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6876 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006877 << PointeeTy << Op->getSourceRange();
6878 return QualType();
6879 }
Eli Friedman090addd2010-01-03 00:20:48 +00006880 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006881 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006882 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006883 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006884 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006885 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006886 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006887 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6888 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006889 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6890 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006891 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006892 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006893 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006894 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006895 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006897 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006898 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006899 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006900 // In C++, a prefix increment is the same type as the operand. Otherwise
6901 // (in C or with postfix), the increment is the unqualified type of the
6902 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006903 if (isPrefix && S.getLangOptions().CPlusPlus) {
6904 VK = VK_LValue;
6905 return ResType;
6906 } else {
6907 VK = VK_RValue;
6908 return ResType.getUnqualifiedType();
6909 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006910}
6911
John Wiegley01296292011-04-08 18:41:53 +00006912ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006913 assert(E->getValueKind() == VK_LValue &&
6914 E->getObjectKind() == OK_ObjCProperty);
6915 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6916
Douglas Gregor33823722011-06-11 01:09:30 +00006917 QualType T = E->getType();
6918 QualType ReceiverType;
6919 if (PRE->isObjectReceiver())
6920 ReceiverType = PRE->getBase()->getType();
6921 else if (PRE->isSuperReceiver())
6922 ReceiverType = PRE->getSuperReceiverType();
6923 else
6924 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6925
John McCall34376a62010-12-04 03:47:34 +00006926 ExprValueKind VK = VK_RValue;
6927 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006928 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006929 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006930 T = getMessageSendResultType(ReceiverType, GetterMethod,
6931 PRE->isClassReceiver(),
6932 PRE->isSuperReceiver());
6933 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006934 }
6935 else {
6936 Diag(PRE->getLocation(), diag::err_getter_not_found)
6937 << PRE->getBase()->getType();
6938 }
John McCall34376a62010-12-04 03:47:34 +00006939 }
Douglas Gregor33823722011-06-11 01:09:30 +00006940
6941 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00006942 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00006943
6944 ExprResult Result = MaybeBindToTemporary(E);
6945 if (!Result.isInvalid())
6946 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00006947
6948 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00006949}
6950
John Wiegley01296292011-04-08 18:41:53 +00006951void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
6952 assert(LHS.get()->getValueKind() == VK_LValue &&
6953 LHS.get()->getObjectKind() == OK_ObjCProperty);
6954 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00006955
John McCall31168b02011-06-15 23:02:42 +00006956 bool Consumed = false;
6957
John Wiegley01296292011-04-08 18:41:53 +00006958 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00006959 // If using property-dot syntax notation for assignment, and there is a
6960 // setter, RHS expression is being passed to the setter argument. So,
6961 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00006962 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00006963 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6964 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00006965 Consumed = (getLangOptions().ObjCAutoRefCount &&
6966 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00006967
6968 // Otherwise, if the getter returns an l-value, just call that.
6969 } else {
John Wiegley01296292011-04-08 18:41:53 +00006970 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00006971 ExprValueKind VK = Expr::getValueKindForType(Result);
6972 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00006973 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
6974 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00006975 return;
John McCallb7bd14f2010-12-02 01:19:52 +00006976 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006977 }
John McCall31168b02011-06-15 23:02:42 +00006978 } else if (getLangOptions().ObjCAutoRefCount) {
6979 const ObjCMethodDecl *setter
6980 = PropRef->getExplicitProperty()->getSetterMethodDecl();
6981 if (setter) {
6982 ObjCMethodDecl::param_iterator P = setter->param_begin();
6983 LHSTy = (*P)->getType();
6984 Consumed = (*P)->hasAttr<NSConsumedAttr>();
6985 }
John McCall34376a62010-12-04 03:47:34 +00006986 }
6987
John McCall31168b02011-06-15 23:02:42 +00006988 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
6989 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006990 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00006991 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00006992 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00006993 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00006994 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00006995 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
6996 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
6997 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00006998 }
6999}
7000
7001
Anders Carlsson806700f2008-02-01 07:15:58 +00007002/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007003/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007004/// where the declaration is needed for type checking. We only need to
7005/// handle cases when the expression references a function designator
7006/// or is an lvalue. Here are some examples:
7007/// - &(x) => x
7008/// - &*****f => f for f a function designator.
7009/// - &s.xx => s
7010/// - &s.zz[1].yy -> s, if zz is an array
7011/// - *(x + 1) -> x, if x is an array
7012/// - &"123"[2] -> 0
7013/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007014static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007015 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007016 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007017 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007018 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007019 // If this is an arrow operator, the address is an offset from
7020 // the base's value, so the object the base refers to is
7021 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007022 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007023 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007024 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007025 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007026 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007027 // FIXME: This code shouldn't be necessary! We should catch the implicit
7028 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007029 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7030 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7031 if (ICE->getSubExpr()->getType()->isArrayType())
7032 return getPrimaryDecl(ICE->getSubExpr());
7033 }
7034 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007035 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007036 case Stmt::UnaryOperatorClass: {
7037 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007038
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007039 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007040 case UO_Real:
7041 case UO_Imag:
7042 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007043 return getPrimaryDecl(UO->getSubExpr());
7044 default:
7045 return 0;
7046 }
7047 }
Steve Naroff47500512007-04-19 23:00:49 +00007048 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007049 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007050 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007051 // If the result of an implicit cast is an l-value, we care about
7052 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007053 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007054 default:
7055 return 0;
7056 }
7057}
7058
7059/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007060/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007061/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007062/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007063/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007064/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007065/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007066static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7067 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007068 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007069 return S.Context.DependentTy;
7070 if (OrigOp->getType() == S.Context.OverloadTy)
7071 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007072 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7073 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007074 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7075 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7076 << OrigOp->getSourceRange();
7077 return QualType();
7078 }
John McCall8d08b9b2010-08-27 09:08:28 +00007079
John McCall2979fe02011-04-12 00:42:48 +00007080 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007081
John McCall8d08b9b2010-08-27 09:08:28 +00007082 // Make sure to ignore parentheses in subsequent checks
7083 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007084
John McCall4bc41ae2010-11-18 19:01:18 +00007085 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007086 // Implement C99-only parts of addressof rules.
7087 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007088 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007089 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7090 // (assuming the deref expression is valid).
7091 return uOp->getSubExpr()->getType();
7092 }
7093 // Technically, there should be a check for array subscript
7094 // expressions here, but the result of one is always an lvalue anyway.
7095 }
John McCallf3a88602011-02-03 08:15:49 +00007096 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007097 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007098
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007099 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007100 bool sfinae = S.isSFINAEContext();
7101 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7102 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007103 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007104 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007105 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007106 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007107 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007108 } else if (lval == Expr::LV_MemberFunction) {
7109 // If it's an instance method, make a member pointer.
7110 // The expression must have exactly the form &A::foo.
7111
7112 // If the underlying expression isn't a decl ref, give up.
7113 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007114 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007115 << OrigOp->getSourceRange();
7116 return QualType();
7117 }
7118 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7119 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7120
7121 // The id-expression was parenthesized.
7122 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007123 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007124 << OrigOp->getSourceRange();
7125
7126 // The method was named without a qualifier.
7127 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007128 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007129 << op->getSourceRange();
7130 }
7131
John McCall4bc41ae2010-11-18 19:01:18 +00007132 return S.Context.getMemberPointerType(op->getType(),
7133 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007134 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007135 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007136 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007137 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007138 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007139 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007140 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007141 return QualType();
7142 }
John McCall086a4642010-11-24 05:12:34 +00007143 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007144 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007145 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007146 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007147 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007148 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007149 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007150 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007151 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007152 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007153 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007154 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007155 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007156 << "property expression" << op->getSourceRange();
7157 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007158 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007159 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007160 // with the register storage-class specifier.
7161 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007162 // in C++ it is not error to take address of a register
7163 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007164 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007165 !S.getLangOptions().CPlusPlus) {
7166 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007167 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007168 return QualType();
7169 }
John McCalld14a8642009-11-21 08:51:07 +00007170 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007171 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007172 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007173 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007174 // Could be a pointer to member, though, if there is an explicit
7175 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007176 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007177 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007178 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007179 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007180 S.Diag(OpLoc,
7181 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007182 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007183 return QualType();
7184 }
Mike Stump11289f42009-09-09 15:08:12 +00007185
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007186 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7187 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007188 return S.Context.getMemberPointerType(op->getType(),
7189 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007190 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007191 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007192 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007193 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007194 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007195
Eli Friedmance7f9002009-05-16 23:27:50 +00007196 if (lval == Expr::LV_IncompleteVoidType) {
7197 // Taking the address of a void variable is technically illegal, but we
7198 // allow it in cases which are otherwise valid.
7199 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007200 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007201 }
7202
Steve Naroff47500512007-04-19 23:00:49 +00007203 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007204 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007205 return S.Context.getObjCObjectPointerType(op->getType());
7206 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007207}
7208
Chris Lattner9156f1b2010-07-05 19:17:26 +00007209/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007210static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7211 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007212 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007213 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007214
John Wiegley01296292011-04-08 18:41:53 +00007215 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7216 if (ConvResult.isInvalid())
7217 return QualType();
7218 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007219 QualType OpTy = Op->getType();
7220 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007221
7222 if (isa<CXXReinterpretCastExpr>(Op)) {
7223 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7224 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7225 Op->getSourceRange());
7226 }
7227
Chris Lattner9156f1b2010-07-05 19:17:26 +00007228 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7229 // is an incomplete type or void. It would be possible to warn about
7230 // dereferencing a void pointer, but it's completely well-defined, and such a
7231 // warning is unlikely to catch any mistakes.
7232 if (const PointerType *PT = OpTy->getAs<PointerType>())
7233 Result = PT->getPointeeType();
7234 else if (const ObjCObjectPointerType *OPT =
7235 OpTy->getAs<ObjCObjectPointerType>())
7236 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007237 else {
John McCall3aef3d82011-04-10 19:13:55 +00007238 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007239 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007240 if (PR.take() != Op)
7241 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007242 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007243
Chris Lattner9156f1b2010-07-05 19:17:26 +00007244 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007245 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007246 << OpTy << Op->getSourceRange();
7247 return QualType();
7248 }
John McCall4bc41ae2010-11-18 19:01:18 +00007249
7250 // Dereferences are usually l-values...
7251 VK = VK_LValue;
7252
7253 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007254 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007255 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007256
7257 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007258}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007259
John McCalle3027922010-08-25 11:45:40 +00007260static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007261 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007262 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007263 switch (Kind) {
7264 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007265 case tok::periodstar: Opc = BO_PtrMemD; break;
7266 case tok::arrowstar: Opc = BO_PtrMemI; break;
7267 case tok::star: Opc = BO_Mul; break;
7268 case tok::slash: Opc = BO_Div; break;
7269 case tok::percent: Opc = BO_Rem; break;
7270 case tok::plus: Opc = BO_Add; break;
7271 case tok::minus: Opc = BO_Sub; break;
7272 case tok::lessless: Opc = BO_Shl; break;
7273 case tok::greatergreater: Opc = BO_Shr; break;
7274 case tok::lessequal: Opc = BO_LE; break;
7275 case tok::less: Opc = BO_LT; break;
7276 case tok::greaterequal: Opc = BO_GE; break;
7277 case tok::greater: Opc = BO_GT; break;
7278 case tok::exclaimequal: Opc = BO_NE; break;
7279 case tok::equalequal: Opc = BO_EQ; break;
7280 case tok::amp: Opc = BO_And; break;
7281 case tok::caret: Opc = BO_Xor; break;
7282 case tok::pipe: Opc = BO_Or; break;
7283 case tok::ampamp: Opc = BO_LAnd; break;
7284 case tok::pipepipe: Opc = BO_LOr; break;
7285 case tok::equal: Opc = BO_Assign; break;
7286 case tok::starequal: Opc = BO_MulAssign; break;
7287 case tok::slashequal: Opc = BO_DivAssign; break;
7288 case tok::percentequal: Opc = BO_RemAssign; break;
7289 case tok::plusequal: Opc = BO_AddAssign; break;
7290 case tok::minusequal: Opc = BO_SubAssign; break;
7291 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7292 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7293 case tok::ampequal: Opc = BO_AndAssign; break;
7294 case tok::caretequal: Opc = BO_XorAssign; break;
7295 case tok::pipeequal: Opc = BO_OrAssign; break;
7296 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007297 }
7298 return Opc;
7299}
7300
John McCalle3027922010-08-25 11:45:40 +00007301static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007302 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007303 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007304 switch (Kind) {
7305 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007306 case tok::plusplus: Opc = UO_PreInc; break;
7307 case tok::minusminus: Opc = UO_PreDec; break;
7308 case tok::amp: Opc = UO_AddrOf; break;
7309 case tok::star: Opc = UO_Deref; break;
7310 case tok::plus: Opc = UO_Plus; break;
7311 case tok::minus: Opc = UO_Minus; break;
7312 case tok::tilde: Opc = UO_Not; break;
7313 case tok::exclaim: Opc = UO_LNot; break;
7314 case tok::kw___real: Opc = UO_Real; break;
7315 case tok::kw___imag: Opc = UO_Imag; break;
7316 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007317 }
7318 return Opc;
7319}
7320
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007321/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7322/// This warning is only emitted for builtin assignment operations. It is also
7323/// suppressed in the event of macro expansions.
7324static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7325 SourceLocation OpLoc) {
7326 if (!S.ActiveTemplateInstantiations.empty())
7327 return;
7328 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7329 return;
7330 lhs = lhs->IgnoreParenImpCasts();
7331 rhs = rhs->IgnoreParenImpCasts();
7332 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7333 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7334 if (!LeftDeclRef || !RightDeclRef ||
7335 LeftDeclRef->getLocation().isMacroID() ||
7336 RightDeclRef->getLocation().isMacroID())
7337 return;
7338 const ValueDecl *LeftDecl =
7339 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7340 const ValueDecl *RightDecl =
7341 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7342 if (LeftDecl != RightDecl)
7343 return;
7344 if (LeftDecl->getType().isVolatileQualified())
7345 return;
7346 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7347 if (RefTy->getPointeeType().isVolatileQualified())
7348 return;
7349
7350 S.Diag(OpLoc, diag::warn_self_assignment)
7351 << LeftDeclRef->getType()
7352 << lhs->getSourceRange() << rhs->getSourceRange();
7353}
7354
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007355/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7356/// operator @p Opc at location @c TokLoc. This routine only supports
7357/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007358ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007359 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007360 Expr *lhsExpr, Expr *rhsExpr) {
7361 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007362 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007363 // The following two variables are used for compound assignment operators
7364 QualType CompLHSTy; // Type of LHS after promotions for computation
7365 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007366 ExprValueKind VK = VK_RValue;
7367 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007368
Douglas Gregor1beec452011-03-12 01:48:56 +00007369 // Check if a 'foo<int>' involved in a binary op, identifies a single
7370 // function unambiguously (i.e. an lvalue ala 13.4)
7371 // But since an assignment can trigger target based overload, exclude it in
7372 // our blind search. i.e:
7373 // template<class T> void f(); template<class T, class U> void f(U);
7374 // f<int> == 0; // resolve f<int> blindly
7375 // void (*p)(int); p = f<int>; // resolve f<int> using target
7376 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007377 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007378 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007379 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007380
John McCall3aef3d82011-04-10 19:13:55 +00007381 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007382 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007383 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007384 }
7385
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007386 // The canonical way to check for a GNU null is with isNullPointerConstant,
7387 // but we use a bit of a hack here for speed; this is a relatively
7388 // hot path, and isNullPointerConstant is slow.
7389 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7390 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007391
7392 // Detect when a NULL constant is used improperly in an expression. These
7393 // are mainly cases where the null pointer is used as an integer instead
7394 // of a pointer.
7395 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007396 // Avoid analyzing cases where the result will either be invalid (and
7397 // diagnosed as such) or entirely valid and not something to warn about.
7398 QualType LeftType = lhs.get()->getType();
7399 QualType RightType = rhs.get()->getType();
7400 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7401 !LeftType->isFunctionType() &&
7402 !RightType->isBlockPointerType() &&
7403 !RightType->isMemberPointerType() &&
7404 !RightType->isFunctionType()) {
7405 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7406 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7407 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7408 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7409 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7410 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7411 // These are the operations that would not make sense with a null pointer
7412 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007413 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007414 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7415 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7416 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7417 Opc == BO_EQ || Opc == BO_NE) {
7418 // These are the operations that would not make sense with a null pointer
7419 // if the other expression the other expression is not a pointer.
7420 if (LeftNull != RightNull &&
7421 !LeftType->isAnyPointerType() &&
7422 !LeftType->canDecayToPointerType() &&
7423 !RightType->isAnyPointerType() &&
7424 !RightType->canDecayToPointerType()) {
7425 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7426 << (LeftNull ? lhs.get()->getSourceRange()
7427 : rhs.get()->getSourceRange());
7428 }
Richard Trieu701fb362011-06-16 21:36:56 +00007429 }
7430 }
7431 }
7432
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007433 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007434 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007435 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007436 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007437 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7438 VK = lhs.get()->getValueKind();
7439 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007440 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007441 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007442 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007443 break;
John McCalle3027922010-08-25 11:45:40 +00007444 case BO_PtrMemD:
7445 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007446 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007447 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007448 break;
John McCalle3027922010-08-25 11:45:40 +00007449 case BO_Mul:
7450 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007451 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007452 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007453 break;
John McCalle3027922010-08-25 11:45:40 +00007454 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007455 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7456 break;
John McCalle3027922010-08-25 11:45:40 +00007457 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007458 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7459 break;
John McCalle3027922010-08-25 11:45:40 +00007460 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007461 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7462 break;
John McCalle3027922010-08-25 11:45:40 +00007463 case BO_Shl:
7464 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007465 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007466 break;
John McCalle3027922010-08-25 11:45:40 +00007467 case BO_LE:
7468 case BO_LT:
7469 case BO_GE:
7470 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007471 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007472 break;
John McCalle3027922010-08-25 11:45:40 +00007473 case BO_EQ:
7474 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007475 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007476 break;
John McCalle3027922010-08-25 11:45:40 +00007477 case BO_And:
7478 case BO_Xor:
7479 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007480 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7481 break;
John McCalle3027922010-08-25 11:45:40 +00007482 case BO_LAnd:
7483 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007484 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007485 break;
John McCalle3027922010-08-25 11:45:40 +00007486 case BO_MulAssign:
7487 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007488 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007489 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007490 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007491 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7492 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007493 break;
John McCalle3027922010-08-25 11:45:40 +00007494 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007495 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7496 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007497 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7498 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007499 break;
John McCalle3027922010-08-25 11:45:40 +00007500 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007501 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007502 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7503 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007504 break;
John McCalle3027922010-08-25 11:45:40 +00007505 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007506 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007507 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7508 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007509 break;
John McCalle3027922010-08-25 11:45:40 +00007510 case BO_ShlAssign:
7511 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007512 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007513 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007514 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7515 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007516 break;
John McCalle3027922010-08-25 11:45:40 +00007517 case BO_AndAssign:
7518 case BO_XorAssign:
7519 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007520 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7521 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007522 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7523 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007524 break;
John McCalle3027922010-08-25 11:45:40 +00007525 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007526 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007527 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7528 VK = rhs.get()->getValueKind();
7529 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007530 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007531 break;
7532 }
John Wiegley01296292011-04-08 18:41:53 +00007533 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007534 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007535 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007536 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7537 ResultTy, VK, OK, OpLoc));
7538 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007539 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007540 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007541 }
John Wiegley01296292011-04-08 18:41:53 +00007542 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7543 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007544 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007545}
7546
Sebastian Redl44615072009-10-27 12:10:02 +00007547/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7548/// operators are mixed in a way that suggests that the programmer forgot that
7549/// comparison operators have higher precedence. The most typical example of
7550/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007551static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007552 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007553 typedef BinaryOperator BinOp;
7554 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7555 rhsopc = static_cast<BinOp::Opcode>(-1);
7556 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007557 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007558 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007559 rhsopc = BO->getOpcode();
7560
7561 // Subs are not binary operators.
7562 if (lhsopc == -1 && rhsopc == -1)
7563 return;
7564
7565 // Bitwise operations are sometimes used as eager logical ops.
7566 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007567 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7568 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007569 return;
7570
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007571 if (BinOp::isComparisonOp(lhsopc)) {
7572 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7573 << SourceRange(lhs->getLocStart(), OpLoc)
7574 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007575 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007576 Self.PDiag(diag::note_precedence_bitwise_silence)
7577 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007578 lhs->getSourceRange());
7579 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007580 Self.PDiag(diag::note_precedence_bitwise_first)
7581 << BinOp::getOpcodeStr(Opc),
7582 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007583 } else if (BinOp::isComparisonOp(rhsopc)) {
7584 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7585 << SourceRange(OpLoc, rhs->getLocEnd())
7586 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007587 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007588 Self.PDiag(diag::note_precedence_bitwise_silence)
7589 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007590 rhs->getSourceRange());
7591 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007592 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007593 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007594 SourceRange(lhs->getLocStart(),
7595 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007596 }
Sebastian Redl43028242009-10-26 15:24:15 +00007597}
7598
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007599/// \brief It accepts a '&' expr that is inside a '|' one.
7600/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7601/// in parentheses.
7602static void
7603EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7604 BinaryOperator *Bop) {
7605 assert(Bop->getOpcode() == BO_And);
7606 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7607 << Bop->getSourceRange() << OpLoc;
7608 SuggestParentheses(Self, Bop->getOperatorLoc(),
7609 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7610 Bop->getSourceRange());
7611}
7612
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007613/// \brief It accepts a '&&' expr that is inside a '||' one.
7614/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7615/// in parentheses.
7616static void
7617EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007618 BinaryOperator *Bop) {
7619 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007620 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7621 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007622 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007623 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007624 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007625}
7626
7627/// \brief Returns true if the given expression can be evaluated as a constant
7628/// 'true'.
7629static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7630 bool Res;
7631 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7632}
7633
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007634/// \brief Returns true if the given expression can be evaluated as a constant
7635/// 'false'.
7636static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7637 bool Res;
7638 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7639}
7640
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007641/// \brief Look for '&&' in the left hand of a '||' expr.
7642static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007643 Expr *OrLHS, Expr *OrRHS) {
7644 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007645 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007646 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7647 if (EvaluatesAsFalse(S, OrRHS))
7648 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007649 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7650 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7651 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7652 } else if (Bop->getOpcode() == BO_LOr) {
7653 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7654 // If it's "a || b && 1 || c" we didn't warn earlier for
7655 // "a || b && 1", but warn now.
7656 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7657 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7658 }
7659 }
7660 }
7661}
7662
7663/// \brief Look for '&&' in the right hand of a '||' expr.
7664static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007665 Expr *OrLHS, Expr *OrRHS) {
7666 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007667 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007668 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7669 if (EvaluatesAsFalse(S, OrLHS))
7670 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007671 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7672 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7673 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007674 }
7675 }
7676}
7677
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007678/// \brief Look for '&' in the left or right hand of a '|' expr.
7679static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7680 Expr *OrArg) {
7681 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7682 if (Bop->getOpcode() == BO_And)
7683 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7684 }
7685}
7686
Sebastian Redl43028242009-10-26 15:24:15 +00007687/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007688/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007689static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007690 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007691 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007692 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007693 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7694
7695 // Diagnose "arg1 & arg2 | arg3"
7696 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7697 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7698 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7699 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007700
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007701 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7702 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007703 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007704 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7705 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007706 }
Sebastian Redl43028242009-10-26 15:24:15 +00007707}
7708
Steve Naroff218bc2b2007-05-04 21:54:46 +00007709// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007710ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007711 tok::TokenKind Kind,
7712 Expr *lhs, Expr *rhs) {
7713 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007714 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7715 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007716
Sebastian Redl43028242009-10-26 15:24:15 +00007717 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7718 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7719
Douglas Gregor5287f092009-11-05 00:51:44 +00007720 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7721}
7722
John McCalldadc5752010-08-24 06:29:42 +00007723ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007724 BinaryOperatorKind Opc,
7725 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007726 if (getLangOptions().CPlusPlus) {
7727 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007728
John McCall622114c2010-12-06 05:26:58 +00007729 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7730 UseBuiltinOperator = false;
7731 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7732 UseBuiltinOperator = true;
7733 } else {
7734 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7735 !rhs->getType()->isOverloadableType();
7736 }
7737
7738 if (!UseBuiltinOperator) {
7739 // Find all of the overloaded operators visible from this
7740 // point. We perform both an operator-name lookup from the local
7741 // scope and an argument-dependent lookup based on the types of
7742 // the arguments.
7743 UnresolvedSet<16> Functions;
7744 OverloadedOperatorKind OverOp
7745 = BinaryOperator::getOverloadedOperator(Opc);
7746 if (S && OverOp != OO_None)
7747 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7748 Functions);
7749
7750 // Build the (potentially-overloaded, potentially-dependent)
7751 // binary operation.
7752 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7753 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007754 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007755
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007756 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007757 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007758}
7759
John McCalldadc5752010-08-24 06:29:42 +00007760ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007761 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007762 Expr *InputExpr) {
7763 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007764 ExprValueKind VK = VK_RValue;
7765 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007766 QualType resultType;
7767 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007768 case UO_PreInc:
7769 case UO_PreDec:
7770 case UO_PostInc:
7771 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007772 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007773 Opc == UO_PreInc ||
7774 Opc == UO_PostInc,
7775 Opc == UO_PreInc ||
7776 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007777 break;
John McCalle3027922010-08-25 11:45:40 +00007778 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007779 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007780 break;
John McCall31996342011-04-07 08:22:57 +00007781 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007782 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007783 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007784 Input = move(resolved);
7785 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7786 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007787 break;
John McCall31996342011-04-07 08:22:57 +00007788 }
John McCalle3027922010-08-25 11:45:40 +00007789 case UO_Plus:
7790 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007791 Input = UsualUnaryConversions(Input.take());
7792 if (Input.isInvalid()) return ExprError();
7793 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007794 if (resultType->isDependentType())
7795 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007796 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7797 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007798 break;
7799 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7800 resultType->isEnumeralType())
7801 break;
7802 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007803 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007804 resultType->isPointerType())
7805 break;
John McCall36226622010-10-12 02:09:17 +00007806 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007807 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007808 if (Input.isInvalid()) return ExprError();
7809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007810 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007811
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007812 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007813 << resultType << Input.get()->getSourceRange());
7814
John McCalle3027922010-08-25 11:45:40 +00007815 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007816 Input = UsualUnaryConversions(Input.take());
7817 if (Input.isInvalid()) return ExprError();
7818 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007819 if (resultType->isDependentType())
7820 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007821 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7822 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7823 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007824 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007825 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007826 else if (resultType->hasIntegerRepresentation())
7827 break;
7828 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007829 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007830 if (Input.isInvalid()) return ExprError();
7831 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007832 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007833 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007834 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007835 }
Steve Naroff35d85152007-05-07 00:24:15 +00007836 break;
John Wiegley01296292011-04-08 18:41:53 +00007837
John McCalle3027922010-08-25 11:45:40 +00007838 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007839 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007840 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7841 if (Input.isInvalid()) return ExprError();
7842 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007843 if (resultType->isDependentType())
7844 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007845 if (resultType->isScalarType()) {
7846 // C99 6.5.3.3p1: ok, fallthrough;
7847 if (Context.getLangOptions().CPlusPlus) {
7848 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7849 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007850 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7851 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007852 }
John McCall36226622010-10-12 02:09:17 +00007853 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007854 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007855 if (Input.isInvalid()) return ExprError();
7856 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007857 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007858 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007859 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007860 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007861
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007862 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007863 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007864 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007865 break;
John McCalle3027922010-08-25 11:45:40 +00007866 case UO_Real:
7867 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007868 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007869 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007870 if (Input.isInvalid()) return ExprError();
7871 if (Input.get()->getValueKind() != VK_RValue &&
7872 Input.get()->getObjectKind() == OK_Ordinary)
7873 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007874 break;
John McCalle3027922010-08-25 11:45:40 +00007875 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007876 resultType = Input.get()->getType();
7877 VK = Input.get()->getValueKind();
7878 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007879 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007880 }
John Wiegley01296292011-04-08 18:41:53 +00007881 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007882 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007883
John Wiegley01296292011-04-08 18:41:53 +00007884 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007885 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007886}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007887
John McCalldadc5752010-08-24 06:29:42 +00007888ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007889 UnaryOperatorKind Opc,
7890 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007891 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007892 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007893 // Find all of the overloaded operators visible from this
7894 // point. We perform both an operator-name lookup from the local
7895 // scope and an argument-dependent lookup based on the types of
7896 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007897 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007898 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007899 if (S && OverOp != OO_None)
7900 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7901 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007902
John McCallb268a282010-08-23 23:25:46 +00007903 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007904 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007905
John McCallb268a282010-08-23 23:25:46 +00007906 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007907}
7908
Douglas Gregor5287f092009-11-05 00:51:44 +00007909// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007910ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007911 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007912 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007913}
7914
Steve Naroff66356bd2007-09-16 14:56:35 +00007915/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007916ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007917 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007918 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007919 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007920 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007921 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007922}
7923
John McCall31168b02011-06-15 23:02:42 +00007924/// Given the last statement in a statement-expression, check whether
7925/// the result is a producing expression (like a call to an
7926/// ns_returns_retained function) and, if so, rebuild it to hoist the
7927/// release out of the full-expression. Otherwise, return null.
7928/// Cannot fail.
7929static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7930 // Should always be wrapped with one of these.
7931 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7932 if (!cleanups) return 0;
7933
7934 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7935 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7936 return 0;
7937
7938 // Splice out the cast. This shouldn't modify any interesting
7939 // features of the statement.
7940 Expr *producer = cast->getSubExpr();
7941 assert(producer->getType() == cast->getType());
7942 assert(producer->getValueKind() == cast->getValueKind());
7943 cleanups->setSubExpr(producer);
7944 return cleanups;
7945}
7946
John McCalldadc5752010-08-24 06:29:42 +00007947ExprResult
John McCallb268a282010-08-23 23:25:46 +00007948Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007949 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007950 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7951 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7952
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007953 bool isFileScope
7954 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007955 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007956 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007957
Chris Lattner366727f2007-07-24 16:58:17 +00007958 // FIXME: there are a variety of strange constraints to enforce here, for
7959 // example, it is not possible to goto into a stmt expression apparently.
7960 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007961
Chris Lattner366727f2007-07-24 16:58:17 +00007962 // If there are sub stmts in the compound stmt, take the type of the last one
7963 // as the type of the stmtexpr.
7964 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007965 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00007966 if (!Compound->body_empty()) {
7967 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007968 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00007969 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007970 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7971 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00007972 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007973 }
John McCall31168b02011-06-15 23:02:42 +00007974
John Wiegley01296292011-04-08 18:41:53 +00007975 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00007976 // Do function/array conversion on the last expression, but not
7977 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00007978 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
7979 if (LastExpr.isInvalid())
7980 return ExprError();
7981 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00007982
John Wiegley01296292011-04-08 18:41:53 +00007983 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00007984 // In ARC, if the final expression ends in a consume, splice
7985 // the consume out and bind it later. In the alternate case
7986 // (when dealing with a retainable type), the result
7987 // initialization will create a produce. In both cases the
7988 // result will be +1, and we'll need to balance that out with
7989 // a bind.
7990 if (Expr *rebuiltLastStmt
7991 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
7992 LastExpr = rebuiltLastStmt;
7993 } else {
7994 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00007995 InitializedEntity::InitializeResult(LPLoc,
7996 Ty,
7997 false),
7998 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00007999 LastExpr);
8000 }
8001
John Wiegley01296292011-04-08 18:41:53 +00008002 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008003 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008004 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008005 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008006 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008007 else
John Wiegley01296292011-04-08 18:41:53 +00008008 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008009 StmtExprMayBindToTemp = true;
8010 }
8011 }
8012 }
Chris Lattner944d3062008-07-26 19:51:01 +00008013 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008014
Eli Friedmanba961a92009-03-23 00:24:07 +00008015 // FIXME: Check that expression type is complete/non-abstract; statement
8016 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008017 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8018 if (StmtExprMayBindToTemp)
8019 return MaybeBindToTemporary(ResStmtExpr);
8020 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008021}
Steve Naroff78864672007-08-01 22:05:33 +00008022
John McCalldadc5752010-08-24 06:29:42 +00008023ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008024 TypeSourceInfo *TInfo,
8025 OffsetOfComponent *CompPtr,
8026 unsigned NumComponents,
8027 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008028 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008029 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008030 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008031
Chris Lattnerf17bd422007-08-30 17:45:32 +00008032 // We must have at least one component that refers to the type, and the first
8033 // one is known to be a field designator. Verify that the ArgTy represents
8034 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008035 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008036 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8037 << ArgTy << TypeRange);
8038
8039 // Type must be complete per C99 7.17p3 because a declaring a variable
8040 // with an incomplete type would be ill-formed.
8041 if (!Dependent
8042 && RequireCompleteType(BuiltinLoc, ArgTy,
8043 PDiag(diag::err_offsetof_incomplete_type)
8044 << TypeRange))
8045 return ExprError();
8046
Chris Lattner78502cf2007-08-31 21:49:13 +00008047 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8048 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008049 // FIXME: This diagnostic isn't actually visible because the location is in
8050 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008051 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008052 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8053 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008054
8055 bool DidWarnAboutNonPOD = false;
8056 QualType CurrentType = ArgTy;
8057 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8058 llvm::SmallVector<OffsetOfNode, 4> Comps;
8059 llvm::SmallVector<Expr*, 4> Exprs;
8060 for (unsigned i = 0; i != NumComponents; ++i) {
8061 const OffsetOfComponent &OC = CompPtr[i];
8062 if (OC.isBrackets) {
8063 // Offset of an array sub-field. TODO: Should we allow vector elements?
8064 if (!CurrentType->isDependentType()) {
8065 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8066 if(!AT)
8067 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8068 << CurrentType);
8069 CurrentType = AT->getElementType();
8070 } else
8071 CurrentType = Context.DependentTy;
8072
8073 // The expression must be an integral expression.
8074 // FIXME: An integral constant expression?
8075 Expr *Idx = static_cast<Expr*>(OC.U.E);
8076 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8077 !Idx->getType()->isIntegerType())
8078 return ExprError(Diag(Idx->getLocStart(),
8079 diag::err_typecheck_subscript_not_integer)
8080 << Idx->getSourceRange());
8081
8082 // Record this array index.
8083 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8084 Exprs.push_back(Idx);
8085 continue;
8086 }
8087
8088 // Offset of a field.
8089 if (CurrentType->isDependentType()) {
8090 // We have the offset of a field, but we can't look into the dependent
8091 // type. Just record the identifier of the field.
8092 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8093 CurrentType = Context.DependentTy;
8094 continue;
8095 }
8096
8097 // We need to have a complete type to look into.
8098 if (RequireCompleteType(OC.LocStart, CurrentType,
8099 diag::err_offsetof_incomplete_type))
8100 return ExprError();
8101
8102 // Look for the designated field.
8103 const RecordType *RC = CurrentType->getAs<RecordType>();
8104 if (!RC)
8105 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8106 << CurrentType);
8107 RecordDecl *RD = RC->getDecl();
8108
8109 // C++ [lib.support.types]p5:
8110 // The macro offsetof accepts a restricted set of type arguments in this
8111 // International Standard. type shall be a POD structure or a POD union
8112 // (clause 9).
8113 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8114 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008115 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008116 PDiag(diag::warn_offsetof_non_pod_type)
8117 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8118 << CurrentType))
8119 DidWarnAboutNonPOD = true;
8120 }
8121
8122 // Look for the field.
8123 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8124 LookupQualifiedName(R, RD);
8125 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008126 IndirectFieldDecl *IndirectMemberDecl = 0;
8127 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008128 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008129 MemberDecl = IndirectMemberDecl->getAnonField();
8130 }
8131
Douglas Gregor882211c2010-04-28 22:16:22 +00008132 if (!MemberDecl)
8133 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8134 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8135 OC.LocEnd));
8136
Douglas Gregor10982ea2010-04-28 22:36:06 +00008137 // C99 7.17p3:
8138 // (If the specified member is a bit-field, the behavior is undefined.)
8139 //
8140 // We diagnose this as an error.
8141 if (MemberDecl->getBitWidth()) {
8142 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8143 << MemberDecl->getDeclName()
8144 << SourceRange(BuiltinLoc, RParenLoc);
8145 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8146 return ExprError();
8147 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008148
8149 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008150 if (IndirectMemberDecl)
8151 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008152
Douglas Gregord1702062010-04-29 00:18:15 +00008153 // If the member was found in a base class, introduce OffsetOfNodes for
8154 // the base class indirections.
8155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8156 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008157 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008158 CXXBasePath &Path = Paths.front();
8159 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8160 B != BEnd; ++B)
8161 Comps.push_back(OffsetOfNode(B->Base));
8162 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008163
Francois Pichet783dd6e2010-11-21 06:08:52 +00008164 if (IndirectMemberDecl) {
8165 for (IndirectFieldDecl::chain_iterator FI =
8166 IndirectMemberDecl->chain_begin(),
8167 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8168 assert(isa<FieldDecl>(*FI));
8169 Comps.push_back(OffsetOfNode(OC.LocStart,
8170 cast<FieldDecl>(*FI), OC.LocEnd));
8171 }
8172 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008173 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008174
Douglas Gregor882211c2010-04-28 22:16:22 +00008175 CurrentType = MemberDecl->getType().getNonReferenceType();
8176 }
8177
8178 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8179 TInfo, Comps.data(), Comps.size(),
8180 Exprs.data(), Exprs.size(), RParenLoc));
8181}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008182
John McCalldadc5752010-08-24 06:29:42 +00008183ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008184 SourceLocation BuiltinLoc,
8185 SourceLocation TypeLoc,
8186 ParsedType argty,
8187 OffsetOfComponent *CompPtr,
8188 unsigned NumComponents,
8189 SourceLocation RPLoc) {
8190
Douglas Gregor882211c2010-04-28 22:16:22 +00008191 TypeSourceInfo *ArgTInfo;
8192 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8193 if (ArgTy.isNull())
8194 return ExprError();
8195
Eli Friedman06dcfd92010-08-05 10:15:45 +00008196 if (!ArgTInfo)
8197 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8198
8199 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8200 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008201}
8202
8203
John McCalldadc5752010-08-24 06:29:42 +00008204ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008205 Expr *CondExpr,
8206 Expr *LHSExpr, Expr *RHSExpr,
8207 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008208 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8209
John McCall7decc9e2010-11-18 06:31:45 +00008210 ExprValueKind VK = VK_RValue;
8211 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008212 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008213 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008214 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008215 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008216 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008217 } else {
8218 // The conditional expression is required to be a constant expression.
8219 llvm::APSInt condEval(32);
8220 SourceLocation ExpLoc;
8221 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008222 return ExprError(Diag(ExpLoc,
8223 diag::err_typecheck_choose_expr_requires_constant)
8224 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008225
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008226 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008227 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8228
8229 resType = ActiveExpr->getType();
8230 ValueDependent = ActiveExpr->isValueDependent();
8231 VK = ActiveExpr->getValueKind();
8232 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008233 }
8234
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008235 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008236 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008237 resType->isDependentType(),
8238 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008239}
8240
Steve Naroffc540d662008-09-03 18:15:37 +00008241//===----------------------------------------------------------------------===//
8242// Clang Extensions.
8243//===----------------------------------------------------------------------===//
8244
8245/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008246void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008247 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8248 PushBlockScope(BlockScope, Block);
8249 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008250 if (BlockScope)
8251 PushDeclContext(BlockScope, Block);
8252 else
8253 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008254}
8255
Mike Stump82f071f2009-02-04 22:31:32 +00008256void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008257 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008258 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008259 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008260
John McCall8cb7bdf2010-06-04 23:28:52 +00008261 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008262 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008263
John McCall3882ace2011-01-05 12:14:39 +00008264 // GetTypeForDeclarator always produces a function type for a block
8265 // literal signature. Furthermore, it is always a FunctionProtoType
8266 // unless the function was written with a typedef.
8267 assert(T->isFunctionType() &&
8268 "GetTypeForDeclarator made a non-function block signature");
8269
8270 // Look for an explicit signature in that function type.
8271 FunctionProtoTypeLoc ExplicitSignature;
8272
8273 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8274 if (isa<FunctionProtoTypeLoc>(tmp)) {
8275 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8276
8277 // Check whether that explicit signature was synthesized by
8278 // GetTypeForDeclarator. If so, don't save that as part of the
8279 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008280 if (ExplicitSignature.getLocalRangeBegin() ==
8281 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008282 // This would be much cheaper if we stored TypeLocs instead of
8283 // TypeSourceInfos.
8284 TypeLoc Result = ExplicitSignature.getResultLoc();
8285 unsigned Size = Result.getFullDataSize();
8286 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8287 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8288
8289 ExplicitSignature = FunctionProtoTypeLoc();
8290 }
John McCalla3ccba02010-06-04 11:21:44 +00008291 }
Mike Stump11289f42009-09-09 15:08:12 +00008292
John McCall3882ace2011-01-05 12:14:39 +00008293 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8294 CurBlock->FunctionType = T;
8295
8296 const FunctionType *Fn = T->getAs<FunctionType>();
8297 QualType RetTy = Fn->getResultType();
8298 bool isVariadic =
8299 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8300
John McCall8e346702010-06-04 19:02:56 +00008301 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008302
John McCalla3ccba02010-06-04 11:21:44 +00008303 // Don't allow returning a objc interface by value.
8304 if (RetTy->isObjCObjectType()) {
8305 Diag(ParamInfo.getSourceRange().getBegin(),
8306 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8307 return;
8308 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008309
John McCalla3ccba02010-06-04 11:21:44 +00008310 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008311 // return type. TODO: what should we do with declarators like:
8312 // ^ * { ... }
8313 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008314 if (RetTy != Context.DependentTy)
8315 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008316
John McCalla3ccba02010-06-04 11:21:44 +00008317 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008318 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008319 if (ExplicitSignature) {
8320 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8321 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008322 if (Param->getIdentifier() == 0 &&
8323 !Param->isImplicit() &&
8324 !Param->isInvalidDecl() &&
8325 !getLangOptions().CPlusPlus)
8326 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008327 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008328 }
John McCalla3ccba02010-06-04 11:21:44 +00008329
8330 // Fake up parameter variables if we have a typedef, like
8331 // ^ fntype { ... }
8332 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8333 for (FunctionProtoType::arg_type_iterator
8334 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8335 ParmVarDecl *Param =
8336 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8337 ParamInfo.getSourceRange().getBegin(),
8338 *I);
John McCall8e346702010-06-04 19:02:56 +00008339 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008340 }
Steve Naroffc540d662008-09-03 18:15:37 +00008341 }
John McCalla3ccba02010-06-04 11:21:44 +00008342
John McCall8e346702010-06-04 19:02:56 +00008343 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008344 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008345 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008346 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8347 CurBlock->TheDecl->param_end(),
8348 /*CheckParameterNames=*/false);
8349 }
8350
John McCalla3ccba02010-06-04 11:21:44 +00008351 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008352 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008353
John McCall8e346702010-06-04 19:02:56 +00008354 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008355 Diag(ParamInfo.getAttributes()->getLoc(),
8356 diag::warn_attribute_sentinel_not_variadic) << 1;
8357 // FIXME: remove the attribute.
8358 }
8359
8360 // Put the parameter variables in scope. We can bail out immediately
8361 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008362 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008363 return;
8364
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008365 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008366 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8367 (*AI)->setOwningFunction(CurBlock->TheDecl);
8368
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008369 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008370 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008371 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008372
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008373 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008374 }
John McCallf7b2fb52010-01-22 00:28:27 +00008375 }
Steve Naroffc540d662008-09-03 18:15:37 +00008376}
8377
8378/// ActOnBlockError - If there is an error parsing a block, this callback
8379/// is invoked to pop the information about the block from the action impl.
8380void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008381 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008382 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008383 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008384}
8385
8386/// ActOnBlockStmtExpr - This is called when the body of a block statement
8387/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008388ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008389 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008390 // If blocks are disabled, emit an error.
8391 if (!LangOpts.Blocks)
8392 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008393
Douglas Gregor9a28e842010-03-01 23:15:13 +00008394 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008395
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008396 PopDeclContext();
8397
Steve Naroffc540d662008-09-03 18:15:37 +00008398 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008399 if (!BSI->ReturnType.isNull())
8400 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008401
Mike Stump3bf1ab42009-07-28 22:04:01 +00008402 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008403 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008404
John McCallc63de662011-02-02 13:00:07 +00008405 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008406 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8407 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008408
John McCall8e346702010-06-04 19:02:56 +00008409 // If the user wrote a function type in some form, try to use that.
8410 if (!BSI->FunctionType.isNull()) {
8411 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8412
8413 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8414 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8415
8416 // Turn protoless block types into nullary block types.
8417 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008418 FunctionProtoType::ExtProtoInfo EPI;
8419 EPI.ExtInfo = Ext;
8420 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008421
8422 // Otherwise, if we don't need to change anything about the function type,
8423 // preserve its sugar structure.
8424 } else if (FTy->getResultType() == RetTy &&
8425 (!NoReturn || FTy->getNoReturnAttr())) {
8426 BlockTy = BSI->FunctionType;
8427
8428 // Otherwise, make the minimal modifications to the function type.
8429 } else {
8430 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008431 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8432 EPI.TypeQuals = 0; // FIXME: silently?
8433 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008434 BlockTy = Context.getFunctionType(RetTy,
8435 FPT->arg_type_begin(),
8436 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008437 EPI);
John McCall8e346702010-06-04 19:02:56 +00008438 }
8439
8440 // If we don't have a function type, just build one from nothing.
8441 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008442 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008443 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008444 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008445 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008446
John McCall8e346702010-06-04 19:02:56 +00008447 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8448 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008449 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008450
Chris Lattner45542ea2009-04-19 05:28:12 +00008451 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008452 if (getCurFunction()->NeedsScopeChecking() &&
8453 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008454 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008455
Chris Lattner60f84492011-02-17 23:58:47 +00008456 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008457
John McCallc63de662011-02-02 13:00:07 +00008458 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00008459
Ted Kremenek1767a272011-02-23 01:51:48 +00008460 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8461 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008462 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008463}
8464
John McCalldadc5752010-08-24 06:29:42 +00008465ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008466 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008467 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008468 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008469 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008470 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008471}
8472
John McCalldadc5752010-08-24 06:29:42 +00008473ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008474 Expr *E, TypeSourceInfo *TInfo,
8475 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008476 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008477
Eli Friedman121ba0c2008-08-09 23:32:40 +00008478 // Get the va_list type
8479 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008480 if (VaListType->isArrayType()) {
8481 // Deal with implicit array decay; for example, on x86-64,
8482 // va_list is an array, but it's supposed to decay to
8483 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008484 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008485 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008486 ExprResult Result = UsualUnaryConversions(E);
8487 if (Result.isInvalid())
8488 return ExprError();
8489 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008490 } else {
8491 // Otherwise, the va_list argument must be an l-value because
8492 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008493 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008494 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008495 return ExprError();
8496 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008497
Douglas Gregorad3150c2009-05-19 23:10:31 +00008498 if (!E->isTypeDependent() &&
8499 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008500 return ExprError(Diag(E->getLocStart(),
8501 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008502 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008503 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008504
David Majnemerc75d1a12011-06-14 05:17:32 +00008505 if (!TInfo->getType()->isDependentType()) {
8506 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8507 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8508 << TInfo->getTypeLoc().getSourceRange()))
8509 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008510
David Majnemerc75d1a12011-06-14 05:17:32 +00008511 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8512 TInfo->getType(),
8513 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8514 << TInfo->getTypeLoc().getSourceRange()))
8515 return ExprError();
8516
John McCall31168b02011-06-15 23:02:42 +00008517 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00008518 Diag(TInfo->getTypeLoc().getBeginLoc(),
8519 diag::warn_second_parameter_to_va_arg_not_pod)
8520 << TInfo->getType()
8521 << TInfo->getTypeLoc().getSourceRange();
8522 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008523
Abramo Bagnara27db2392010-08-10 10:06:15 +00008524 QualType T = TInfo->getType().getNonLValueExprType(Context);
8525 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008526}
8527
John McCalldadc5752010-08-24 06:29:42 +00008528ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008529 // The type of __null will be int or long, depending on the size of
8530 // pointers on the target.
8531 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008532 unsigned pw = Context.Target.getPointerWidth(0);
8533 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008534 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008535 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008536 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008537 else if (pw == Context.Target.getLongLongWidth())
8538 Ty = Context.LongLongTy;
8539 else {
8540 assert(!"I don't know size of pointer!");
8541 Ty = Context.IntTy;
8542 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008543
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008544 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008545}
8546
Alexis Huntc46382e2010-04-28 23:02:27 +00008547static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008548 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008549 if (!SemaRef.getLangOptions().ObjC1)
8550 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008551
Anders Carlssonace5d072009-11-10 04:46:30 +00008552 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8553 if (!PT)
8554 return;
8555
8556 // Check if the destination is of type 'id'.
8557 if (!PT->isObjCIdType()) {
8558 // Check if the destination is the 'NSString' interface.
8559 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8560 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8561 return;
8562 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008563
Anders Carlssonace5d072009-11-10 04:46:30 +00008564 // Strip off any parens and casts.
8565 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8566 if (!SL || SL->isWide())
8567 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008568
Douglas Gregora771f462010-03-31 17:46:05 +00008569 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008570}
8571
Chris Lattner9bad62c2008-01-04 18:04:52 +00008572bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8573 SourceLocation Loc,
8574 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008575 Expr *SrcExpr, AssignmentAction Action,
8576 bool *Complained) {
8577 if (Complained)
8578 *Complained = false;
8579
Chris Lattner9bad62c2008-01-04 18:04:52 +00008580 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008581 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008582 bool isInvalid = false;
8583 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008584 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008585
Chris Lattner9bad62c2008-01-04 18:04:52 +00008586 switch (ConvTy) {
8587 default: assert(0 && "Unknown conversion type");
8588 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008589 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008590 DiagKind = diag::ext_typecheck_convert_pointer_int;
8591 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008592 case IntToPointer:
8593 DiagKind = diag::ext_typecheck_convert_int_pointer;
8594 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008595 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008596 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008597 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008598 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8599 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +00008600 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008601 case IncompatiblePointerSign:
8602 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8603 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008604 case FunctionVoidPointer:
8605 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8606 break;
John McCall4fff8f62011-02-01 00:10:29 +00008607 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008608 // Perform array-to-pointer decay if necessary.
8609 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8610
John McCall4fff8f62011-02-01 00:10:29 +00008611 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8612 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8613 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8614 DiagKind = diag::err_typecheck_incompatible_address_space;
8615 break;
John McCall31168b02011-06-15 23:02:42 +00008616
8617
8618 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008619 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008620 break;
John McCall4fff8f62011-02-01 00:10:29 +00008621 }
8622
8623 llvm_unreachable("unknown error case for discarding qualifiers!");
8624 // fallthrough
8625 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008626 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008627 // If the qualifiers lost were because we were applying the
8628 // (deprecated) C++ conversion from a string literal to a char*
8629 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8630 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008631 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008632 // bit of refactoring (so that the second argument is an
8633 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008634 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008635 // C++ semantics.
8636 if (getLangOptions().CPlusPlus &&
8637 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8638 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008639 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8640 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008641 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008642 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008643 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008644 case IntToBlockPointer:
8645 DiagKind = diag::err_int_to_block_pointer;
8646 break;
8647 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008648 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008649 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008650 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008651 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008652 // it can give a more specific diagnostic.
8653 DiagKind = diag::warn_incompatible_qualified_id;
8654 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008655 case IncompatibleVectors:
8656 DiagKind = diag::warn_incompatible_vectors;
8657 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008658 case Incompatible:
8659 DiagKind = diag::err_typecheck_convert_incompatible;
8660 isInvalid = true;
8661 break;
8662 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008663
Douglas Gregorc68e1402010-04-09 00:35:39 +00008664 QualType FirstType, SecondType;
8665 switch (Action) {
8666 case AA_Assigning:
8667 case AA_Initializing:
8668 // The destination type comes first.
8669 FirstType = DstType;
8670 SecondType = SrcType;
8671 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008672
Douglas Gregorc68e1402010-04-09 00:35:39 +00008673 case AA_Returning:
8674 case AA_Passing:
8675 case AA_Converting:
8676 case AA_Sending:
8677 case AA_Casting:
8678 // The source type comes first.
8679 FirstType = SrcType;
8680 SecondType = DstType;
8681 break;
8682 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008683
Douglas Gregorc68e1402010-04-09 00:35:39 +00008684 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008685 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +00008686 if (CheckInferredResultType)
8687 EmitRelatedResultTypeNote(SrcExpr);
8688
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008689 if (Complained)
8690 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008691 return isInvalid;
8692}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008693
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008694bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008695 llvm::APSInt ICEResult;
8696 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8697 if (Result)
8698 *Result = ICEResult;
8699 return false;
8700 }
8701
Anders Carlssone54e8a12008-11-30 19:50:32 +00008702 Expr::EvalResult EvalResult;
8703
Mike Stump4e1f26a2009-02-19 03:04:26 +00008704 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008705 EvalResult.HasSideEffects) {
8706 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8707
8708 if (EvalResult.Diag) {
8709 // We only show the note if it's not the usual "invalid subexpression"
8710 // or if it's actually in a subexpression.
8711 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8712 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8713 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8714 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008715
Anders Carlssone54e8a12008-11-30 19:50:32 +00008716 return true;
8717 }
8718
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008719 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8720 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008721
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008722 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008723 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8724 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008725 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008726
Anders Carlssone54e8a12008-11-30 19:50:32 +00008727 if (Result)
8728 *Result = EvalResult.Val.getInt();
8729 return false;
8730}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008731
Douglas Gregorff790f12009-11-26 00:44:06 +00008732void
Mike Stump11289f42009-09-09 15:08:12 +00008733Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008734 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008735 ExpressionEvaluationContextRecord(NewContext,
8736 ExprTemporaries.size(),
8737 ExprNeedsCleanups));
8738 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008739}
8740
Mike Stump11289f42009-09-09 15:08:12 +00008741void
Douglas Gregorff790f12009-11-26 00:44:06 +00008742Sema::PopExpressionEvaluationContext() {
8743 // Pop the current expression evaluation context off the stack.
8744 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8745 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008746
Douglas Gregorfab31f42009-12-12 07:57:52 +00008747 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8748 if (Rec.PotentiallyReferenced) {
8749 // Mark any remaining declarations in the current position of the stack
8750 // as "referenced". If they were not meant to be referenced, semantic
8751 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008752 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008753 I = Rec.PotentiallyReferenced->begin(),
8754 IEnd = Rec.PotentiallyReferenced->end();
8755 I != IEnd; ++I)
8756 MarkDeclarationReferenced(I->first, I->second);
8757 }
8758
8759 if (Rec.PotentiallyDiagnosed) {
8760 // Emit any pending diagnostics.
8761 for (PotentiallyEmittedDiagnostics::iterator
8762 I = Rec.PotentiallyDiagnosed->begin(),
8763 IEnd = Rec.PotentiallyDiagnosed->end();
8764 I != IEnd; ++I)
8765 Diag(I->first, I->second);
8766 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008767 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008768
8769 // When are coming out of an unevaluated context, clear out any
8770 // temporaries that we may have created as part of the evaluation of
8771 // the expression in that context: they aren't relevant because they
8772 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008773 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008774 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8775 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008776 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8777
8778 // Otherwise, merge the contexts together.
8779 } else {
8780 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8781 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008782
8783 // Destroy the popped expression evaluation record.
8784 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008785}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008786
John McCall31168b02011-06-15 23:02:42 +00008787void Sema::DiscardCleanupsInEvaluationContext() {
8788 ExprTemporaries.erase(
8789 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8790 ExprTemporaries.end());
8791 ExprNeedsCleanups = false;
8792}
8793
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008794/// \brief Note that the given declaration was referenced in the source code.
8795///
8796/// This routine should be invoke whenever a given declaration is referenced
8797/// in the source code, and where that reference occurred. If this declaration
8798/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8799/// C99 6.9p3), then the declaration will be marked as used.
8800///
8801/// \param Loc the location where the declaration was referenced.
8802///
8803/// \param D the declaration that has been referenced by the source code.
8804void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8805 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008806
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008807 D->setReferenced();
8808
Douglas Gregorebada0772010-06-17 23:14:26 +00008809 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008810 return;
Mike Stump11289f42009-09-09 15:08:12 +00008811
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008812 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8813 // template or not. The reason for this is that unevaluated expressions
8814 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8815 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008816 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008817 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008818 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008819 return;
8820 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008821
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008822 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8823 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008824
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008825 // Do not mark anything as "used" within a dependent context; wait for
8826 // an instantiation.
8827 if (CurContext->isDependentContext())
8828 return;
Mike Stump11289f42009-09-09 15:08:12 +00008829
Douglas Gregorff790f12009-11-26 00:44:06 +00008830 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008831 case Unevaluated:
8832 // We are in an expression that is not potentially evaluated; do nothing.
8833 return;
Mike Stump11289f42009-09-09 15:08:12 +00008834
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008835 case PotentiallyEvaluated:
8836 // We are in a potentially-evaluated expression, so this declaration is
8837 // "used"; handle this below.
8838 break;
Mike Stump11289f42009-09-09 15:08:12 +00008839
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008840 case PotentiallyPotentiallyEvaluated:
8841 // We are in an expression that may be potentially evaluated; queue this
8842 // declaration reference until we know whether the expression is
8843 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008844 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008845 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008846
8847 case PotentiallyEvaluatedIfUsed:
8848 // Referenced declarations will only be used if the construct in the
8849 // containing expression is used.
8850 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008851 }
Mike Stump11289f42009-09-09 15:08:12 +00008852
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008853 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008855 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8856 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008857 return;
8858 if (!Constructor->isUsed(false))
8859 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008860 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008861 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008862 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00008863 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008864 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008865
Douglas Gregor88d292c2010-05-13 16:44:06 +00008866 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008867 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00008868 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008869 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008870 if (Destructor->isVirtual())
8871 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008872 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00008873 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008874 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008875 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008876 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008877 } else if (MethodDecl->isVirtual())
8878 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008879 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008880 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00008881 // Recursive functions should be marked when used from another function.
8882 if (CurContext == Function) return;
8883
Mike Stump11289f42009-09-09 15:08:12 +00008884 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008885 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008886 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008887 bool AlreadyInstantiated = false;
8888 if (FunctionTemplateSpecializationInfo *SpecInfo
8889 = Function->getTemplateSpecializationInfo()) {
8890 if (SpecInfo->getPointOfInstantiation().isInvalid())
8891 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008892 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008893 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008894 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008895 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008896 = Function->getMemberSpecializationInfo()) {
8897 if (MSInfo->getPointOfInstantiation().isInvalid())
8898 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008899 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008900 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008901 AlreadyInstantiated = true;
8902 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008903
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008904 if (!AlreadyInstantiated) {
8905 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8906 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8907 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8908 Loc));
8909 else
Chandler Carruth54080172010-08-25 08:44:16 +00008910 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008911 }
John McCall83779672011-02-19 02:53:41 +00008912 } else {
8913 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008914 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8915 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008916 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008917 MarkDeclarationReferenced(Loc, *i);
8918 }
John McCall83779672011-02-19 02:53:41 +00008919 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008920
John McCall83779672011-02-19 02:53:41 +00008921 // Keep track of used but undefined functions.
8922 if (!Function->isPure() && !Function->hasBody() &&
8923 Function->getLinkage() != ExternalLinkage) {
8924 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
8925 if (old.isInvalid()) old = Loc;
8926 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008927
John McCall83779672011-02-19 02:53:41 +00008928 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008929 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008930 }
Mike Stump11289f42009-09-09 15:08:12 +00008931
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008932 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008933 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008934 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008935 Var->getInstantiatedFromStaticDataMember()) {
8936 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8937 assert(MSInfo && "Missing member specialization information?");
8938 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8939 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8940 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00008941 // This is a modification of an existing AST node. Notify listeners.
8942 if (ASTMutationListener *L = getASTMutationListener())
8943 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00008944 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008945 }
8946 }
Mike Stump11289f42009-09-09 15:08:12 +00008947
John McCall15dd4042011-02-21 19:25:48 +00008948 // Keep track of used but undefined variables. We make a hole in
8949 // the warning for static const data members with in-line
8950 // initializers.
John McCall83779672011-02-19 02:53:41 +00008951 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00008952 && Var->getLinkage() != ExternalLinkage
8953 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00008954 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
8955 if (old.isInvalid()) old = Loc;
8956 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008957
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008958 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008959 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008960 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008961}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008962
Douglas Gregor5597ab42010-05-07 23:12:07 +00008963namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008964 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008965 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008966 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008967 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8968 Sema &S;
8969 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008970
Douglas Gregor5597ab42010-05-07 23:12:07 +00008971 public:
8972 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008973
Douglas Gregor5597ab42010-05-07 23:12:07 +00008974 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008975
8976 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8977 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008978 };
8979}
8980
Chandler Carruthaf80f662010-06-09 08:17:30 +00008981bool MarkReferencedDecls::TraverseTemplateArgument(
8982 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008983 if (Arg.getKind() == TemplateArgument::Declaration) {
8984 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8985 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008986
8987 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008988}
8989
Chandler Carruthaf80f662010-06-09 08:17:30 +00008990bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008991 if (ClassTemplateSpecializationDecl *Spec
8992 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8993 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008994 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008995 }
8996
Chandler Carruthc65667c2010-06-10 10:31:57 +00008997 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008998}
8999
9000void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9001 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009002 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009003}
9004
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009005namespace {
9006 /// \brief Helper class that marks all of the declarations referenced by
9007 /// potentially-evaluated subexpressions as "referenced".
9008 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9009 Sema &S;
9010
9011 public:
9012 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9013
9014 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9015
9016 void VisitDeclRefExpr(DeclRefExpr *E) {
9017 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9018 }
9019
9020 void VisitMemberExpr(MemberExpr *E) {
9021 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009022 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009023 }
9024
9025 void VisitCXXNewExpr(CXXNewExpr *E) {
9026 if (E->getConstructor())
9027 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9028 if (E->getOperatorNew())
9029 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9030 if (E->getOperatorDelete())
9031 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009032 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009033 }
9034
9035 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9036 if (E->getOperatorDelete())
9037 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009038 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9039 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9040 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9041 S.MarkDeclarationReferenced(E->getLocStart(),
9042 S.LookupDestructor(Record));
9043 }
9044
Douglas Gregor32b3de52010-09-11 23:32:50 +00009045 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009046 }
9047
9048 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9049 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009050 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009051 }
9052
9053 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9054 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9055 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009056
9057 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9058 Visit(E->getExpr());
9059 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009060 };
9061}
9062
9063/// \brief Mark any declarations that appear within this expression or any
9064/// potentially-evaluated subexpressions as "referenced".
9065void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9066 EvaluatedExprMarker(*this).Visit(E);
9067}
9068
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009069/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9070/// of the program being compiled.
9071///
9072/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009073/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009074/// possibility that the code will actually be executable. Code in sizeof()
9075/// expressions, code used only during overload resolution, etc., are not
9076/// potentially evaluated. This routine will suppress such diagnostics or,
9077/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009078/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009079/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009080///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009081/// This routine should be used for all diagnostics that describe the run-time
9082/// behavior of a program, such as passing a non-POD value through an ellipsis.
9083/// Failure to do so will likely result in spurious diagnostics or failures
9084/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009085bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009086 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009087 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009088 case Unevaluated:
9089 // The argument will never be evaluated, so don't complain.
9090 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009091
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009092 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009093 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009094 if (stmt && getCurFunctionOrMethodDecl()) {
9095 FunctionScopes.back()->PossiblyUnreachableDiags.
9096 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9097 }
9098 else
9099 Diag(Loc, PD);
9100
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009101 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009102
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009103 case PotentiallyPotentiallyEvaluated:
9104 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9105 break;
9106 }
9107
9108 return false;
9109}
9110
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009111bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9112 CallExpr *CE, FunctionDecl *FD) {
9113 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9114 return false;
9115
9116 PartialDiagnostic Note =
9117 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9118 << FD->getDeclName() : PDiag();
9119 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009120
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009121 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009122 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009123 PDiag(diag::err_call_function_incomplete_return)
9124 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009125 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009126 << CE->getSourceRange(),
9127 std::make_pair(NoteLoc, Note)))
9128 return true;
9129
9130 return false;
9131}
9132
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009133// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009134// will prevent this condition from triggering, which is what we want.
9135void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9136 SourceLocation Loc;
9137
John McCall0506e4a2009-11-11 02:41:58 +00009138 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009139 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009140
John McCalld5707ab2009-10-12 21:59:07 +00009141 if (isa<BinaryOperator>(E)) {
9142 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009143 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009144 return;
9145
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009146 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9147
John McCallb0e419e2009-11-12 00:06:05 +00009148 // Greylist some idioms by putting them into a warning subcategory.
9149 if (ObjCMessageExpr *ME
9150 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9151 Selector Sel = ME->getSelector();
9152
John McCallb0e419e2009-11-12 00:06:05 +00009153 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009154 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009155 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9156
9157 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009158 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009159 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9160 }
John McCall0506e4a2009-11-11 02:41:58 +00009161
John McCalld5707ab2009-10-12 21:59:07 +00009162 Loc = Op->getOperatorLoc();
9163 } else if (isa<CXXOperatorCallExpr>(E)) {
9164 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009165 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009166 return;
9167
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009168 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009169 Loc = Op->getOperatorLoc();
9170 } else {
9171 // Not an assignment.
9172 return;
9173 }
9174
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009175 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009176
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009177 SourceLocation Open = E->getSourceRange().getBegin();
9178 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9179 Diag(Loc, diag::note_condition_assign_silence)
9180 << FixItHint::CreateInsertion(Open, "(")
9181 << FixItHint::CreateInsertion(Close, ")");
9182
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009183 if (IsOrAssign)
9184 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9185 << FixItHint::CreateReplacement(Loc, "!=");
9186 else
9187 Diag(Loc, diag::note_condition_assign_to_comparison)
9188 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009189}
9190
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009191/// \brief Redundant parentheses over an equality comparison can indicate
9192/// that the user intended an assignment used as condition.
9193void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009194 // Don't warn if the parens came from a macro.
9195 SourceLocation parenLoc = parenE->getLocStart();
9196 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9197 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009198 // Don't warn for dependent expressions.
9199 if (parenE->isTypeDependent())
9200 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009201
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009202 Expr *E = parenE->IgnoreParens();
9203
9204 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009205 if (opE->getOpcode() == BO_EQ &&
9206 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9207 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009208 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009209
Ted Kremenekae022092011-02-02 02:20:30 +00009210 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009211 Diag(Loc, diag::note_equality_comparison_silence)
9212 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9213 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009214 Diag(Loc, diag::note_equality_comparison_to_assign)
9215 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009216 }
9217}
9218
John Wiegley01296292011-04-08 18:41:53 +00009219ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009220 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009221 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9222 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009223
John McCall0009fcc2011-04-26 20:42:42 +00009224 ExprResult result = CheckPlaceholderExpr(E);
9225 if (result.isInvalid()) return ExprError();
9226 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009227
John McCall0009fcc2011-04-26 20:42:42 +00009228 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009229 if (getLangOptions().CPlusPlus)
9230 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9231
John Wiegley01296292011-04-08 18:41:53 +00009232 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9233 if (ERes.isInvalid())
9234 return ExprError();
9235 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009236
9237 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009238 if (!T->isScalarType()) { // C99 6.8.4.1p1
9239 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9240 << T << E->getSourceRange();
9241 return ExprError();
9242 }
John McCalld5707ab2009-10-12 21:59:07 +00009243 }
9244
John Wiegley01296292011-04-08 18:41:53 +00009245 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009246}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009247
John McCalldadc5752010-08-24 06:29:42 +00009248ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9249 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009250 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009251 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009252
9253 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009254}
John McCall36e7fe32010-10-12 00:20:44 +00009255
John McCall31996342011-04-07 08:22:57 +00009256namespace {
John McCall2979fe02011-04-12 00:42:48 +00009257 /// A visitor for rebuilding a call to an __unknown_any expression
9258 /// to have an appropriate type.
9259 struct RebuildUnknownAnyFunction
9260 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9261
9262 Sema &S;
9263
9264 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9265
9266 ExprResult VisitStmt(Stmt *S) {
9267 llvm_unreachable("unexpected statement!");
9268 return ExprError();
9269 }
9270
9271 ExprResult VisitExpr(Expr *expr) {
9272 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9273 << expr->getSourceRange();
9274 return ExprError();
9275 }
9276
9277 /// Rebuild an expression which simply semantically wraps another
9278 /// expression which it shares the type and value kind of.
9279 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9280 ExprResult subResult = Visit(expr->getSubExpr());
9281 if (subResult.isInvalid()) return ExprError();
9282
9283 Expr *subExpr = subResult.take();
9284 expr->setSubExpr(subExpr);
9285 expr->setType(subExpr->getType());
9286 expr->setValueKind(subExpr->getValueKind());
9287 assert(expr->getObjectKind() == OK_Ordinary);
9288 return expr;
9289 }
9290
9291 ExprResult VisitParenExpr(ParenExpr *paren) {
9292 return rebuildSugarExpr(paren);
9293 }
9294
9295 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9296 return rebuildSugarExpr(op);
9297 }
9298
9299 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9300 ExprResult subResult = Visit(op->getSubExpr());
9301 if (subResult.isInvalid()) return ExprError();
9302
9303 Expr *subExpr = subResult.take();
9304 op->setSubExpr(subExpr);
9305 op->setType(S.Context.getPointerType(subExpr->getType()));
9306 assert(op->getValueKind() == VK_RValue);
9307 assert(op->getObjectKind() == OK_Ordinary);
9308 return op;
9309 }
9310
9311 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9312 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9313
9314 expr->setType(decl->getType());
9315
9316 assert(expr->getValueKind() == VK_RValue);
9317 if (S.getLangOptions().CPlusPlus &&
9318 !(isa<CXXMethodDecl>(decl) &&
9319 cast<CXXMethodDecl>(decl)->isInstance()))
9320 expr->setValueKind(VK_LValue);
9321
9322 return expr;
9323 }
9324
9325 ExprResult VisitMemberExpr(MemberExpr *mem) {
9326 return resolveDecl(mem, mem->getMemberDecl());
9327 }
9328
9329 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9330 return resolveDecl(ref, ref->getDecl());
9331 }
9332 };
9333}
9334
9335/// Given a function expression of unknown-any type, try to rebuild it
9336/// to have a function type.
9337static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9338 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9339 if (result.isInvalid()) return ExprError();
9340 return S.DefaultFunctionArrayConversion(result.take());
9341}
9342
9343namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009344 /// A visitor for rebuilding an expression of type __unknown_anytype
9345 /// into one which resolves the type directly on the referring
9346 /// expression. Strict preservation of the original source
9347 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009348 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009349 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009350
9351 Sema &S;
9352
9353 /// The current destination type.
9354 QualType DestType;
9355
9356 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9357 : S(S), DestType(castType) {}
9358
John McCall39439732011-04-09 22:50:59 +00009359 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009360 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009361 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009362 }
9363
John McCall2d2e8702011-04-11 07:02:50 +00009364 ExprResult VisitExpr(Expr *expr) {
9365 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9366 << expr->getSourceRange();
9367 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009368 }
9369
John McCall2d2e8702011-04-11 07:02:50 +00009370 ExprResult VisitCallExpr(CallExpr *call);
9371 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9372
John McCall39439732011-04-09 22:50:59 +00009373 /// Rebuild an expression which simply semantically wraps another
9374 /// expression which it shares the type and value kind of.
9375 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9376 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009377 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009378 Expr *subExpr = subResult.take();
9379 expr->setSubExpr(subExpr);
9380 expr->setType(subExpr->getType());
9381 expr->setValueKind(subExpr->getValueKind());
9382 assert(expr->getObjectKind() == OK_Ordinary);
9383 return expr;
9384 }
John McCall31996342011-04-07 08:22:57 +00009385
John McCall39439732011-04-09 22:50:59 +00009386 ExprResult VisitParenExpr(ParenExpr *paren) {
9387 return rebuildSugarExpr(paren);
9388 }
9389
9390 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9391 return rebuildSugarExpr(op);
9392 }
9393
John McCall2979fe02011-04-12 00:42:48 +00009394 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9395 const PointerType *ptr = DestType->getAs<PointerType>();
9396 if (!ptr) {
9397 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9398 << op->getSourceRange();
9399 return ExprError();
9400 }
9401 assert(op->getValueKind() == VK_RValue);
9402 assert(op->getObjectKind() == OK_Ordinary);
9403 op->setType(DestType);
9404
9405 // Build the sub-expression as if it were an object of the pointee type.
9406 DestType = ptr->getPointeeType();
9407 ExprResult subResult = Visit(op->getSubExpr());
9408 if (subResult.isInvalid()) return ExprError();
9409 op->setSubExpr(subResult.take());
9410 return op;
9411 }
9412
John McCall2d2e8702011-04-11 07:02:50 +00009413 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009414
John McCall2979fe02011-04-12 00:42:48 +00009415 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009416
John McCall2979fe02011-04-12 00:42:48 +00009417 ExprResult VisitMemberExpr(MemberExpr *mem) {
9418 return resolveDecl(mem, mem->getMemberDecl());
9419 }
John McCall39439732011-04-09 22:50:59 +00009420
9421 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009422 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009423 }
9424 };
9425}
9426
John McCall2d2e8702011-04-11 07:02:50 +00009427/// Rebuilds a call expression which yielded __unknown_anytype.
9428ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9429 Expr *callee = call->getCallee();
9430
9431 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009432 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009433 FK_FunctionPointer,
9434 FK_BlockPointer
9435 };
9436
9437 FnKind kind;
9438 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009439 if (type == S.Context.BoundMemberTy) {
9440 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9441 kind = FK_MemberFunction;
9442 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009443 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9444 type = ptr->getPointeeType();
9445 kind = FK_FunctionPointer;
9446 } else {
9447 type = type->castAs<BlockPointerType>()->getPointeeType();
9448 kind = FK_BlockPointer;
9449 }
9450 const FunctionType *fnType = type->castAs<FunctionType>();
9451
9452 // Verify that this is a legal result type of a function.
9453 if (DestType->isArrayType() || DestType->isFunctionType()) {
9454 unsigned diagID = diag::err_func_returning_array_function;
9455 if (kind == FK_BlockPointer)
9456 diagID = diag::err_block_returning_array_function;
9457
9458 S.Diag(call->getExprLoc(), diagID)
9459 << DestType->isFunctionType() << DestType;
9460 return ExprError();
9461 }
9462
9463 // Otherwise, go ahead and set DestType as the call's result.
9464 call->setType(DestType.getNonLValueExprType(S.Context));
9465 call->setValueKind(Expr::getValueKindForType(DestType));
9466 assert(call->getObjectKind() == OK_Ordinary);
9467
9468 // Rebuild the function type, replacing the result type with DestType.
9469 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9470 DestType = S.Context.getFunctionType(DestType,
9471 proto->arg_type_begin(),
9472 proto->getNumArgs(),
9473 proto->getExtProtoInfo());
9474 else
9475 DestType = S.Context.getFunctionNoProtoType(DestType,
9476 fnType->getExtInfo());
9477
9478 // Rebuild the appropriate pointer-to-function type.
9479 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009480 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009481 // Nothing to do.
9482 break;
9483
9484 case FK_FunctionPointer:
9485 DestType = S.Context.getPointerType(DestType);
9486 break;
9487
9488 case FK_BlockPointer:
9489 DestType = S.Context.getBlockPointerType(DestType);
9490 break;
9491 }
9492
9493 // Finally, we can recurse.
9494 ExprResult calleeResult = Visit(callee);
9495 if (!calleeResult.isUsable()) return ExprError();
9496 call->setCallee(calleeResult.take());
9497
9498 // Bind a temporary if necessary.
9499 return S.MaybeBindToTemporary(call);
9500}
9501
9502ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009503 ObjCMethodDecl *method = msg->getMethodDecl();
9504 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +00009505
John McCall2979fe02011-04-12 00:42:48 +00009506 // Verify that this is a legal result type of a call.
9507 if (DestType->isArrayType() || DestType->isFunctionType()) {
9508 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9509 << DestType->isFunctionType() << DestType;
9510 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009511 }
9512
John McCall2979fe02011-04-12 00:42:48 +00009513 assert(method->getResultType() == S.Context.UnknownAnyTy);
9514 method->setResultType(DestType);
9515
John McCall2d2e8702011-04-11 07:02:50 +00009516 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009517 msg->setType(DestType.getNonReferenceType());
9518 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009519
John McCall2979fe02011-04-12 00:42:48 +00009520 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009521}
9522
9523ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009524 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009525 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009526 assert(ice->getValueKind() == VK_RValue);
9527 assert(ice->getObjectKind() == OK_Ordinary);
9528
John McCall2979fe02011-04-12 00:42:48 +00009529 ice->setType(DestType);
9530
John McCall2d2e8702011-04-11 07:02:50 +00009531 // Rebuild the sub-expression as the pointee (function) type.
9532 DestType = DestType->castAs<PointerType>()->getPointeeType();
9533
9534 ExprResult result = Visit(ice->getSubExpr());
9535 if (!result.isUsable()) return ExprError();
9536
9537 ice->setSubExpr(result.take());
9538 return S.Owned(ice);
9539}
9540
John McCall2979fe02011-04-12 00:42:48 +00009541ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009542 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009543 QualType type = DestType;
9544
9545 // We know how to make this work for certain kinds of decls:
9546
9547 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009548 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009549 // This is true because FunctionDecls must always have function
9550 // type, so we can't be resolving the entire thing at once.
9551 assert(type->isFunctionType());
9552
John McCall4adb38c2011-04-27 00:36:17 +00009553 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9554 if (method->isInstance()) {
9555 valueKind = VK_RValue;
9556 type = S.Context.BoundMemberTy;
9557 }
9558
John McCall2d2e8702011-04-11 07:02:50 +00009559 // Function references aren't l-values in C.
9560 if (!S.getLangOptions().CPlusPlus)
9561 valueKind = VK_RValue;
9562
9563 // - variables
9564 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009565 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9566 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009567 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009568 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9569 << decl << expr->getSourceRange();
9570 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009571 }
9572
9573 // - nothing else
9574 } else {
9575 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9576 << decl << expr->getSourceRange();
9577 return ExprError();
9578 }
9579
John McCall2979fe02011-04-12 00:42:48 +00009580 decl->setType(DestType);
9581 expr->setType(type);
9582 expr->setValueKind(valueKind);
9583 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009584}
9585
John McCall31996342011-04-07 08:22:57 +00009586/// Check a cast of an unknown-any type. We intentionally only
9587/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009588ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9589 Expr *castExpr, CastKind &castKind,
9590 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009591 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009592 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9593 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009594
John McCall39439732011-04-09 22:50:59 +00009595 castExpr = result.take();
9596 VK = castExpr->getValueKind();
9597 castKind = CK_NoOp;
9598
9599 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009600}
9601
9602static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9603 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009604 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009605 while (true) {
9606 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009607 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009608 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009609 diagID = diag::err_uncasted_call_of_unknown_any;
9610 } else {
John McCall31996342011-04-07 08:22:57 +00009611 break;
John McCall2d2e8702011-04-11 07:02:50 +00009612 }
John McCall31996342011-04-07 08:22:57 +00009613 }
9614
John McCall2d2e8702011-04-11 07:02:50 +00009615 SourceLocation loc;
9616 NamedDecl *d;
9617 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9618 loc = ref->getLocation();
9619 d = ref->getDecl();
9620 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9621 loc = mem->getMemberLoc();
9622 d = mem->getMemberDecl();
9623 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9624 diagID = diag::err_uncasted_call_of_unknown_any;
9625 loc = msg->getSelectorLoc();
9626 d = msg->getMethodDecl();
9627 assert(d && "unknown method returning __unknown_any?");
9628 } else {
9629 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9630 << e->getSourceRange();
9631 return ExprError();
9632 }
9633
9634 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009635
9636 // Never recoverable.
9637 return ExprError();
9638}
9639
John McCall36e7fe32010-10-12 00:20:44 +00009640/// Check for operands with placeholder types and complain if found.
9641/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009642ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009643 // Placeholder types are always *exactly* the appropriate builtin type.
9644 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009645
John McCall31996342011-04-07 08:22:57 +00009646 // Overloaded expressions.
9647 if (type == Context.OverloadTy)
9648 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009649 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009650 QualType(),
9651 diag::err_ovl_unresolvable);
9652
John McCall0009fcc2011-04-26 20:42:42 +00009653 // Bound member functions.
9654 if (type == Context.BoundMemberTy) {
9655 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9656 << E->getSourceRange();
9657 return ExprError();
9658 }
9659
John McCall31996342011-04-07 08:22:57 +00009660 // Expressions of unknown type.
9661 if (type == Context.UnknownAnyTy)
9662 return diagnoseUnknownAnyExpr(*this, E);
9663
9664 assert(!type->isPlaceholderType());
9665 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009666}
Richard Trieu2c850c02011-04-21 21:44:26 +00009667
9668bool Sema::CheckCaseExpression(Expr *expr) {
9669 if (expr->isTypeDependent())
9670 return true;
9671 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9672 return expr->getType()->isIntegralOrEnumerationType();
9673 return false;
9674}