blob: 5efc36559d977030e88bc05818b3aa1a4c2feab6 [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
Hans Wennborg38198de2011-07-12 08:45:31 +00001407 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001408 R.addDecl(ND);
1409 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001410 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001411 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1412 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001413 else
1414 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001415 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001416 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001417 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1418 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001419 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001420 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001421
1422 // Tell the callee to try to recover.
1423 return false;
1424 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001425
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001426 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001427 // FIXME: If we ended up with a typo for a type name or
1428 // Objective-C class name, we're in trouble because the parser
1429 // is in the wrong place to recover. Suggest the typo
1430 // correction, but don't make it a fix-it since we're not going
1431 // to recover well anyway.
1432 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001433 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001434 else
1435 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001436 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001437 << SS.getRange();
1438
1439 // Don't try to recover; it won't work.
1440 return true;
1441 }
1442 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001443 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001444 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001445 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001446 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001447 else
Douglas Gregor25363982010-01-01 00:15:04 +00001448 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001449 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001450 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001451 return true;
1452 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001453 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001454 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001455
1456 // Emit a special diagnostic for failed member lookups.
1457 // FIXME: computing the declaration context might fail here (?)
1458 if (!SS.isEmpty()) {
1459 Diag(R.getNameLoc(), diag::err_no_member)
1460 << Name << computeDeclContext(SS, false)
1461 << SS.getRange();
1462 return true;
1463 }
1464
John McCalld681c392009-12-16 08:11:27 +00001465 // Give up, we can't recover.
1466 Diag(R.getNameLoc(), diagnostic) << Name;
1467 return true;
1468}
1469
Douglas Gregor05fcf842010-11-02 20:36:02 +00001470ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1471 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001472 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1473 if (!IDecl)
1474 return 0;
1475 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1476 if (!ClassImpDecl)
1477 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001478 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001479 if (!property)
1480 return 0;
1481 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001482 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1483 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001484 return 0;
1485 return property;
1486}
1487
Douglas Gregor05fcf842010-11-02 20:36:02 +00001488bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1489 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1490 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1491 if (!IDecl)
1492 return false;
1493 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1494 if (!ClassImpDecl)
1495 return false;
1496 if (ObjCPropertyImplDecl *PIDecl
1497 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1498 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1499 PIDecl->getPropertyIvarDecl())
1500 return false;
1501
1502 return true;
1503}
1504
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001505ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1506 IdentifierInfo *II,
1507 SourceLocation NameLoc) {
1508 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001509 bool LookForIvars;
1510 if (Lookup.empty())
1511 LookForIvars = true;
1512 else if (CurMeth->isClassMethod())
1513 LookForIvars = false;
1514 else
1515 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001516 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1517 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001518 if (!LookForIvars)
1519 return 0;
1520
Fariborz Jahanian18722982010-07-17 00:59:30 +00001521 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1522 if (!IDecl)
1523 return 0;
1524 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001525 if (!ClassImpDecl)
1526 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001527 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001528 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001529 if (!property)
1530 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001531 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001532 DynamicImplSeen =
1533 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001534 // property implementation has a designated ivar. No need to assume a new
1535 // one.
1536 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1537 return 0;
1538 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001539 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001540 QualType PropType = Context.getCanonicalType(property->getType());
1541 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001542 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001543 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001544 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001545 (Expr *)0, true);
1546 ClassImpDecl->addDecl(Ivar);
1547 IDecl->makeDeclVisibleInContext(Ivar, false);
1548 property->setPropertyIvarDecl(Ivar);
1549 return Ivar;
1550 }
1551 return 0;
1552}
1553
John McCalldadc5752010-08-24 06:29:42 +00001554ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001555 CXXScopeSpec &SS,
1556 UnqualifiedId &Id,
1557 bool HasTrailingLParen,
1558 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001559 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1560 "cannot be direct & operand and have a trailing lparen");
1561
1562 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001563 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001564
John McCall10eae182009-11-30 22:42:35 +00001565 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001566
1567 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001568 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001569 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001570 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001571
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001572 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001573 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001574 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001575
John McCalle66edc12009-11-24 19:00:30 +00001576 // C++ [temp.dep.expr]p3:
1577 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001578 // -- an identifier that was declared with a dependent type,
1579 // (note: handled after lookup)
1580 // -- a template-id that is dependent,
1581 // (note: handled in BuildTemplateIdExpr)
1582 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001583 // -- a nested-name-specifier that contains a class-name that
1584 // names a dependent type.
1585 // Determine whether this is a member of an unknown specialization;
1586 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001587 bool DependentID = false;
1588 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1589 Name.getCXXNameType()->isDependentType()) {
1590 DependentID = true;
1591 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001592 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001593 if (RequireCompleteDeclContext(SS, DC))
1594 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001595 } else {
1596 DependentID = true;
1597 }
1598 }
1599
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001600 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001601 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001602 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001603
Fariborz Jahanian86151342010-07-22 23:33:21 +00001604 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001605 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001606 LookupResult R(*this, NameInfo,
1607 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1608 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001609 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001610 // Lookup the template name again to correctly establish the context in
1611 // which it was found. This is really unfortunate as we already did the
1612 // lookup to determine that it was a template name in the first place. If
1613 // this becomes a performance hit, we can work harder to preserve those
1614 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001615 bool MemberOfUnknownSpecialization;
1616 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1617 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001618
1619 if (MemberOfUnknownSpecialization ||
1620 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1621 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1622 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001623 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001624 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001625 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001626
Douglas Gregora5226932011-02-04 13:35:07 +00001627 // If the result might be in a dependent base class, this is a dependent
1628 // id-expression.
1629 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1630 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1631 TemplateArgs);
1632
John McCalle66edc12009-11-24 19:00:30 +00001633 // If this reference is in an Objective-C method, then we need to do
1634 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001635 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001636 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001637 if (E.isInvalid())
1638 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001639
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001640 if (Expr *Ex = E.takeAs<Expr>())
1641 return Owned(Ex);
1642
1643 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001644 if (getLangOptions().ObjCDefaultSynthProperties &&
1645 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001646 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001647 if (const ObjCPropertyDecl *Property =
1648 canSynthesizeProvisionalIvar(II)) {
1649 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1650 Diag(Property->getLocation(), diag::note_property_declare);
1651 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001652 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1653 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001654 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001655 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001656 // for further use, this must be set to false if in class method.
1657 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001658 }
Chris Lattner59a25942008-03-31 00:36:02 +00001659 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001660
John McCalle66edc12009-11-24 19:00:30 +00001661 if (R.isAmbiguous())
1662 return ExprError();
1663
Douglas Gregor171c45a2009-02-18 21:56:37 +00001664 // Determine whether this name might be a candidate for
1665 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001666 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001667
John McCalle66edc12009-11-24 19:00:30 +00001668 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001669 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001670 // in C90, extension in C99, forbidden in C++).
1671 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1672 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1673 if (D) R.addDecl(D);
1674 }
1675
1676 // If this name wasn't predeclared and if this is not a function
1677 // call, diagnose the problem.
1678 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001679 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001680 return ExprError();
1681
1682 assert(!R.empty() &&
1683 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001684
1685 // If we found an Objective-C instance variable, let
1686 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001687 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001688 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1689 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001690 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001691 assert(E.isInvalid() || E.get());
1692 return move(E);
1693 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001694 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001695 }
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCalle66edc12009-11-24 19:00:30 +00001697 // This is guaranteed from this point on.
1698 assert(!R.empty() || ADL);
1699
John McCall2d74de92009-12-01 22:10:20 +00001700 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001701 // C++ [class.mfct.non-static]p3:
1702 // When an id-expression that is not part of a class member access
1703 // syntax and not used to form a pointer to member is used in the
1704 // body of a non-static member function of class X, if name lookup
1705 // resolves the name in the id-expression to a non-static non-type
1706 // member of some class C, the id-expression is transformed into a
1707 // class member access expression using (*this) as the
1708 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001709 //
1710 // But we don't actually need to do this for '&' operands if R
1711 // resolved to a function or overloaded function set, because the
1712 // expression is ill-formed if it actually works out to be a
1713 // non-static member function:
1714 //
1715 // C++ [expr.ref]p4:
1716 // Otherwise, if E1.E2 refers to a non-static member function. . .
1717 // [t]he expression can be used only as the left-hand operand of a
1718 // member function call.
1719 //
1720 // There are other safeguards against such uses, but it's important
1721 // to get this right here so that we don't end up making a
1722 // spuriously dependent expression if we're inside a dependent
1723 // instance method.
John McCall57500772009-12-16 12:17:52 +00001724 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001725 bool MightBeImplicitMember;
1726 if (!isAddressOfOperand)
1727 MightBeImplicitMember = true;
1728 else if (!SS.isEmpty())
1729 MightBeImplicitMember = false;
1730 else if (R.isOverloadedResult())
1731 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001732 else if (R.isUnresolvableResult())
1733 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001734 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001735 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1736 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001737
1738 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001739 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001740 }
1741
John McCalle66edc12009-11-24 19:00:30 +00001742 if (TemplateArgs)
1743 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001744
John McCalle66edc12009-11-24 19:00:30 +00001745 return BuildDeclarationNameExpr(SS, R, ADL);
1746}
1747
John McCall10eae182009-11-30 22:42:35 +00001748/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1749/// declaration name, generally during template instantiation.
1750/// There's a large number of things which don't need to be done along
1751/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001752ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001753Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001754 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001755 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001756 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001757 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001758
John McCall0b66eb32010-05-01 00:40:08 +00001759 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001760 return ExprError();
1761
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001762 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001763 LookupQualifiedName(R, DC);
1764
1765 if (R.isAmbiguous())
1766 return ExprError();
1767
1768 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001769 Diag(NameInfo.getLoc(), diag::err_no_member)
1770 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001771 return ExprError();
1772 }
1773
1774 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1775}
1776
1777/// LookupInObjCMethod - The parser has read a name in, and Sema has
1778/// detected that we're currently inside an ObjC method. Perform some
1779/// additional lookup.
1780///
1781/// Ideally, most of this would be done by lookup, but there's
1782/// actually quite a lot of extra work involved.
1783///
1784/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001785ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001786Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001787 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001788 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001789 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001790
John McCalle66edc12009-11-24 19:00:30 +00001791 // There are two cases to handle here. 1) scoped lookup could have failed,
1792 // in which case we should look for an ivar. 2) scoped lookup could have
1793 // found a decl, but that decl is outside the current instance method (i.e.
1794 // a global variable). In these two cases, we do a lookup for an ivar with
1795 // this name, if the lookup sucedes, we replace it our current decl.
1796
1797 // If we're in a class method, we don't normally want to look for
1798 // ivars. But if we don't find anything else, and there's an
1799 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001800 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001801
1802 bool LookForIvars;
1803 if (Lookup.empty())
1804 LookForIvars = true;
1805 else if (IsClassMethod)
1806 LookForIvars = false;
1807 else
1808 LookForIvars = (Lookup.isSingleResult() &&
1809 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001810 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001811 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001812 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001813 ObjCInterfaceDecl *ClassDeclared;
1814 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1815 // Diagnose using an ivar in a class method.
1816 if (IsClassMethod)
1817 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1818 << IV->getDeclName());
1819
1820 // If we're referencing an invalid decl, just return this as a silent
1821 // error node. The error diagnostic was already emitted on the decl.
1822 if (IV->isInvalidDecl())
1823 return ExprError();
1824
1825 // Check if referencing a field with __attribute__((deprecated)).
1826 if (DiagnoseUseOfDecl(IV, Loc))
1827 return ExprError();
1828
1829 // Diagnose the use of an ivar outside of the declaring class.
1830 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1831 ClassDeclared != IFace)
1832 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1833
1834 // FIXME: This should use a new expr for a direct reference, don't
1835 // turn this into Self->ivar, just return a BareIVarExpr or something.
1836 IdentifierInfo &II = Context.Idents.get("self");
1837 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001838 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001839 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001840 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001841 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001842 SelfName, false, false);
1843 if (SelfExpr.isInvalid())
1844 return ExprError();
1845
John Wiegley01296292011-04-08 18:41:53 +00001846 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1847 if (SelfExpr.isInvalid())
1848 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001849
John McCalle66edc12009-11-24 19:00:30 +00001850 MarkDeclarationReferenced(Loc, IV);
1851 return Owned(new (Context)
1852 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001853 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001854 }
Chris Lattner87313662010-04-12 05:10:17 +00001855 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001856 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001857 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001858 ObjCInterfaceDecl *ClassDeclared;
1859 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1860 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1861 IFace == ClassDeclared)
1862 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1863 }
1864 }
1865
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001866 if (Lookup.empty() && II && AllowBuiltinCreation) {
1867 // FIXME. Consolidate this with similar code in LookupName.
1868 if (unsigned BuiltinID = II->getBuiltinID()) {
1869 if (!(getLangOptions().CPlusPlus &&
1870 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1871 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1872 S, Lookup.isForRedeclaration(),
1873 Lookup.getNameLoc());
1874 if (D) Lookup.addDecl(D);
1875 }
1876 }
1877 }
John McCalle66edc12009-11-24 19:00:30 +00001878 // Sentinel value saying that we didn't do anything special.
1879 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001880}
John McCalld14a8642009-11-21 08:51:07 +00001881
John McCall16df1e52010-03-30 21:47:33 +00001882/// \brief Cast a base object to a member's actual type.
1883///
1884/// Logically this happens in three phases:
1885///
1886/// * First we cast from the base type to the naming class.
1887/// The naming class is the class into which we were looking
1888/// when we found the member; it's the qualifier type if a
1889/// qualifier was provided, and otherwise it's the base type.
1890///
1891/// * Next we cast from the naming class to the declaring class.
1892/// If the member we found was brought into a class's scope by
1893/// a using declaration, this is that class; otherwise it's
1894/// the class declaring the member.
1895///
1896/// * Finally we cast from the declaring class to the "true"
1897/// declaring class of the member. This conversion does not
1898/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001899ExprResult
1900Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001901 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001902 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001903 NamedDecl *Member) {
1904 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1905 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001906 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001907
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001908 QualType DestRecordType;
1909 QualType DestType;
1910 QualType FromRecordType;
1911 QualType FromType = From->getType();
1912 bool PointerConversions = false;
1913 if (isa<FieldDecl>(Member)) {
1914 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001915
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001916 if (FromType->getAs<PointerType>()) {
1917 DestType = Context.getPointerType(DestRecordType);
1918 FromRecordType = FromType->getPointeeType();
1919 PointerConversions = true;
1920 } else {
1921 DestType = DestRecordType;
1922 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001923 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001924 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1925 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001926 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001927
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001928 DestType = Method->getThisType(Context);
1929 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001930
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001931 if (FromType->getAs<PointerType>()) {
1932 FromRecordType = FromType->getPointeeType();
1933 PointerConversions = true;
1934 } else {
1935 FromRecordType = FromType;
1936 DestType = DestRecordType;
1937 }
1938 } else {
1939 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001940 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001942
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001943 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001944 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001945
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 // If the unqualified types are the same, no conversion is necessary.
1947 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001948 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001949
John McCall16df1e52010-03-30 21:47:33 +00001950 SourceRange FromRange = From->getSourceRange();
1951 SourceLocation FromLoc = FromRange.getBegin();
1952
John McCall2536c6d2010-08-25 10:28:54 +00001953 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001954
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001955 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001957 // class name.
1958 //
1959 // If the member was a qualified name and the qualified referred to a
1960 // specific base subobject type, we'll cast to that intermediate type
1961 // first and then to the object in which the member is declared. That allows
1962 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1963 //
1964 // class Base { public: int x; };
1965 // class Derived1 : public Base { };
1966 // class Derived2 : public Base { };
1967 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1968 //
1969 // void VeryDerived::f() {
1970 // x = 17; // error: ambiguous base subobjects
1971 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1972 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001973 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001974 QualType QType = QualType(Qualifier->getAsType(), 0);
1975 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1976 assert(QType->isRecordType() && "lookup done with non-record type");
1977
1978 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1979
1980 // In C++98, the qualifier type doesn't actually have to be a base
1981 // type of the object type, in which case we just ignore it.
1982 // Otherwise build the appropriate casts.
1983 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001984 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001985 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001986 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001987 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00001988
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001990 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00001991 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1992 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001993
1994 FromType = QType;
1995 FromRecordType = QRecordType;
1996
1997 // If the qualifier type was the same as the destination type,
1998 // we're done.
1999 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002000 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002001 }
2002 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002003
John McCall16df1e52010-03-30 21:47:33 +00002004 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002005
John McCall16df1e52010-03-30 21:47:33 +00002006 // If we actually found the member through a using declaration, cast
2007 // down to the using declaration's type.
2008 //
2009 // Pointer equality is fine here because only one declaration of a
2010 // class ever has member declarations.
2011 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2012 assert(isa<UsingShadowDecl>(FoundDecl));
2013 QualType URecordType = Context.getTypeDeclType(
2014 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2015
2016 // We only need to do this if the naming-class to declaring-class
2017 // conversion is non-trivial.
2018 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2019 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002020 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002021 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002022 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002023 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002024
John McCall16df1e52010-03-30 21:47:33 +00002025 QualType UType = URecordType;
2026 if (PointerConversions)
2027 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002028 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2029 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002030 FromType = UType;
2031 FromRecordType = URecordType;
2032 }
2033
2034 // We don't do access control for the conversion from the
2035 // declaring class to the true declaring class.
2036 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002037 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002038
John McCallcf142162010-08-07 06:22:56 +00002039 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002040 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2041 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002042 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002043 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002044
John Wiegley01296292011-04-08 18:41:53 +00002045 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2046 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002047}
Douglas Gregor3256d042009-06-30 15:47:41 +00002048
John McCalle66edc12009-11-24 19:00:30 +00002049bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002050 const LookupResult &R,
2051 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002052 // Only when used directly as the postfix-expression of a call.
2053 if (!HasTrailingLParen)
2054 return false;
2055
2056 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002057 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002058 return false;
2059
2060 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002061 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002062 return false;
2063
2064 // Turn off ADL when we find certain kinds of declarations during
2065 // normal lookup:
2066 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2067 NamedDecl *D = *I;
2068
2069 // C++0x [basic.lookup.argdep]p3:
2070 // -- a declaration of a class member
2071 // Since using decls preserve this property, we check this on the
2072 // original decl.
John McCall57500772009-12-16 12:17:52 +00002073 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002074 return false;
2075
2076 // C++0x [basic.lookup.argdep]p3:
2077 // -- a block-scope function declaration that is not a
2078 // using-declaration
2079 // NOTE: we also trigger this for function templates (in fact, we
2080 // don't check the decl type at all, since all other decl types
2081 // turn off ADL anyway).
2082 if (isa<UsingShadowDecl>(D))
2083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2084 else if (D->getDeclContext()->isFunctionOrMethod())
2085 return false;
2086
2087 // C++0x [basic.lookup.argdep]p3:
2088 // -- a declaration that is neither a function or a function
2089 // template
2090 // And also for builtin functions.
2091 if (isa<FunctionDecl>(D)) {
2092 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2093
2094 // But also builtin functions.
2095 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2096 return false;
2097 } else if (!isa<FunctionTemplateDecl>(D))
2098 return false;
2099 }
2100
2101 return true;
2102}
2103
2104
John McCalld14a8642009-11-21 08:51:07 +00002105/// Diagnoses obvious problems with the use of the given declaration
2106/// as an expression. This is only actually called for lookups that
2107/// were not overloaded, and it doesn't promise that the declaration
2108/// will in fact be used.
2109static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002110 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002111 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2112 return true;
2113 }
2114
2115 if (isa<ObjCInterfaceDecl>(D)) {
2116 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2117 return true;
2118 }
2119
2120 if (isa<NamespaceDecl>(D)) {
2121 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2122 return true;
2123 }
2124
2125 return false;
2126}
2127
John McCalldadc5752010-08-24 06:29:42 +00002128ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002129Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002130 LookupResult &R,
2131 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002132 // If this is a single, fully-resolved result and we don't need ADL,
2133 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002134 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002135 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2136 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002137
2138 // We only need to check the declaration if there's exactly one
2139 // result, because in the overloaded case the results can only be
2140 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002141 if (R.isSingleResult() &&
2142 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002143 return ExprError();
2144
John McCall58cc69d2010-01-27 01:50:18 +00002145 // Otherwise, just build an unresolved lookup expression. Suppress
2146 // any lookup-related diagnostics; we'll hash these out later, when
2147 // we've picked a target.
2148 R.suppressDiagnostics();
2149
John McCalld14a8642009-11-21 08:51:07 +00002150 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002151 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002152 SS.getWithLocInContext(Context),
2153 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002154 NeedsADL, R.isOverloadedResult(),
2155 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002156
2157 return Owned(ULE);
2158}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002159
John McCalld14a8642009-11-21 08:51:07 +00002160/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002161ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002162Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002163 const DeclarationNameInfo &NameInfo,
2164 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002165 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002166 assert(!isa<FunctionTemplateDecl>(D) &&
2167 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002168
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002169 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002170 if (CheckDeclInExpr(*this, Loc, D))
2171 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002172
Douglas Gregore7488b92009-12-01 16:58:18 +00002173 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2174 // Specifically diagnose references to class templates that are missing
2175 // a template argument list.
2176 Diag(Loc, diag::err_template_decl_ref)
2177 << Template << SS.getRange();
2178 Diag(Template->getLocation(), diag::note_template_decl_here);
2179 return ExprError();
2180 }
2181
2182 // Make sure that we're referring to a value.
2183 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2184 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002185 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002186 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002187 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002188 return ExprError();
2189 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002190
Douglas Gregor171c45a2009-02-18 21:56:37 +00002191 // Check whether this declaration can be used. Note that we suppress
2192 // this check when we're going to perform argument-dependent lookup
2193 // on this function name, because this might not be the function
2194 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002195 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002196 return ExprError();
2197
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002198 // Only create DeclRefExpr's for valid Decl's.
2199 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002200 return ExprError();
2201
John McCallf3a88602011-02-03 08:15:49 +00002202 // Handle members of anonymous structs and unions. If we got here,
2203 // and the reference is to a class member indirect field, then this
2204 // must be the subject of a pointer-to-member expression.
2205 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2206 if (!indirectField->isCXXClassMember())
2207 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2208 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002209
Chris Lattner2a9d9892008-10-20 05:16:36 +00002210 // If the identifier reference is inside a block, and it refers to a value
2211 // that is outside the block, create a BlockDeclRefExpr instead of a
2212 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2213 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002214 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002215 // We do not do this for things like enum constants, global variables, etc,
2216 // as they do not get snapshotted.
2217 //
John McCall351762c2011-02-07 10:33:21 +00002218 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002219 case CR_Error:
2220 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002221
John McCallc63de662011-02-02 13:00:07 +00002222 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002223 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2224 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2225
2226 case CR_CaptureByRef:
2227 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2228 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002229
2230 case CR_NoCapture: {
2231 // If this reference is not in a block or if the referenced
2232 // variable is within the block, create a normal DeclRefExpr.
2233
2234 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002235 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002236
2237 switch (D->getKind()) {
2238 // Ignore all the non-ValueDecl kinds.
2239#define ABSTRACT_DECL(kind)
2240#define VALUE(type, base)
2241#define DECL(type, base) \
2242 case Decl::type:
2243#include "clang/AST/DeclNodes.inc"
2244 llvm_unreachable("invalid value decl kind");
2245 return ExprError();
2246
2247 // These shouldn't make it here.
2248 case Decl::ObjCAtDefsField:
2249 case Decl::ObjCIvar:
2250 llvm_unreachable("forming non-member reference to ivar?");
2251 return ExprError();
2252
2253 // Enum constants are always r-values and never references.
2254 // Unresolved using declarations are dependent.
2255 case Decl::EnumConstant:
2256 case Decl::UnresolvedUsingValue:
2257 valueKind = VK_RValue;
2258 break;
2259
2260 // Fields and indirect fields that got here must be for
2261 // pointer-to-member expressions; we just call them l-values for
2262 // internal consistency, because this subexpression doesn't really
2263 // exist in the high-level semantics.
2264 case Decl::Field:
2265 case Decl::IndirectField:
2266 assert(getLangOptions().CPlusPlus &&
2267 "building reference to field in C?");
2268
2269 // These can't have reference type in well-formed programs, but
2270 // for internal consistency we do this anyway.
2271 type = type.getNonReferenceType();
2272 valueKind = VK_LValue;
2273 break;
2274
2275 // Non-type template parameters are either l-values or r-values
2276 // depending on the type.
2277 case Decl::NonTypeTemplateParm: {
2278 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2279 type = reftype->getPointeeType();
2280 valueKind = VK_LValue; // even if the parameter is an r-value reference
2281 break;
2282 }
2283
2284 // For non-references, we need to strip qualifiers just in case
2285 // the template parameter was declared as 'const int' or whatever.
2286 valueKind = VK_RValue;
2287 type = type.getUnqualifiedType();
2288 break;
2289 }
2290
2291 case Decl::Var:
2292 // In C, "extern void blah;" is valid and is an r-value.
2293 if (!getLangOptions().CPlusPlus &&
2294 !type.hasQualifiers() &&
2295 type->isVoidType()) {
2296 valueKind = VK_RValue;
2297 break;
2298 }
2299 // fallthrough
2300
2301 case Decl::ImplicitParam:
2302 case Decl::ParmVar:
2303 // These are always l-values.
2304 valueKind = VK_LValue;
2305 type = type.getNonReferenceType();
2306 break;
2307
2308 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002309 const FunctionType *fty = type->castAs<FunctionType>();
2310
2311 // If we're referring to a function with an __unknown_anytype
2312 // result type, make the entire expression __unknown_anytype.
2313 if (fty->getResultType() == Context.UnknownAnyTy) {
2314 type = Context.UnknownAnyTy;
2315 valueKind = VK_RValue;
2316 break;
2317 }
2318
John McCallf4cd4f92011-02-09 01:13:10 +00002319 // Functions are l-values in C++.
2320 if (getLangOptions().CPlusPlus) {
2321 valueKind = VK_LValue;
2322 break;
2323 }
2324
2325 // C99 DR 316 says that, if a function type comes from a
2326 // function definition (without a prototype), that type is only
2327 // used for checking compatibility. Therefore, when referencing
2328 // the function, we pretend that we don't have the full function
2329 // type.
John McCall2979fe02011-04-12 00:42:48 +00002330 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2331 isa<FunctionProtoType>(fty))
2332 type = Context.getFunctionNoProtoType(fty->getResultType(),
2333 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002334
2335 // Functions are r-values in C.
2336 valueKind = VK_RValue;
2337 break;
2338 }
2339
2340 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002341 // If we're referring to a method with an __unknown_anytype
2342 // result type, make the entire expression __unknown_anytype.
2343 // This should only be possible with a type written directly.
2344 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2345 if (proto->getResultType() == Context.UnknownAnyTy) {
2346 type = Context.UnknownAnyTy;
2347 valueKind = VK_RValue;
2348 break;
2349 }
2350
John McCallf4cd4f92011-02-09 01:13:10 +00002351 // C++ methods are l-values if static, r-values if non-static.
2352 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2353 valueKind = VK_LValue;
2354 break;
2355 }
2356 // fallthrough
2357
2358 case Decl::CXXConversion:
2359 case Decl::CXXDestructor:
2360 case Decl::CXXConstructor:
2361 valueKind = VK_RValue;
2362 break;
2363 }
2364
2365 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2366 }
2367
John McCallc63de662011-02-02 13:00:07 +00002368 }
John McCall7decc9e2010-11-18 06:31:45 +00002369
John McCall351762c2011-02-07 10:33:21 +00002370 llvm_unreachable("unknown capture result");
2371 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002372}
Chris Lattnere168f762006-11-10 05:29:30 +00002373
John McCall2979fe02011-04-12 00:42:48 +00002374ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002375 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002376
Chris Lattnere168f762006-11-10 05:29:30 +00002377 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002378 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002379 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2380 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2381 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002382 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002383
Chris Lattnera81a0272008-01-12 08:14:25 +00002384 // Pre-defined identifiers are of type char[x], where x is the length of the
2385 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002386
Anders Carlsson2fb08242009-09-08 18:24:21 +00002387 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002388 if (!currentDecl && getCurBlock())
2389 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002390 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002391 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002392 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002393 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002394
Anders Carlsson0b209a82009-09-11 01:22:35 +00002395 QualType ResTy;
2396 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2397 ResTy = Context.DependentTy;
2398 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002399 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002400
Anders Carlsson0b209a82009-09-11 01:22:35 +00002401 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002402 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002403 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2404 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002405 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002406}
2407
John McCalldadc5752010-08-24 06:29:42 +00002408ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002409 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002410 bool Invalid = false;
2411 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2412 if (Invalid)
2413 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002414
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002415 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2416 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002417 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002418 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002419
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002420 QualType Ty;
2421 if (!getLangOptions().CPlusPlus)
2422 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2423 else if (Literal.isWide())
2424 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002425 else if (Literal.isMultiChar())
2426 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002427 else
2428 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002429
Sebastian Redl20614a72009-01-20 22:23:13 +00002430 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2431 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002432 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002433}
2434
John McCalldadc5752010-08-24 06:29:42 +00002435ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002436 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002437 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2438 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002439 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002440 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002441 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002442 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002443 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002444
Chris Lattner23b7eb62007-06-15 23:05:46 +00002445 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002446 // Add padding so that NumericLiteralParser can overread by one character.
2447 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002448 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002449
Chris Lattner67ca9252007-05-21 01:08:44 +00002450 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002451 bool Invalid = false;
2452 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2453 if (Invalid)
2454 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002455
Mike Stump11289f42009-09-09 15:08:12 +00002456 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002457 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002458 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002459 return ExprError();
2460
Chris Lattner1c20a172007-08-26 03:42:43 +00002461 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002462
Chris Lattner1c20a172007-08-26 03:42:43 +00002463 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002464 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002465 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002466 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002467 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002468 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002469 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002470 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002471
2472 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2473
John McCall53b93a02009-12-24 09:08:04 +00002474 using llvm::APFloat;
2475 APFloat Val(Format);
2476
2477 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002478
2479 // Overflow is always an error, but underflow is only an error if
2480 // we underflowed to zero (APFloat reports denormals as underflow).
2481 if ((result & APFloat::opOverflow) ||
2482 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002483 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002484 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002485 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002486 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002487 APFloat::getLargest(Format).toString(buffer);
2488 } else {
John McCall62abc942010-02-26 23:35:57 +00002489 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002490 APFloat::getSmallest(Format).toString(buffer);
2491 }
2492
2493 Diag(Tok.getLocation(), diagnostic)
2494 << Ty
2495 << llvm::StringRef(buffer.data(), buffer.size());
2496 }
2497
2498 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002499 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002500
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002501 if (Ty == Context.DoubleTy) {
2502 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002503 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002504 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2505 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002506 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002507 }
2508 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002509 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002510 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002511 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002512 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002513
Neil Boothac582c52007-08-29 22:00:19 +00002514 // long long is a C99 feature.
2515 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002516 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002517 Diag(Tok.getLocation(), diag::ext_longlong);
2518
Chris Lattner67ca9252007-05-21 01:08:44 +00002519 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002520 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002521
Chris Lattner67ca9252007-05-21 01:08:44 +00002522 if (Literal.GetIntegerValue(ResultVal)) {
2523 // If this value didn't fit into uintmax_t, warn and force to ull.
2524 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002525 Ty = Context.UnsignedLongLongTy;
2526 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002527 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002528 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002529 // If this value fits into a ULL, try to figure out what else it fits into
2530 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002531
Chris Lattner67ca9252007-05-21 01:08:44 +00002532 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2533 // be an unsigned int.
2534 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2535
2536 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002537 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002538 if (!Literal.isLong && !Literal.isLongLong) {
2539 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002540 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002541
Chris Lattner67ca9252007-05-21 01:08:44 +00002542 // Does it fit in a unsigned int?
2543 if (ResultVal.isIntN(IntSize)) {
2544 // Does it fit in a signed int?
2545 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002546 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002547 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002548 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002549 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002550 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002551 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002552
Chris Lattner67ca9252007-05-21 01:08:44 +00002553 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002554 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002555 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002556
Chris Lattner67ca9252007-05-21 01:08:44 +00002557 // Does it fit in a unsigned long?
2558 if (ResultVal.isIntN(LongSize)) {
2559 // Does it fit in a signed long?
2560 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002561 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002562 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002563 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002564 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002565 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002566 }
2567
Chris Lattner67ca9252007-05-21 01:08:44 +00002568 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002569 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002570 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Does it fit in a unsigned long long?
2573 if (ResultVal.isIntN(LongLongSize)) {
2574 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002575 // To be compatible with MSVC, hex integer literals ending with the
2576 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002577 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2578 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002579 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002580 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002581 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002582 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002583 }
2584 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002585
Chris Lattner67ca9252007-05-21 01:08:44 +00002586 // If we still couldn't decide a type, we probably have something that
2587 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002588 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002589 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002590 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002591 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002593
Chris Lattner55258cf2008-05-09 05:59:00 +00002594 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002595 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002596 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002597 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002598 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002599
Chris Lattner1c20a172007-08-26 03:42:43 +00002600 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2601 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002602 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002603 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002604
2605 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002606}
2607
John McCalldadc5752010-08-24 06:29:42 +00002608ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002609 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002610 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002611 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002612}
2613
Chandler Carruth62da79c2011-05-26 08:53:12 +00002614static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2615 SourceLocation Loc,
2616 SourceRange ArgRange) {
2617 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2618 // scalar or vector data type argument..."
2619 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2620 // type (C99 6.2.5p18) or void.
2621 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2622 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2623 << T << ArgRange;
2624 return true;
2625 }
2626
2627 assert((T->isVoidType() || !T->isIncompleteType()) &&
2628 "Scalar types should always be complete");
2629 return false;
2630}
2631
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002632static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2633 SourceLocation Loc,
2634 SourceRange ArgRange,
2635 UnaryExprOrTypeTrait TraitKind) {
2636 // C99 6.5.3.4p1:
2637 if (T->isFunctionType()) {
2638 // alignof(function) is allowed as an extension.
2639 if (TraitKind == UETT_SizeOf)
2640 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2641 return false;
2642 }
2643
2644 // Allow sizeof(void)/alignof(void) as an extension.
2645 if (T->isVoidType()) {
2646 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2647 return false;
2648 }
2649
2650 return true;
2651}
2652
2653static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2654 SourceLocation Loc,
2655 SourceRange ArgRange,
2656 UnaryExprOrTypeTrait TraitKind) {
2657 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2658 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2659 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2660 << T << (TraitKind == UETT_SizeOf)
2661 << ArgRange;
2662 return true;
2663 }
2664
2665 return false;
2666}
2667
Chandler Carruth14502c22011-05-26 08:53:10 +00002668/// \brief Check the constrains on expression operands to unary type expression
2669/// and type traits.
2670///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002671/// Completes any types necessary and validates the constraints on the operand
2672/// expression. The logic mostly mirrors the type-based overload, but may modify
2673/// the expression as it completes the type for that expression through template
2674/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002675bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2676 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002677 QualType ExprTy = Op->getType();
2678
2679 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2680 // the result is the size of the referenced type."
2681 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2682 // result shall be the alignment of the referenced type."
2683 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2684 ExprTy = Ref->getPointeeType();
2685
2686 if (ExprKind == UETT_VecStep)
2687 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2688 Op->getSourceRange());
2689
2690 // Whitelist some types as extensions
2691 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2692 Op->getSourceRange(), ExprKind))
2693 return false;
2694
2695 if (RequireCompleteExprType(Op,
2696 PDiag(diag::err_sizeof_alignof_incomplete_type)
2697 << ExprKind << Op->getSourceRange(),
2698 std::make_pair(SourceLocation(), PDiag(0))))
2699 return true;
2700
2701 // Completeing the expression's type may have changed it.
2702 ExprTy = Op->getType();
2703 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2704 ExprTy = Ref->getPointeeType();
2705
2706 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2707 Op->getSourceRange(), ExprKind))
2708 return true;
2709
Nico Weber0870deb2011-06-15 02:47:03 +00002710 if (ExprKind == UETT_SizeOf) {
2711 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2712 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2713 QualType OType = PVD->getOriginalType();
2714 QualType Type = PVD->getType();
2715 if (Type->isPointerType() && OType->isArrayType()) {
2716 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2717 << Type << OType;
2718 Diag(PVD->getLocation(), diag::note_declared_at);
2719 }
2720 }
2721 }
2722 }
2723
Chandler Carruth7c430c02011-05-27 01:33:31 +00002724 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002725}
2726
2727/// \brief Check the constraints on operands to unary expression and type
2728/// traits.
2729///
2730/// This will complete any types necessary, and validate the various constraints
2731/// on those operands.
2732///
Steve Naroff71b59a92007-06-04 22:22:31 +00002733/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002734/// C99 6.3.2.1p[2-4] all state:
2735/// Except when it is the operand of the sizeof operator ...
2736///
2737/// C++ [expr.sizeof]p4
2738/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2739/// standard conversions are not applied to the operand of sizeof.
2740///
2741/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002742bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2743 SourceLocation OpLoc,
2744 SourceRange ExprRange,
2745 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002746 if (exprType->isDependentType())
2747 return false;
2748
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002749 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2750 // the result is the size of the referenced type."
2751 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2752 // result shall be the alignment of the referenced type."
2753 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2754 exprType = Ref->getPointeeType();
2755
Chandler Carruth62da79c2011-05-26 08:53:12 +00002756 if (ExprKind == UETT_VecStep)
2757 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002758
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002759 // Whitelist some types as extensions
2760 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2761 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002762 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002763
Chris Lattner62975a72009-04-24 00:30:45 +00002764 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002766 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002767 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002769 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2770 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattner62975a72009-04-24 00:30:45 +00002773 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002774}
2775
Chandler Carruth14502c22011-05-26 08:53:10 +00002776static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002777 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002778
Mike Stump11289f42009-09-09 15:08:12 +00002779 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002780 if (isa<DeclRefExpr>(E))
2781 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002782
2783 // Cannot know anything else if the expression is dependent.
2784 if (E->isTypeDependent())
2785 return false;
2786
Douglas Gregor71235ec2009-05-02 02:18:30 +00002787 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002788 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2789 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002790 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002791 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002792
2793 // Alignment of a field access is always okay, so long as it isn't a
2794 // bit-field.
2795 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002796 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002797 return false;
2798
Chandler Carruth14502c22011-05-26 08:53:10 +00002799 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002800}
2801
Chandler Carruth14502c22011-05-26 08:53:10 +00002802bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002803 E = E->IgnoreParens();
2804
2805 // Cannot know anything else if the expression is dependent.
2806 if (E->isTypeDependent())
2807 return false;
2808
Chandler Carruth14502c22011-05-26 08:53:10 +00002809 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002810}
2811
Douglas Gregor0950e412009-03-13 21:01:28 +00002812/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002813ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002814Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2815 SourceLocation OpLoc,
2816 UnaryExprOrTypeTrait ExprKind,
2817 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002818 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002819 return ExprError();
2820
John McCallbcd03502009-12-07 02:54:59 +00002821 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002822
Douglas Gregor0950e412009-03-13 21:01:28 +00002823 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002824 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002825 return ExprError();
2826
2827 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002828 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2829 Context.getSizeType(),
2830 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002831}
2832
2833/// \brief Build a sizeof or alignof expression given an expression
2834/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002835ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002836Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2837 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002838 ExprResult PE = CheckPlaceholderExpr(E);
2839 if (PE.isInvalid())
2840 return ExprError();
2841
2842 E = PE.get();
2843
Douglas Gregor0950e412009-03-13 21:01:28 +00002844 // Verify that the operand is valid.
2845 bool isInvalid = false;
2846 if (E->isTypeDependent()) {
2847 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002848 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002849 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002850 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002851 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002852 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002853 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002854 isInvalid = true;
2855 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002856 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002857 }
2858
2859 if (isInvalid)
2860 return ExprError();
2861
2862 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002863 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002864 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002865 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002866}
2867
Peter Collingbournee190dee2011-03-11 19:24:49 +00002868/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2869/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002870/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002871ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002872Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2873 UnaryExprOrTypeTrait ExprKind, bool isType,
2874 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002875 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002876 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002877
Sebastian Redl6f282892008-11-11 17:56:53 +00002878 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002879 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002880 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002881 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002882 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002883
Douglas Gregor0950e412009-03-13 21:01:28 +00002884 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002885 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002886 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002887}
2888
John Wiegley01296292011-04-08 18:41:53 +00002889static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002890 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002891 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002892 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002893
John McCall34376a62010-12-04 03:47:34 +00002894 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002895 if (V.get()->getObjectKind() != OK_Ordinary) {
2896 V = S.DefaultLvalueConversion(V.take());
2897 if (V.isInvalid())
2898 return QualType();
2899 }
John McCall34376a62010-12-04 03:47:34 +00002900
Chris Lattnere267f5d2007-08-26 05:39:26 +00002901 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002902 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002903 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattnere267f5d2007-08-26 05:39:26 +00002905 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002906 if (V.get()->getType()->isArithmeticType())
2907 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002908
John McCall36226622010-10-12 02:09:17 +00002909 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002910 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002911 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002912 if (PR.get() != V.get()) {
2913 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002914 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002915 }
2916
Chris Lattnere267f5d2007-08-26 05:39:26 +00002917 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002918 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002919 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002920 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002921}
2922
2923
Chris Lattnere168f762006-11-10 05:29:30 +00002924
John McCalldadc5752010-08-24 06:29:42 +00002925ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002926Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002927 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002928 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002929 switch (Kind) {
2930 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002931 case tok::plusplus: Opc = UO_PostInc; break;
2932 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002933 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002934
John McCallb268a282010-08-23 23:25:46 +00002935 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002936}
2937
John McCalldadc5752010-08-24 06:29:42 +00002938ExprResult
John McCallb268a282010-08-23 23:25:46 +00002939Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2940 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002941 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002942 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002943 if (Result.isInvalid()) return ExprError();
2944 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002945
John McCallb268a282010-08-23 23:25:46 +00002946 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregor40412ac2008-11-19 17:17:41 +00002948 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002949 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002950 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002951 Context.DependentTy,
2952 VK_LValue, OK_Ordinary,
2953 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002954 }
2955
Mike Stump11289f42009-09-09 15:08:12 +00002956 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002957 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002958 LHSExp->getType()->isEnumeralType() ||
2959 RHSExp->getType()->isRecordType() ||
2960 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002961 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002962 }
2963
John McCallb268a282010-08-23 23:25:46 +00002964 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002965}
2966
2967
John McCalldadc5752010-08-24 06:29:42 +00002968ExprResult
John McCallb268a282010-08-23 23:25:46 +00002969Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2970 Expr *Idx, SourceLocation RLoc) {
2971 Expr *LHSExp = Base;
2972 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002973
Chris Lattner36d572b2007-07-16 00:14:47 +00002974 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00002975 if (!LHSExp->getType()->getAs<VectorType>()) {
2976 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2977 if (Result.isInvalid())
2978 return ExprError();
2979 LHSExp = Result.take();
2980 }
2981 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
2982 if (Result.isInvalid())
2983 return ExprError();
2984 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002985
Chris Lattner36d572b2007-07-16 00:14:47 +00002986 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002987 ExprValueKind VK = VK_LValue;
2988 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002989
Steve Naroffc1aadb12007-03-28 21:49:40 +00002990 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002991 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002992 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002993 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002994 Expr *BaseExpr, *IndexExpr;
2995 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002996 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2997 BaseExpr = LHSExp;
2998 IndexExpr = RHSExp;
2999 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003000 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003001 BaseExpr = LHSExp;
3002 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003003 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003004 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003005 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003006 BaseExpr = RHSExp;
3007 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003008 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003009 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003010 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003011 BaseExpr = LHSExp;
3012 IndexExpr = RHSExp;
3013 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003014 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003015 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003016 // Handle the uncommon case of "123[Ptr]".
3017 BaseExpr = RHSExp;
3018 IndexExpr = LHSExp;
3019 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003020 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003021 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003022 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003023 VK = LHSExp->getValueKind();
3024 if (VK != VK_RValue)
3025 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003026
Chris Lattner36d572b2007-07-16 00:14:47 +00003027 // FIXME: need to deal with const...
3028 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003029 } else if (LHSTy->isArrayType()) {
3030 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003031 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003032 // wasn't promoted because of the C90 rule that doesn't
3033 // allow promoting non-lvalue arrays. Warn, then
3034 // force the promotion here.
3035 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3036 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003037 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3038 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003039 LHSTy = LHSExp->getType();
3040
3041 BaseExpr = LHSExp;
3042 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003043 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003044 } else if (RHSTy->isArrayType()) {
3045 // Same as previous, except for 123[f().a] case
3046 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3047 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003048 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3049 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003050 RHSTy = RHSExp->getType();
3051
3052 BaseExpr = RHSExp;
3053 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003054 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003055 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003056 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3057 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003058 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003059 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003060 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003061 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3062 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003063
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003064 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003065 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3066 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003067 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3068
Douglas Gregorac1fb652009-03-24 19:52:54 +00003069 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003070 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3071 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003072 // incomplete types are not object types.
3073 if (ResultType->isFunctionType()) {
3074 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3075 << ResultType << BaseExpr->getSourceRange();
3076 return ExprError();
3077 }
Mike Stump11289f42009-09-09 15:08:12 +00003078
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003079 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3080 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003081 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3082 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003083
3084 // C forbids expressions of unqualified void type from being l-values.
3085 // See IsCForbiddenLValueType.
3086 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003087 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003088 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003089 PDiag(diag::err_subscript_incomplete_type)
3090 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003091 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattner62975a72009-04-24 00:30:45 +00003093 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003094 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003095 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3096 << ResultType << BaseExpr->getSourceRange();
3097 return ExprError();
3098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
John McCall4bc41ae2010-11-18 19:01:18 +00003100 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003101 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003102
Mike Stump4e1f26a2009-02-19 03:04:26 +00003103 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003104 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003105}
3106
John McCalldadc5752010-08-24 06:29:42 +00003107ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003108 FunctionDecl *FD,
3109 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003110 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003111 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003112 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003113 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003114 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003115 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003116 return ExprError();
3117 }
3118
3119 if (Param->hasUninstantiatedDefaultArg()) {
3120 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003121
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003122 // Instantiate the expression.
3123 MultiLevelTemplateArgumentList ArgList
3124 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003125
Nico Weber44887f62010-11-29 18:19:25 +00003126 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003127 = ArgList.getInnermost();
3128 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3129 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003130
Nico Weber44887f62010-11-29 18:19:25 +00003131 ExprResult Result;
3132 {
3133 // C++ [dcl.fct.default]p5:
3134 // The names in the [default argument] expression are bound, and
3135 // the semantic constraints are checked, at the point where the
3136 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003137 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003138 Result = SubstExpr(UninstExpr, ArgList);
3139 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003140 if (Result.isInvalid())
3141 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003142
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003143 // Check the expression as an initializer for the parameter.
3144 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003145 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003146 InitializationKind Kind
3147 = InitializationKind::CreateCopy(Param->getLocation(),
3148 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3149 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003150
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003151 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3152 Result = InitSeq.Perform(*this, Entity, Kind,
3153 MultiExprArg(*this, &ResultE, 1));
3154 if (Result.isInvalid())
3155 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003156
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003157 // Build the default argument expression.
3158 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3159 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003160 }
3161
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003162 // If the default expression creates temporaries, we need to
3163 // push them to the current stack of expression temporaries so they'll
3164 // be properly destroyed.
3165 // FIXME: We should really be rebuilding the default argument with new
3166 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003167 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3168 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3169 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3170 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3171 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003172 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003173 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003174
3175 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003176 // Just mark all of the declarations in this potentially-evaluated expression
3177 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003178 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003179 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003180}
3181
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003182/// ConvertArgumentsForCall - Converts the arguments specified in
3183/// Args/NumArgs to the parameter types of the function FDecl with
3184/// function prototype Proto. Call is the call expression itself, and
3185/// Fn is the function expression. For a C++ member function, this
3186/// routine does not attempt to convert the object argument. Returns
3187/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003188bool
3189Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003190 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003191 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003192 Expr **Args, unsigned NumArgs,
3193 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003194 // Bail out early if calling a builtin with custom typechecking.
3195 // We don't need to do this in the
3196 if (FDecl)
3197 if (unsigned ID = FDecl->getBuiltinID())
3198 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3199 return false;
3200
Mike Stump4e1f26a2009-02-19 03:04:26 +00003201 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003202 // assignment, to the types of the corresponding parameter, ...
3203 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003204 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003205
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003206 // If too few arguments are available (and we don't have default
3207 // arguments for the remaining parameters), don't make the call.
3208 if (NumArgs < NumArgsInProto) {
3209 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3210 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003211 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003212 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003213 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003214 }
3215
3216 // If too many are passed and not variadic, error on the extras and drop
3217 // them.
3218 if (NumArgs > NumArgsInProto) {
3219 if (!Proto->isVariadic()) {
3220 Diag(Args[NumArgsInProto]->getLocStart(),
3221 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003222 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003223 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003224 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3225 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003226
3227 // Emit the location of the prototype.
3228 if (FDecl && !FDecl->getBuiltinID())
3229 Diag(FDecl->getLocStart(),
3230 diag::note_typecheck_call_too_many_args)
3231 << FDecl;
3232
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003233 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003234 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003235 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003236 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003237 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003238 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003239 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003240 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3241 if (Fn->getType()->isBlockPointerType())
3242 CallType = VariadicBlock; // Block
3243 else if (isa<MemberExpr>(Fn))
3244 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003245 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003246 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003247 if (Invalid)
3248 return true;
3249 unsigned TotalNumArgs = AllArgs.size();
3250 for (unsigned i = 0; i < TotalNumArgs; ++i)
3251 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003252
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003253 return false;
3254}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003255
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003256bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3257 FunctionDecl *FDecl,
3258 const FunctionProtoType *Proto,
3259 unsigned FirstProtoArg,
3260 Expr **Args, unsigned NumArgs,
3261 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003262 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003263 unsigned NumArgsInProto = Proto->getNumArgs();
3264 unsigned NumArgsToCheck = NumArgs;
3265 bool Invalid = false;
3266 if (NumArgs != NumArgsInProto)
3267 // Use default arguments for missing arguments
3268 NumArgsToCheck = NumArgsInProto;
3269 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003270 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003271 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003272 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003273
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003274 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003275 if (ArgIx < NumArgs) {
3276 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003277
Eli Friedman3164fb12009-03-22 22:00:50 +00003278 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3279 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003280 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003281 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003282 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003283
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003284 // Pass the argument
3285 ParmVarDecl *Param = 0;
3286 if (FDecl && i < FDecl->getNumParams())
3287 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003288
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003289 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003290 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003291 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3292 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003293 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003294 SourceLocation(),
3295 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003296 if (ArgE.isInvalid())
3297 return true;
3298
3299 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003300 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003301 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003302
John McCalldadc5752010-08-24 06:29:42 +00003303 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003304 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003305 if (ArgExpr.isInvalid())
3306 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003307
Anders Carlsson355933d2009-08-25 03:49:14 +00003308 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003309 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003310 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003311 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003312
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003313 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003314 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003315
3316 // Assume that extern "C" functions with variadic arguments that
3317 // return __unknown_anytype aren't *really* variadic.
3318 if (Proto->getResultType() == Context.UnknownAnyTy &&
3319 FDecl && FDecl->isExternC()) {
3320 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3321 ExprResult arg;
3322 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3323 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3324 else
3325 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3326 Invalid |= arg.isInvalid();
3327 AllArgs.push_back(arg.take());
3328 }
3329
3330 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3331 } else {
3332 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3333 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3334 Invalid |= Arg.isInvalid();
3335 AllArgs.push_back(Arg.take());
3336 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003337 }
3338 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003339 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003340}
3341
John McCall2979fe02011-04-12 00:42:48 +00003342/// Given a function expression of unknown-any type, try to rebuild it
3343/// to have a function type.
3344static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3345
Steve Naroff83895f72007-09-16 03:34:24 +00003346/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003347/// This provides the location of the left/right parens and a list of comma
3348/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003349ExprResult
John McCallb268a282010-08-23 23:25:46 +00003350Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003351 MultiExprArg args, SourceLocation RParenLoc,
3352 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003353 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003354
3355 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003356 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003357 if (Result.isInvalid()) return ExprError();
3358 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003359
John McCallb268a282010-08-23 23:25:46 +00003360 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003361
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003362 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003363 // If this is a pseudo-destructor expression, build the call immediately.
3364 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3365 if (NumArgs > 0) {
3366 // Pseudo-destructor calls should not have any arguments.
3367 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003368 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003369 SourceRange(Args[0]->getLocStart(),
3370 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003371
Douglas Gregorad8a3362009-09-04 17:36:40 +00003372 NumArgs = 0;
3373 }
Mike Stump11289f42009-09-09 15:08:12 +00003374
Douglas Gregorad8a3362009-09-04 17:36:40 +00003375 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003376 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003377 }
Mike Stump11289f42009-09-09 15:08:12 +00003378
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003379 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003380 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003381 // FIXME: Will need to cache the results of name lookup (including ADL) in
3382 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003383 bool Dependent = false;
3384 if (Fn->isTypeDependent())
3385 Dependent = true;
3386 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3387 Dependent = true;
3388
Peter Collingbourne41f85462011-02-09 21:07:24 +00003389 if (Dependent) {
3390 if (ExecConfig) {
3391 return Owned(new (Context) CUDAKernelCallExpr(
3392 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3393 Context.DependentTy, VK_RValue, RParenLoc));
3394 } else {
3395 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3396 Context.DependentTy, VK_RValue,
3397 RParenLoc));
3398 }
3399 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003400
3401 // Determine whether this is a call to an object (C++ [over.call.object]).
3402 if (Fn->getType()->isRecordType())
3403 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003404 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003405
John McCall2979fe02011-04-12 00:42:48 +00003406 if (Fn->getType() == Context.UnknownAnyTy) {
3407 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3408 if (result.isInvalid()) return ExprError();
3409 Fn = result.take();
3410 }
3411
John McCall0009fcc2011-04-26 20:42:42 +00003412 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003413 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003414 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003415 }
John McCall0009fcc2011-04-26 20:42:42 +00003416 }
John McCall10eae182009-11-30 22:42:35 +00003417
John McCall0009fcc2011-04-26 20:42:42 +00003418 // Check for overloaded calls. This can happen even in C due to extensions.
3419 if (Fn->getType() == Context.OverloadTy) {
3420 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3421
3422 // We aren't supposed to apply this logic if there's an '&' involved.
3423 if (!find.IsAddressOfOperand) {
3424 OverloadExpr *ovl = find.Expression;
3425 if (isa<UnresolvedLookupExpr>(ovl)) {
3426 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3427 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3428 RParenLoc, ExecConfig);
3429 } else {
John McCall2d74de92009-12-01 22:10:20 +00003430 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003431 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003432 }
3433 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003434 }
3435
Douglas Gregore254f902009-02-04 00:32:51 +00003436 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003437
Eli Friedmane14b1992009-12-26 03:35:45 +00003438 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003439
John McCall57500772009-12-16 12:17:52 +00003440 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3442 if (UnOp->getOpcode() == UO_AddrOf)
3443 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3444
John McCall57500772009-12-16 12:17:52 +00003445 if (isa<DeclRefExpr>(NakedFn))
3446 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003447 else if (isa<MemberExpr>(NakedFn))
3448 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003449
Peter Collingbourne41f85462011-02-09 21:07:24 +00003450 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3451 ExecConfig);
3452}
3453
3454ExprResult
3455Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3456 MultiExprArg execConfig, SourceLocation GGGLoc) {
3457 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3458 if (!ConfigDecl)
3459 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3460 << "cudaConfigureCall");
3461 QualType ConfigQTy = ConfigDecl->getType();
3462
3463 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3464 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3465
3466 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003467}
3468
Tanya Lattner55808c12011-06-04 00:47:47 +00003469/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3470///
3471/// __builtin_astype( value, dst type )
3472///
3473ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3474 SourceLocation BuiltinLoc,
3475 SourceLocation RParenLoc) {
3476 ExprValueKind VK = VK_RValue;
3477 ExprObjectKind OK = OK_Ordinary;
3478 QualType DstTy = GetTypeFromParser(destty);
3479 QualType SrcTy = expr->getType();
3480 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3481 return ExprError(Diag(BuiltinLoc,
3482 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003483 << DstTy
3484 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003485 << expr->getSourceRange());
3486 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3487}
3488
John McCall57500772009-12-16 12:17:52 +00003489/// BuildResolvedCallExpr - Build a call to a resolved expression,
3490/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003491/// unary-convert to an expression of function-pointer or
3492/// block-pointer type.
3493///
3494/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003495ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003496Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3497 SourceLocation LParenLoc,
3498 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003499 SourceLocation RParenLoc,
3500 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003501 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3502
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003503 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003504 ExprResult Result = UsualUnaryConversions(Fn);
3505 if (Result.isInvalid())
3506 return ExprError();
3507 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003508
Chris Lattner08464942007-12-28 05:29:59 +00003509 // Make the call expr early, before semantic checks. This guarantees cleanup
3510 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003511 CallExpr *TheCall;
3512 if (Config) {
3513 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3514 cast<CallExpr>(Config),
3515 Args, NumArgs,
3516 Context.BoolTy,
3517 VK_RValue,
3518 RParenLoc);
3519 } else {
3520 TheCall = new (Context) CallExpr(Context, Fn,
3521 Args, NumArgs,
3522 Context.BoolTy,
3523 VK_RValue,
3524 RParenLoc);
3525 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003526
John McCallbebede42011-02-26 05:39:39 +00003527 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3528
3529 // Bail out early if calling a builtin with custom typechecking.
3530 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3531 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3532
John McCall31996342011-04-07 08:22:57 +00003533 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003534 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003535 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003536 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3537 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003538 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003539 if (FuncT == 0)
3540 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3541 << Fn->getType() << Fn->getSourceRange());
3542 } else if (const BlockPointerType *BPT =
3543 Fn->getType()->getAs<BlockPointerType>()) {
3544 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3545 } else {
John McCall31996342011-04-07 08:22:57 +00003546 // Handle calls to expressions of unknown-any type.
3547 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003548 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003549 if (rewrite.isInvalid()) return ExprError();
3550 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003551 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003552 goto retry;
3553 }
3554
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003555 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3556 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003557 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003558
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003559 if (getLangOptions().CUDA) {
3560 if (Config) {
3561 // CUDA: Kernel calls must be to global functions
3562 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3563 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3564 << FDecl->getName() << Fn->getSourceRange());
3565
3566 // CUDA: Kernel function must have 'void' return type
3567 if (!FuncT->getResultType()->isVoidType())
3568 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3569 << Fn->getType() << Fn->getSourceRange());
3570 }
3571 }
3572
Eli Friedman3164fb12009-03-22 22:00:50 +00003573 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003574 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003575 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003576 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003577 return ExprError();
3578
Chris Lattner08464942007-12-28 05:29:59 +00003579 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003580 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003581 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003582
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003583 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003584 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003585 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003586 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003587 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003588 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003589
Douglas Gregord8e97de2009-04-02 15:37:10 +00003590 if (FDecl) {
3591 // Check if we have too few/too many template arguments, based
3592 // on our knowledge of the function definition.
3593 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003594 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003595 const FunctionProtoType *Proto
3596 = Def->getType()->getAs<FunctionProtoType>();
3597 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003598 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3599 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003600 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003601
3602 // If the function we're calling isn't a function prototype, but we have
3603 // a function prototype from a prior declaratiom, use that prototype.
3604 if (!FDecl->hasPrototype())
3605 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003606 }
3607
Steve Naroff0b661582007-08-28 23:30:39 +00003608 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003609 for (unsigned i = 0; i != NumArgs; i++) {
3610 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003611
3612 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003613 InitializedEntity Entity
3614 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003615 Proto->getArgType(i),
3616 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003617 ExprResult ArgE = PerformCopyInitialization(Entity,
3618 SourceLocation(),
3619 Owned(Arg));
3620 if (ArgE.isInvalid())
3621 return true;
3622
3623 Arg = ArgE.takeAs<Expr>();
3624
3625 } else {
John Wiegley01296292011-04-08 18:41:53 +00003626 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3627
3628 if (ArgE.isInvalid())
3629 return true;
3630
3631 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003632 }
3633
Douglas Gregor83025412010-10-26 05:45:40 +00003634 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3635 Arg->getType(),
3636 PDiag(diag::err_call_incomplete_argument)
3637 << Arg->getSourceRange()))
3638 return ExprError();
3639
Chris Lattner08464942007-12-28 05:29:59 +00003640 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003641 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003642 }
Chris Lattner08464942007-12-28 05:29:59 +00003643
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003644 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3645 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003646 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3647 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003648
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003649 // Check for sentinels
3650 if (NDecl)
3651 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003653 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003654 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003655 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003656 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003657
John McCallbebede42011-02-26 05:39:39 +00003658 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003659 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003660 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003661 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003662 return ExprError();
3663 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003664
John McCallb268a282010-08-23 23:25:46 +00003665 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003666}
3667
John McCalldadc5752010-08-24 06:29:42 +00003668ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003669Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003670 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003671 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003672 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003673 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003674
3675 TypeSourceInfo *TInfo;
3676 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3677 if (!TInfo)
3678 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3679
John McCallb268a282010-08-23 23:25:46 +00003680 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003681}
3682
John McCalldadc5752010-08-24 06:29:42 +00003683ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003684Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003685 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003686 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003687
Eli Friedman37a186d2008-05-20 05:22:08 +00003688 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003689 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3690 PDiag(diag::err_illegal_decl_array_incomplete_type)
3691 << SourceRange(LParenLoc,
3692 literalExpr->getSourceRange().getEnd())))
3693 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003694 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003695 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3696 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003697 } else if (!literalType->isDependentType() &&
3698 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003699 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003700 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003701 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003702 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003703
Douglas Gregor85dabae2009-12-16 01:38:02 +00003704 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003705 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003706 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003707 = InitializationKind::CreateCStyleCast(LParenLoc,
3708 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003709 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003710 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003711 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003712 &literalType);
3713 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003714 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003715 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003716
Chris Lattner79413952008-12-04 23:50:19 +00003717 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003718 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003719 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003720 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003721 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003722
John McCall7decc9e2010-11-18 06:31:45 +00003723 // In C, compound literals are l-values for some reason.
3724 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3725
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003726 return MaybeBindToTemporary(
3727 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3728 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003729}
3730
John McCalldadc5752010-08-24 06:29:42 +00003731ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003732Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003733 SourceLocation RBraceLoc) {
3734 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003735 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003736
Steve Naroff30d242c2007-09-15 18:49:24 +00003737 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003738 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003739
Ted Kremenekac034612010-04-13 23:39:13 +00003740 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3741 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003742 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003743 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003744}
3745
John McCalld7646252010-11-14 08:17:51 +00003746/// Prepares for a scalar cast, performing all the necessary stages
3747/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003748static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003749 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3750 // Also, callers should have filtered out the invalid cases with
3751 // pointers. Everything else should be possible.
3752
John Wiegley01296292011-04-08 18:41:53 +00003753 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003754 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003755 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003756
John McCall8cb679e2010-11-15 09:13:47 +00003757 switch (SrcTy->getScalarTypeKind()) {
3758 case Type::STK_MemberPointer:
3759 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003760
John McCall8cb679e2010-11-15 09:13:47 +00003761 case Type::STK_Pointer:
3762 switch (DestTy->getScalarTypeKind()) {
3763 case Type::STK_Pointer:
3764 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003765 CK_AnyPointerToObjCPointerCast :
3766 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003767 case Type::STK_Bool:
3768 return CK_PointerToBoolean;
3769 case Type::STK_Integral:
3770 return CK_PointerToIntegral;
3771 case Type::STK_Floating:
3772 case Type::STK_FloatingComplex:
3773 case Type::STK_IntegralComplex:
3774 case Type::STK_MemberPointer:
3775 llvm_unreachable("illegal cast from pointer");
3776 }
3777 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003778
John McCall8cb679e2010-11-15 09:13:47 +00003779 case Type::STK_Bool: // casting from bool is like casting from an integer
3780 case Type::STK_Integral:
3781 switch (DestTy->getScalarTypeKind()) {
3782 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003783 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003784 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003785 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003786 case Type::STK_Bool:
3787 return CK_IntegralToBoolean;
3788 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003789 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003790 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003791 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003792 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003793 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3794 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003795 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003796 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003797 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3798 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003799 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003800 case Type::STK_MemberPointer:
3801 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003802 }
3803 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003804
John McCall8cb679e2010-11-15 09:13:47 +00003805 case Type::STK_Floating:
3806 switch (DestTy->getScalarTypeKind()) {
3807 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003808 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003809 case Type::STK_Bool:
3810 return CK_FloatingToBoolean;
3811 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003812 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003813 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003814 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3815 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003816 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003817 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003818 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3819 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003820 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003821 case Type::STK_Pointer:
3822 llvm_unreachable("valid float->pointer cast?");
3823 case Type::STK_MemberPointer:
3824 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003825 }
3826 break;
3827
John McCall8cb679e2010-11-15 09:13:47 +00003828 case Type::STK_FloatingComplex:
3829 switch (DestTy->getScalarTypeKind()) {
3830 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003831 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003832 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003833 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003834 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003835 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003836 if (S.Context.hasSameType(ET, DestTy))
3837 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003838 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003839 return CK_FloatingCast;
3840 }
John McCall8cb679e2010-11-15 09:13:47 +00003841 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003842 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003843 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003844 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3845 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003846 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003847 case Type::STK_Pointer:
3848 llvm_unreachable("valid complex float->pointer cast?");
3849 case Type::STK_MemberPointer:
3850 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003851 }
3852 break;
3853
John McCall8cb679e2010-11-15 09:13:47 +00003854 case Type::STK_IntegralComplex:
3855 switch (DestTy->getScalarTypeKind()) {
3856 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003857 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003858 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003859 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003860 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003861 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003862 if (S.Context.hasSameType(ET, DestTy))
3863 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003864 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003865 return CK_IntegralCast;
3866 }
John McCall8cb679e2010-11-15 09:13:47 +00003867 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003868 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003869 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003870 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3871 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003872 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003873 case Type::STK_Pointer:
3874 llvm_unreachable("valid complex int->pointer cast?");
3875 case Type::STK_MemberPointer:
3876 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003877 }
3878 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003879 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003880
John McCalld7646252010-11-14 08:17:51 +00003881 llvm_unreachable("Unhandled scalar cast");
3882 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003883}
3884
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003885/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003886ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3887 QualType castType, Expr *castExpr,
3888 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003889 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003890 if (castExpr->getType() == Context.UnknownAnyTy)
3891 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3892
Sebastian Redl9f831db2009-07-25 15:41:38 +00003893 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003894 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003895 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003896 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003897 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003898
John McCall3aef3d82011-04-10 19:13:55 +00003899 assert(!castExpr->getType()->isPlaceholderType());
3900
John McCall7decc9e2010-11-18 06:31:45 +00003901 // We only support r-value casts in C.
3902 VK = VK_RValue;
3903
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003904 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3905 // type needs to be scalar.
3906 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003907 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003908 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3909 if (castExprRes.isInvalid())
3910 return ExprError();
3911 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003912
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003913 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003914 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003915 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003916 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003917
John Wiegley01296292011-04-08 18:41:53 +00003918 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3919 if (castExprRes.isInvalid())
3920 return ExprError();
3921 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003922
Eli Friedmane98194d2010-07-17 20:43:49 +00003923 if (RequireCompleteType(TyR.getBegin(), castType,
3924 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003925 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003926
Anders Carlssonef918ac2009-10-16 02:35:04 +00003927 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003928 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003929 (castType->isStructureType() || castType->isUnionType())) {
3930 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003931 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003932 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3933 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003934 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003935 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003936 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003937
Anders Carlsson525b76b2009-10-16 02:48:28 +00003938 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003939 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003940 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003941 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003942 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003943 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003944 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003945 castExpr->getType()) &&
3946 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003947 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3948 << castExpr->getSourceRange();
3949 break;
3950 }
3951 }
John Wiegley01296292011-04-08 18:41:53 +00003952 if (Field == FieldEnd) {
3953 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003954 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003955 return ExprError();
3956 }
John McCalle3027922010-08-25 11:45:40 +00003957 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00003958 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003959 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003960
Anders Carlsson525b76b2009-10-16 02:48:28 +00003961 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00003962 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00003963 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003964 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003965 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003966
John McCalld7646252010-11-14 08:17:51 +00003967 // The type we're casting to is known to be a scalar or vector.
3968
3969 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003970 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003971 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00003972 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003973 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003974 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003975 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003976 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003977
3978 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00003979 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003980
Anton Yartsev28ccef72011-03-27 09:32:40 +00003981 if (castType->isVectorType()) {
3982 if (castType->getAs<VectorType>()->getVectorKind() ==
3983 VectorType::AltiVecVector &&
3984 (castExpr->getType()->isIntegerType() ||
3985 castExpr->getType()->isFloatingType())) {
3986 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00003987 return Owned(castExpr);
3988 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
3989 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00003990 } else
John Wiegley01296292011-04-08 18:41:53 +00003991 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00003992 }
John Wiegley01296292011-04-08 18:41:53 +00003993 if (castExpr->getType()->isVectorType()) {
3994 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
3995 return ExprError();
3996 else
3997 return Owned(castExpr);
3998 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003999
John McCalld7646252010-11-14 08:17:51 +00004000 // The source and target types are both scalars, i.e.
4001 // - arithmetic types (fundamental, enum, and complex)
4002 // - all kinds of pointers
4003 // Note that member pointers were filtered out with C++, above.
4004
John Wiegley01296292011-04-08 18:41:53 +00004005 if (isa<ObjCSelectorExpr>(castExpr)) {
4006 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4007 return ExprError();
4008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004009
John McCalld7646252010-11-14 08:17:51 +00004010 // If either type is a pointer, the other type has to be either an
4011 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004012 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004013 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004014 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004015 castExprType->isArithmeticType()) {
4016 Diag(castExpr->getLocStart(),
4017 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004018 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004019 return ExprError();
4020 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004021 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004022 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4023 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004024 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004025 return ExprError();
4026 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004027 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004028
John McCall31168b02011-06-15 23:02:42 +00004029 if (getLangOptions().ObjCAutoRefCount) {
4030 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4031 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4032 castType, castExpr, CCK_CStyleCast);
4033
4034 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4035 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4036 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4037 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4038 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4039 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4040 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4041 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004042 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004043 << castExprType << castType << AA_Casting
4044 << castExpr->getSourceRange();
4045
4046 return ExprError();
4047 }
4048 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004049 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004050 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4051 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004052 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004053 << castExprType << castType
4054 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004055 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004056 }
4057 }
4058
John Wiegley01296292011-04-08 18:41:53 +00004059 castExprRes = Owned(castExpr);
4060 Kind = PrepareScalarCast(*this, castExprRes, castType);
4061 if (castExprRes.isInvalid())
4062 return ExprError();
4063 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004064
John McCalld7646252010-11-14 08:17:51 +00004065 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004066 CheckCastAlign(castExpr, castType, TyR);
4067
John Wiegley01296292011-04-08 18:41:53 +00004068 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004069}
4070
Anders Carlsson525b76b2009-10-16 02:48:28 +00004071bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004072 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004073 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004074
Anders Carlssonde71adf2007-11-27 05:51:55 +00004075 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004076 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004077 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004078 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004079 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004080 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004081 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004082 } else
4083 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004084 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004085 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004086
John McCalle3027922010-08-25 11:45:40 +00004087 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004088 return false;
4089}
4090
John Wiegley01296292011-04-08 18:41:53 +00004091ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4092 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004093 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004094
Anders Carlsson43d70f82009-10-16 05:23:41 +00004095 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004096
Nate Begemanc8961a42009-06-27 22:05:55 +00004097 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4098 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004099 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004100 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4101 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004102 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004103 return ExprError();
4104 }
John McCalle3027922010-08-25 11:45:40 +00004105 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004106 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004107 }
4108
Nate Begemanbd956c42009-06-28 02:36:38 +00004109 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004110 // conversion will take place first from scalar to elt type, and then
4111 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004112 if (SrcTy->isPointerType())
4113 return Diag(R.getBegin(),
4114 diag::err_invalid_conversion_between_vector_and_scalar)
4115 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004116
4117 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004118 ExprResult CastExprRes = Owned(CastExpr);
4119 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4120 if (CastExprRes.isInvalid())
4121 return ExprError();
4122 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004123
John McCalle3027922010-08-25 11:45:40 +00004124 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004125 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004126}
4127
John McCalldadc5752010-08-24 06:29:42 +00004128ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004129Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4130 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004131 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004132 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004133 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004134
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004135 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4136 if (D.isInvalidType())
4137 return ExprError();
4138
4139 if (getLangOptions().CPlusPlus) {
4140 // Check that there are no default arguments (C++ only).
4141 CheckExtraCXXDefaultArguments(D);
4142 }
4143
4144 QualType castType = castTInfo->getType();
4145 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004146
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004147 bool isVectorLiteral = false;
4148
4149 // Check for an altivec or OpenCL literal,
4150 // i.e. all the elements are integer constants.
4151 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4152 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4153 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4154 if (PLE && PLE->getNumExprs() == 0) {
4155 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4156 return ExprError();
4157 }
4158 if (PE || PLE->getNumExprs() == 1) {
4159 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4160 if (!E->getType()->isVectorType())
4161 isVectorLiteral = true;
4162 }
4163 else
4164 isVectorLiteral = true;
4165 }
4166
4167 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4168 // then handle it as such.
4169 if (isVectorLiteral)
4170 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4171
Nate Begeman5ec4b312009-08-10 23:49:36 +00004172 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004173 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4174 // sequence of BinOp comma operators.
4175 if (isa<ParenListExpr>(castExpr)) {
4176 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4177 if (Result.isInvalid()) return ExprError();
4178 castExpr = Result.take();
4179 }
John McCallebe54742010-01-15 18:56:44 +00004180
John McCallb268a282010-08-23 23:25:46 +00004181 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004182}
4183
John McCalldadc5752010-08-24 06:29:42 +00004184ExprResult
John McCallebe54742010-01-15 18:56:44 +00004185Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004186 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004187 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004188 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004189 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004190 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004191 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4192 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004193 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004194 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004195 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004196
John McCallcf142162010-08-07 06:22:56 +00004197 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004198 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004199 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004200 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004201}
4202
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004203ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4204 SourceLocation RParenLoc, Expr *E,
4205 TypeSourceInfo *TInfo) {
4206 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4207 "Expected paren or paren list expression");
4208
4209 Expr **exprs;
4210 unsigned numExprs;
4211 Expr *subExpr;
4212 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4213 exprs = PE->getExprs();
4214 numExprs = PE->getNumExprs();
4215 } else {
4216 subExpr = cast<ParenExpr>(E)->getSubExpr();
4217 exprs = &subExpr;
4218 numExprs = 1;
4219 }
4220
4221 QualType Ty = TInfo->getType();
4222 assert(Ty->isVectorType() && "Expected vector type");
4223
4224 llvm::SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004225 const VectorType *VTy = Ty->getAs<VectorType>();
4226 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4227
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004228 // '(...)' form of vector initialization in AltiVec: the number of
4229 // initializers must be one or must match the size of the vector.
4230 // If a single value is specified in the initializer then it will be
4231 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004232 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004233 // The number of initializers must be one or must match the size of the
4234 // vector. If a single value is specified in the initializer then it will
4235 // be replicated to all the components of the vector
4236 if (numExprs == 1) {
4237 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4238 ExprResult Literal = Owned(exprs[0]);
4239 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4240 PrepareScalarCast(*this, Literal, ElemTy));
4241 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4242 }
4243 else if (numExprs < numElems) {
4244 Diag(E->getExprLoc(),
4245 diag::err_incorrect_number_of_vector_initializers);
4246 return ExprError();
4247 }
4248 else
4249 for (unsigned i = 0, e = numExprs; i != e; ++i)
4250 initExprs.push_back(exprs[i]);
4251 }
Tanya Lattner83559382011-07-15 23:07:01 +00004252 else {
4253 // For OpenCL, when the number of initializers is a single value,
4254 // it will be replicated to all components of the vector.
4255 if (getLangOptions().OpenCL &&
4256 VTy->getVectorKind() == VectorType::GenericVector &&
4257 numExprs == 1) {
4258 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4259 ExprResult Literal = Owned(exprs[0]);
4260 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4261 PrepareScalarCast(*this, Literal, ElemTy));
4262 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4263 }
4264
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004265 for (unsigned i = 0, e = numExprs; i != e; ++i)
4266 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004267 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004268 // FIXME: This means that pretty-printing the final AST will produce curly
4269 // braces instead of the original commas.
4270 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4271 &initExprs[0],
4272 initExprs.size(), RParenLoc);
4273 initE->setType(Ty);
4274 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4275}
4276
Nate Begeman5ec4b312009-08-10 23:49:36 +00004277/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4278/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004279ExprResult
John McCallb268a282010-08-23 23:25:46 +00004280Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004281 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4282 if (!E)
4283 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004284
John McCalldadc5752010-08-24 06:29:42 +00004285 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004286
Nate Begeman5ec4b312009-08-10 23:49:36 +00004287 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004288 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4289 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCallb268a282010-08-23 23:25:46 +00004291 if (Result.isInvalid()) return ExprError();
4292
4293 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004294}
4295
John McCalldadc5752010-08-24 06:29:42 +00004296ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004297 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004298 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004299 unsigned nexprs = Val.size();
4300 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004301 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4302 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004303 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004304 expr = new (Context) ParenExpr(L, R, exprs[0]);
4305 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004306 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4307 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004308 return Owned(expr);
4309}
4310
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004311/// \brief Emit a specialized diagnostic when one expression is a null pointer
4312/// constant and the other is not a pointer.
4313bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4314 SourceLocation QuestionLoc) {
4315 Expr *NullExpr = LHS;
4316 Expr *NonPointerExpr = RHS;
4317 Expr::NullPointerConstantKind NullKind =
4318 NullExpr->isNullPointerConstant(Context,
4319 Expr::NPC_ValueDependentIsNotNull);
4320
4321 if (NullKind == Expr::NPCK_NotNull) {
4322 NullExpr = RHS;
4323 NonPointerExpr = LHS;
4324 NullKind =
4325 NullExpr->isNullPointerConstant(Context,
4326 Expr::NPC_ValueDependentIsNotNull);
4327 }
4328
4329 if (NullKind == Expr::NPCK_NotNull)
4330 return false;
4331
4332 if (NullKind == Expr::NPCK_ZeroInteger) {
4333 // In this case, check to make sure that we got here from a "NULL"
4334 // string in the source code.
4335 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004336 SourceLocation loc = NullExpr->getExprLoc();
4337 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004338 return false;
4339 }
4340
4341 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4342 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4343 << NonPointerExpr->getType() << DiagType
4344 << NonPointerExpr->getSourceRange();
4345 return true;
4346}
4347
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004348/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4349/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004350/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004351QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004352 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004353 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004354
John McCall3aef3d82011-04-10 19:13:55 +00004355 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004356 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004357 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004358
John McCall3aef3d82011-04-10 19:13:55 +00004359 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004360 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004361 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004362
Sebastian Redl1a99f442009-04-16 17:51:27 +00004363 // C++ is sufficiently different to merit its own checker.
4364 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004365 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004366
4367 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004368 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004369
John Wiegley01296292011-04-08 18:41:53 +00004370 Cond = UsualUnaryConversions(Cond.take());
4371 if (Cond.isInvalid())
4372 return QualType();
4373 LHS = UsualUnaryConversions(LHS.take());
4374 if (LHS.isInvalid())
4375 return QualType();
4376 RHS = UsualUnaryConversions(RHS.take());
4377 if (RHS.isInvalid())
4378 return QualType();
4379
4380 QualType CondTy = Cond.get()->getType();
4381 QualType LHSTy = LHS.get()->getType();
4382 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004383
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004384 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004385 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004386 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4387 // Throw an error if its not either.
4388 if (getLangOptions().OpenCL) {
4389 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004390 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004391 diag::err_typecheck_cond_expect_scalar_or_vector)
4392 << CondTy;
4393 return QualType();
4394 }
4395 }
4396 else {
John Wiegley01296292011-04-08 18:41:53 +00004397 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004398 << CondTy;
4399 return QualType();
4400 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004401 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004402
Chris Lattnere2949f42008-01-06 22:42:25 +00004403 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004404 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004405 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004406
Nate Begemanabb5a732010-09-20 22:41:17 +00004407 // OpenCL: If the condition is a vector, and both operands are scalar,
4408 // attempt to implicity convert them to the vector type to act like the
4409 // built in select.
4410 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4411 // Both operands should be of scalar type.
4412 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004413 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004414 << CondTy;
4415 return QualType();
4416 }
4417 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004418 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004419 << CondTy;
4420 return QualType();
4421 }
4422 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004423 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4424 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004425 }
4426
Chris Lattnere2949f42008-01-06 22:42:25 +00004427 // If both operands have arithmetic type, do the usual arithmetic conversions
4428 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004429 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4430 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004431 if (LHS.isInvalid() || RHS.isInvalid())
4432 return QualType();
4433 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004434 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004435
Chris Lattnere2949f42008-01-06 22:42:25 +00004436 // If both operands are the same structure or union type, the result is that
4437 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004438 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4439 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004440 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004441 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004442 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004443 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004444 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004445 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004446
Chris Lattnere2949f42008-01-06 22:42:25 +00004447 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004448 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004449 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4450 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004451 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4452 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004453 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004454 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4455 << LHS.get()->getSourceRange();
4456 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4457 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004458 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004459 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004460 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4461 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004462 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004463 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004464 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004465 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004466 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004467 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004468 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004469 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4470 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004471 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004472 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004474 // All objective-c pointer type analysis is done here.
4475 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4476 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004477 if (LHS.isInvalid() || RHS.isInvalid())
4478 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004479 if (!compositeType.isNull())
4480 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004481
4482
Steve Naroff05efa972009-07-01 14:36:47 +00004483 // Handle block pointer types.
4484 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4485 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4486 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4487 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004488 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4489 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004490 return destType;
4491 }
4492 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004493 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004494 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004495 }
Steve Naroff05efa972009-07-01 14:36:47 +00004496 // We have 2 block pointer types.
4497 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4498 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004499 return LHSTy;
4500 }
Steve Naroff05efa972009-07-01 14:36:47 +00004501 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004502 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4503 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004504
Steve Naroff05efa972009-07-01 14:36:47 +00004505 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4506 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004507 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004508 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004509 // In this situation, we assume void* type. No especially good
4510 // reason, but this is what gcc does, and we do have to pick
4511 // to get a consistent AST.
4512 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004513 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4514 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004515 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004516 }
Steve Naroff05efa972009-07-01 14:36:47 +00004517 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004518 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4519 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004520 return LHSTy;
4521 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004522
Steve Naroff05efa972009-07-01 14:36:47 +00004523 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4524 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4525 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004526 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4527 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004528
4529 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4530 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4531 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004532 QualType destPointee
4533 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004534 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004535 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004536 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004537 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004538 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004539 return destType;
4540 }
4541 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004542 QualType destPointee
4543 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004544 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004545 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004546 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004547 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004548 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004549 return destType;
4550 }
4551
4552 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4553 // Two identical pointer types are always compatible.
4554 return LHSTy;
4555 }
4556 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4557 rhptee.getUnqualifiedType())) {
4558 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004559 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004560 // In this situation, we assume void* type. No especially good
4561 // reason, but this is what gcc does, and we do have to pick
4562 // to get a consistent AST.
4563 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004564 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4565 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004566 return incompatTy;
4567 }
4568 // The pointer types are compatible.
4569 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4570 // differently qualified versions of compatible types, the result type is
4571 // a pointer to an appropriately qualified version of the *composite*
4572 // type.
4573 // FIXME: Need to calculate the composite type.
4574 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004575 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4576 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004577 return LHSTy;
4578 }
Mike Stump11289f42009-09-09 15:08:12 +00004579
John McCalle84af4e2010-11-13 01:35:44 +00004580 // GCC compatibility: soften pointer/integer mismatch. Note that
4581 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004582 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4583 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004584 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4585 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004586 return RHSTy;
4587 }
4588 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4589 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004590 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4591 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004592 return LHSTy;
4593 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004594
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004595 // Emit a better diagnostic if one of the expressions is a null pointer
4596 // constant and the other is not a pointer type. In this case, the user most
4597 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004598 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004599 return QualType();
4600
Chris Lattnere2949f42008-01-06 22:42:25 +00004601 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004602 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004603 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004604 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004605}
4606
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004607/// FindCompositeObjCPointerType - Helper method to find composite type of
4608/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004609QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004610 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004611 QualType LHSTy = LHS.get()->getType();
4612 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004613
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004614 // Handle things like Class and struct objc_class*. Here we case the result
4615 // to the pseudo-builtin, because that will be implicitly cast back to the
4616 // redefinition type if an attempt is made to access its fields.
4617 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004618 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004619 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004620 return LHSTy;
4621 }
4622 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004623 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004624 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004625 return RHSTy;
4626 }
4627 // And the same for struct objc_object* / id
4628 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004629 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004630 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004631 return LHSTy;
4632 }
4633 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004634 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004635 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004636 return RHSTy;
4637 }
4638 // And the same for struct objc_selector* / SEL
4639 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004640 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004641 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004642 return LHSTy;
4643 }
4644 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004645 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004646 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004647 return RHSTy;
4648 }
4649 // Check constraints for Objective-C object pointers types.
4650 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004651
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004652 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4653 // Two identical object pointer types are always compatible.
4654 return LHSTy;
4655 }
4656 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4657 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4658 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004659
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004660 // If both operands are interfaces and either operand can be
4661 // assigned to the other, use that type as the composite
4662 // type. This allows
4663 // xxx ? (A*) a : (B*) b
4664 // where B is a subclass of A.
4665 //
4666 // Additionally, as for assignment, if either type is 'id'
4667 // allow silent coercion. Finally, if the types are
4668 // incompatible then make sure to use 'id' as the composite
4669 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004670
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004671 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4672 // It could return the composite type.
4673 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4674 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4675 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4676 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4677 } else if ((LHSTy->isObjCQualifiedIdType() ||
4678 RHSTy->isObjCQualifiedIdType()) &&
4679 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4680 // Need to handle "id<xx>" explicitly.
4681 // GCC allows qualified id and any Objective-C type to devolve to
4682 // id. Currently localizing to here until clear this should be
4683 // part of ObjCQualifiedIdTypesAreCompatible.
4684 compositeType = Context.getObjCIdType();
4685 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4686 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004687 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004688 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4689 ;
4690 else {
4691 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4692 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004693 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004694 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004695 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4696 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004697 return incompatTy;
4698 }
4699 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004700 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4701 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004702 return compositeType;
4703 }
4704 // Check Objective-C object pointer types and 'void *'
4705 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4706 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4707 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4708 QualType destPointee
4709 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4710 QualType destType = Context.getPointerType(destPointee);
4711 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004712 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004713 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004714 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004715 return destType;
4716 }
4717 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4718 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4719 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4720 QualType destPointee
4721 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4722 QualType destType = Context.getPointerType(destPointee);
4723 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004724 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004725 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004726 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004727 return destType;
4728 }
4729 return QualType();
4730}
4731
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004732/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004733/// ParenRange in parentheses.
4734static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004735 const PartialDiagnostic &Note,
4736 SourceRange ParenRange) {
4737 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4738 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4739 EndLoc.isValid()) {
4740 Self.Diag(Loc, Note)
4741 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4742 << FixItHint::CreateInsertion(EndLoc, ")");
4743 } else {
4744 // We can't display the parentheses, so just show the bare note.
4745 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004746 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004747}
4748
4749static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4750 return Opc >= BO_Mul && Opc <= BO_Shr;
4751}
4752
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004753/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4754/// expression, either using a built-in or overloaded operator,
4755/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4756static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4757 Expr **RHS) {
4758 E = E->IgnoreParenImpCasts();
4759 E = E->IgnoreConversionOperator();
4760 E = E->IgnoreParenImpCasts();
4761
4762 // Built-in binary operator.
4763 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4764 if (IsArithmeticOp(OP->getOpcode())) {
4765 *Opcode = OP->getOpcode();
4766 *RHS = OP->getRHS();
4767 return true;
4768 }
4769 }
4770
4771 // Overloaded operator.
4772 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4773 if (Call->getNumArgs() != 2)
4774 return false;
4775
4776 // Make sure this is really a binary operator that is safe to pass into
4777 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4778 OverloadedOperatorKind OO = Call->getOperator();
4779 if (OO < OO_Plus || OO > OO_Arrow)
4780 return false;
4781
4782 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4783 if (IsArithmeticOp(OpKind)) {
4784 *Opcode = OpKind;
4785 *RHS = Call->getArg(1);
4786 return true;
4787 }
4788 }
4789
4790 return false;
4791}
4792
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004793static bool IsLogicOp(BinaryOperatorKind Opc) {
4794 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4795}
4796
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004797/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4798/// or is a logical expression such as (x==y) which has int type, but is
4799/// commonly interpreted as boolean.
4800static bool ExprLooksBoolean(Expr *E) {
4801 E = E->IgnoreParenImpCasts();
4802
4803 if (E->getType()->isBooleanType())
4804 return true;
4805 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4806 return IsLogicOp(OP->getOpcode());
4807 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4808 return OP->getOpcode() == UO_LNot;
4809
4810 return false;
4811}
4812
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004813/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4814/// and binary operator are mixed in a way that suggests the programmer assumed
4815/// the conditional operator has higher precedence, for example:
4816/// "int x = a + someBinaryCondition ? 1 : 2".
4817static void DiagnoseConditionalPrecedence(Sema &Self,
4818 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004819 Expr *Condition,
4820 Expr *LHS,
4821 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004822 BinaryOperatorKind CondOpcode;
4823 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004824
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004825 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004826 return;
4827 if (!ExprLooksBoolean(CondRHS))
4828 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004829
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004830 // The condition is an arithmetic binary expression, with a right-
4831 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004832
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004833 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004834 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004835 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004836
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004837 SuggestParentheses(Self, OpLoc,
4838 Self.PDiag(diag::note_precedence_conditional_silence)
4839 << BinaryOperator::getOpcodeStr(CondOpcode),
4840 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004841
4842 SuggestParentheses(Self, OpLoc,
4843 Self.PDiag(diag::note_precedence_conditional_first),
4844 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004845}
4846
Steve Naroff83895f72007-09-16 03:34:24 +00004847/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004848/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004849ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004850 SourceLocation ColonLoc,
4851 Expr *CondExpr, Expr *LHSExpr,
4852 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004853 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4854 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004855 OpaqueValueExpr *opaqueValue = 0;
4856 Expr *commonExpr = 0;
4857 if (LHSExpr == 0) {
4858 commonExpr = CondExpr;
4859
4860 // We usually want to apply unary conversions *before* saving, except
4861 // in the special case of a C++ l-value conditional.
4862 if (!(getLangOptions().CPlusPlus
4863 && !commonExpr->isTypeDependent()
4864 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4865 && commonExpr->isGLValue()
4866 && commonExpr->isOrdinaryOrBitFieldObject()
4867 && RHSExpr->isOrdinaryOrBitFieldObject()
4868 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004869 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4870 if (commonRes.isInvalid())
4871 return ExprError();
4872 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004873 }
4874
4875 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4876 commonExpr->getType(),
4877 commonExpr->getValueKind(),
4878 commonExpr->getObjectKind());
4879 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004880 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004881
John McCall7decc9e2010-11-18 06:31:45 +00004882 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004883 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004884 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4885 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004886 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004887 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4888 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004889 return ExprError();
4890
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004891 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4892 RHS.get());
4893
John McCallc07a0c72011-02-17 10:25:35 +00004894 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004895 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4896 LHS.take(), ColonLoc,
4897 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004898
4899 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004900 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4901 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004902}
4903
John McCallaba90822011-01-31 23:13:11 +00004904// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004905// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004906// routine is it effectively iqnores the qualifiers on the top level pointee.
4907// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4908// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004909static Sema::AssignConvertType
4910checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4911 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4912 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004913
Steve Naroff1f4d7272007-05-11 04:00:31 +00004914 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004915 const Type *lhptee, *rhptee;
4916 Qualifiers lhq, rhq;
4917 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4918 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004919
John McCallaba90822011-01-31 23:13:11 +00004920 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004921
4922 // C99 6.5.16.1p1: This following citation is common to constraints
4923 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4924 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004925 Qualifiers lq;
4926
John McCall31168b02011-06-15 23:02:42 +00004927 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4928 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4929 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4930 // Ignore lifetime for further calculation.
4931 lhq.removeObjCLifetime();
4932 rhq.removeObjCLifetime();
4933 }
4934
John McCall4fff8f62011-02-01 00:10:29 +00004935 if (!lhq.compatiblyIncludes(rhq)) {
4936 // Treat address-space mismatches as fatal. TODO: address subspaces
4937 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4938 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4939
John McCall31168b02011-06-15 23:02:42 +00004940 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004941 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004942 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4943 .compatiblyIncludes(
4944 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004945 && (lhptee->isVoidType() || rhptee->isVoidType()))
4946 ; // keep old
4947
John McCall31168b02011-06-15 23:02:42 +00004948 // Treat lifetime mismatches as fatal.
4949 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4950 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4951
John McCall4fff8f62011-02-01 00:10:29 +00004952 // For GCC compatibility, other qualifier mismatches are treated
4953 // as still compatible in C.
4954 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4955 }
Steve Naroff3f597292007-05-11 22:18:03 +00004956
Mike Stump4e1f26a2009-02-19 03:04:26 +00004957 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4958 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004959 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004960 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004961 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004962 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004963
Chris Lattner0a788432008-01-03 22:56:36 +00004964 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004965 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004966 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004967 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004968
Chris Lattner0a788432008-01-03 22:56:36 +00004969 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004970 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004971 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004972
4973 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004974 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004975 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004976 }
John McCall4fff8f62011-02-01 00:10:29 +00004977
Mike Stump4e1f26a2009-02-19 03:04:26 +00004978 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004979 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00004980 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
4981 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004982 // Check if the pointee types are compatible ignoring the sign.
4983 // We explicitly check for char so that we catch "char" vs
4984 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004985 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004986 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004987 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004988 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004989
Chris Lattnerec3a1562009-10-17 20:33:28 +00004990 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004991 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004992 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004993 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004994
John McCall4fff8f62011-02-01 00:10:29 +00004995 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004996 // Types are compatible ignoring the sign. Qualifier incompatibility
4997 // takes priority over sign incompatibility because the sign
4998 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00004999 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005000 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005001
John McCallaba90822011-01-31 23:13:11 +00005002 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005003 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005004
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005005 // If we are a multi-level pointer, it's possible that our issue is simply
5006 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5007 // the eventual target type is the same and the pointers have the same
5008 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005009 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005010 do {
John McCall4fff8f62011-02-01 00:10:29 +00005011 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5012 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005013 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005014
John McCall4fff8f62011-02-01 00:10:29 +00005015 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005016 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005018
Eli Friedman80160bd2009-03-22 23:59:44 +00005019 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005020 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005021 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005022 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005023}
5024
John McCallaba90822011-01-31 23:13:11 +00005025/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005026/// block pointer types are compatible or whether a block and normal pointer
5027/// are compatible. It is more restrict than comparing two function pointer
5028// types.
John McCallaba90822011-01-31 23:13:11 +00005029static Sema::AssignConvertType
5030checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5031 QualType rhsType) {
5032 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5033 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5034
Steve Naroff081c7422008-09-04 15:10:53 +00005035 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005036
Steve Naroff081c7422008-09-04 15:10:53 +00005037 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005038 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5039 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005040
John McCallaba90822011-01-31 23:13:11 +00005041 // In C++, the types have to match exactly.
5042 if (S.getLangOptions().CPlusPlus)
5043 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005044
John McCallaba90822011-01-31 23:13:11 +00005045 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005046
Steve Naroff081c7422008-09-04 15:10:53 +00005047 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005048 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5049 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005050
John McCallaba90822011-01-31 23:13:11 +00005051 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5052 return Sema::IncompatibleBlockPointer;
5053
Steve Naroff081c7422008-09-04 15:10:53 +00005054 return ConvTy;
5055}
5056
John McCallaba90822011-01-31 23:13:11 +00005057/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005058/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005059static Sema::AssignConvertType
5060checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5061 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5062 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5063
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005064 if (lhsType->isObjCBuiltinType()) {
5065 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005066 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5067 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005068 return Sema::IncompatiblePointer;
5069 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005070 }
5071 if (rhsType->isObjCBuiltinType()) {
5072 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005073 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5074 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005075 return Sema::IncompatiblePointer;
5076 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005077 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005078 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005079 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005080 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005081 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005082
John McCallaba90822011-01-31 23:13:11 +00005083 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5084 return Sema::CompatiblePointerDiscardsQualifiers;
5085
5086 if (S.Context.typesAreCompatible(lhsType, rhsType))
5087 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005088 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005089 return Sema::IncompatibleObjCQualifiedId;
5090 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005091}
5092
John McCall29600e12010-11-16 02:32:08 +00005093Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005094Sema::CheckAssignmentConstraints(SourceLocation Loc,
5095 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005096 // Fake up an opaque expression. We don't actually care about what
5097 // cast operations are required, so if CheckAssignmentConstraints
5098 // adds casts to this they'll be wasted, but fortunately that doesn't
5099 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005100 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005101 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005102 CastKind K = CK_Invalid;
5103
5104 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5105}
5106
Mike Stump4e1f26a2009-02-19 03:04:26 +00005107/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5108/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005109/// pointers. Here are some objectionable examples that GCC considers warnings:
5110///
5111/// int a, *pint;
5112/// short *pshort;
5113/// struct foo *pfoo;
5114///
5115/// pint = pshort; // warning: assignment from incompatible pointer type
5116/// a = pint; // warning: assignment makes integer from pointer without a cast
5117/// pint = a; // warning: assignment makes pointer from integer without a cast
5118/// pint = pfoo; // warning: assignment from incompatible pointer type
5119///
5120/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005121/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005122///
John McCall8cb679e2010-11-15 09:13:47 +00005123/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005124Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005125Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005126 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005127 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005128 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005129
Chris Lattnera52c2f22008-01-04 23:18:45 +00005130 // Get canonical types. We're not formatting these types, just comparing
5131 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005132 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5133 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005134
John McCalle5255932011-01-31 22:28:28 +00005135 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005136 if (lhsType == rhsType) {
5137 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005138 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005139 }
5140
Douglas Gregor6b754842008-10-28 00:22:11 +00005141 // If the left-hand side is a reference type, then we are in a
5142 // (rare!) case where we've allowed the use of references in C,
5143 // e.g., as a parameter type in a built-in function. In this case,
5144 // just make sure that the type referenced is compatible with the
5145 // right-hand side type. The caller is responsible for adjusting
5146 // lhsType so that the resulting expression does not have reference
5147 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005148 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005149 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5150 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005151 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005152 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005153 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005154 }
John McCalle5255932011-01-31 22:28:28 +00005155
Nate Begemanbd956c42009-06-28 02:36:38 +00005156 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5157 // to the same ExtVector type.
5158 if (lhsType->isExtVectorType()) {
5159 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005160 return Incompatible;
5161 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005162 // CK_VectorSplat does T -> vector T, so first cast to the
5163 // element type.
5164 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5165 if (elType != rhsType) {
5166 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005167 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005168 }
5169 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005170 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005171 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005172 }
Mike Stump11289f42009-09-09 15:08:12 +00005173
John McCalle5255932011-01-31 22:28:28 +00005174 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005175 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005176 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005177 // Allow assignments of an AltiVec vector type to an equivalent GCC
5178 // vector type and vice versa
5179 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5180 Kind = CK_BitCast;
5181 return Compatible;
5182 }
5183
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005184 // If we are allowing lax vector conversions, and LHS and RHS are both
5185 // vectors, the total size only needs to be the same. This is a bitcast;
5186 // no bits are changed but the result type is different.
5187 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005188 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005189 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005190 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005191 }
Chris Lattner881a2122008-01-04 23:32:24 +00005192 }
5193 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005194 }
Eli Friedman3360d892008-05-30 18:07:22 +00005195
John McCalle5255932011-01-31 22:28:28 +00005196 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005197 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005198 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005199 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005200 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005201 }
Eli Friedman3360d892008-05-30 18:07:22 +00005202
John McCalle5255932011-01-31 22:28:28 +00005203 // Conversions to normal pointers.
5204 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5205 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005206 if (isa<PointerType>(rhsType)) {
5207 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005208 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005209 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005210
John McCalle5255932011-01-31 22:28:28 +00005211 // int -> T*
5212 if (rhsType->isIntegerType()) {
5213 Kind = CK_IntegralToPointer; // FIXME: null?
5214 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005215 }
John McCalle5255932011-01-31 22:28:28 +00005216
5217 // C pointers are not compatible with ObjC object pointers,
5218 // with two exceptions:
5219 if (isa<ObjCObjectPointerType>(rhsType)) {
5220 // - conversions to void*
5221 if (lhsPointer->getPointeeType()->isVoidType()) {
5222 Kind = CK_AnyPointerToObjCPointerCast;
5223 return Compatible;
5224 }
5225
5226 // - conversions from 'Class' to the redefinition type
5227 if (rhsType->isObjCClassType() &&
5228 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005229 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005230 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005231 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005232
John McCalle5255932011-01-31 22:28:28 +00005233 Kind = CK_BitCast;
5234 return IncompatiblePointer;
5235 }
5236
5237 // U^ -> void*
5238 if (rhsType->getAs<BlockPointerType>()) {
5239 if (lhsPointer->getPointeeType()->isVoidType()) {
5240 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005241 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005242 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005243 }
John McCalle5255932011-01-31 22:28:28 +00005244
Steve Naroff081c7422008-09-04 15:10:53 +00005245 return Incompatible;
5246 }
5247
John McCalle5255932011-01-31 22:28:28 +00005248 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005249 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005250 // U^ -> T^
5251 if (rhsType->isBlockPointerType()) {
5252 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005253 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005254 }
5255
5256 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005257 if (rhsType->isIntegerType()) {
5258 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005259 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005260 }
5261
John McCalle5255932011-01-31 22:28:28 +00005262 // id -> T^
5263 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5264 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005265 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005266 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005267
John McCalle5255932011-01-31 22:28:28 +00005268 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005269 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005270 if (RHSPT->getPointeeType()->isVoidType()) {
5271 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005272 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005273 }
John McCall8cb679e2010-11-15 09:13:47 +00005274
Chris Lattnera52c2f22008-01-04 23:18:45 +00005275 return Incompatible;
5276 }
5277
John McCalle5255932011-01-31 22:28:28 +00005278 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005279 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005280 // A* -> B*
5281 if (rhsType->isObjCObjectPointerType()) {
5282 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005283 Sema::AssignConvertType result =
5284 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5285 if (getLangOptions().ObjCAutoRefCount &&
5286 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005287 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5288 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005289 return result;
John McCalle5255932011-01-31 22:28:28 +00005290 }
5291
5292 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005293 if (rhsType->isIntegerType()) {
5294 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005295 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005296 }
5297
John McCalle5255932011-01-31 22:28:28 +00005298 // In general, C pointers are not compatible with ObjC object pointers,
5299 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005300 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005301 // - conversions from 'void*'
5302 if (rhsType->isVoidPointerType()) {
5303 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005304 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005305 }
5306
5307 // - conversions to 'Class' from its redefinition type
5308 if (lhsType->isObjCClassType() &&
5309 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5310 Kind = CK_BitCast;
5311 return Compatible;
5312 }
5313
5314 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005315 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005316 }
John McCalle5255932011-01-31 22:28:28 +00005317
5318 // T^ -> A*
5319 if (rhsType->isBlockPointerType()) {
5320 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005321 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005322 }
5323
Steve Naroff7cae42b2009-07-10 23:34:53 +00005324 return Incompatible;
5325 }
John McCalle5255932011-01-31 22:28:28 +00005326
5327 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005328 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005329 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005330 if (lhsType == Context.BoolTy) {
5331 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005332 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005333 }
Eli Friedman3360d892008-05-30 18:07:22 +00005334
John McCalle5255932011-01-31 22:28:28 +00005335 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005336 if (lhsType->isIntegerType()) {
5337 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005338 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005339 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005340
Chris Lattnera52c2f22008-01-04 23:18:45 +00005341 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005342 }
John McCalle5255932011-01-31 22:28:28 +00005343
5344 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005345 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005346 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005347 if (lhsType == Context.BoolTy) {
5348 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005349 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005350 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005351
John McCalle5255932011-01-31 22:28:28 +00005352 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005353 if (lhsType->isIntegerType()) {
5354 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005355 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005356 }
5357
Steve Naroff7cae42b2009-07-10 23:34:53 +00005358 return Incompatible;
5359 }
Eli Friedman3360d892008-05-30 18:07:22 +00005360
John McCalle5255932011-01-31 22:28:28 +00005361 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005362 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005363 if (Context.typesAreCompatible(lhsType, rhsType)) {
5364 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005365 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005366 }
Bill Wendling216423b2007-05-30 06:30:29 +00005367 }
John McCalle5255932011-01-31 22:28:28 +00005368
Steve Naroff98cf3e92007-06-06 18:38:38 +00005369 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005370}
5371
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005372/// \brief Constructs a transparent union from an expression that is
5373/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005374static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005375 QualType UnionType, FieldDecl *Field) {
5376 // Build an initializer list that designates the appropriate member
5377 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005378 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005379 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005380 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005381 SourceLocation());
5382 Initializer->setType(UnionType);
5383 Initializer->setInitializedFieldInUnion(Field);
5384
5385 // Build a compound literal constructing a value of the transparent
5386 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005387 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005388 EResult = S.Owned(
5389 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5390 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005391}
5392
5393Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005394Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5395 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005396
Mike Stump11289f42009-09-09 15:08:12 +00005397 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005398 // transparent_union GCC extension.
5399 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005400 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005401 return Incompatible;
5402
5403 // The field to initialize within the transparent union.
5404 RecordDecl *UD = UT->getDecl();
5405 FieldDecl *InitField = 0;
5406 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005407 for (RecordDecl::field_iterator it = UD->field_begin(),
5408 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005409 it != itend; ++it) {
5410 if (it->getType()->isPointerType()) {
5411 // If the transparent union contains a pointer type, we allow:
5412 // 1) void pointer
5413 // 2) null pointer constant
5414 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005415 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005416 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005417 InitField = *it;
5418 break;
5419 }
Mike Stump11289f42009-09-09 15:08:12 +00005420
John Wiegley01296292011-04-08 18:41:53 +00005421 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005422 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005423 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005424 InitField = *it;
5425 break;
5426 }
5427 }
5428
John McCall8cb679e2010-11-15 09:13:47 +00005429 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005430 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005431 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005432 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005433 InitField = *it;
5434 break;
5435 }
5436 }
5437
5438 if (!InitField)
5439 return Incompatible;
5440
John Wiegley01296292011-04-08 18:41:53 +00005441 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005442 return Compatible;
5443}
5444
Chris Lattner9bad62c2008-01-04 18:04:52 +00005445Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005446Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005447 if (getLangOptions().CPlusPlus) {
5448 if (!lhsType->isRecordType()) {
5449 // C++ 5.17p3: If the left operand is not of class type, the
5450 // expression is implicitly converted (C++ 4) to the
5451 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005452 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5453 lhsType.getUnqualifiedType(),
5454 AA_Assigning);
5455 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005456 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005457 Sema::AssignConvertType result = Compatible;
5458 if (getLangOptions().ObjCAutoRefCount &&
5459 !CheckObjCARCUnavailableWeakConversion(lhsType, rExpr.get()->getType()))
5460 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005461 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005462 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005463 }
5464
5465 // FIXME: Currently, we fall through and treat C++ classes like C
5466 // structures.
John McCall34376a62010-12-04 03:47:34 +00005467 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005468
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005469 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5470 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005471 if ((lhsType->isPointerType() ||
5472 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005473 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005474 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005475 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005476 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005477 return Compatible;
5478 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005479
Chris Lattnere6dcd502007-10-16 02:55:40 +00005480 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005481 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005482 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005483 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005484 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005485 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005486 if (!lhsType->isReferenceType()) {
5487 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5488 if (rExpr.isInvalid())
5489 return Incompatible;
5490 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005491
John McCall8cb679e2010-11-15 09:13:47 +00005492 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005493 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005494 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005496 // C99 6.5.16.1p2: The value of the right operand is converted to the
5497 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005498 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5499 // so that we can use references in built-in functions even in C.
5500 // The getNonReferenceType() call makes sure that the resulting expression
5501 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005502 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5503 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005504 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005505}
5506
John Wiegley01296292011-04-08 18:41:53 +00005507QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005508 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005509 << lex.get()->getType() << rex.get()->getType()
5510 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005511 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005512}
5513
Eli Friedman1408bc92011-06-23 18:10:35 +00005514QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5515 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005516 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005517 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005518 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005519 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005520 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005521 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005522
Nate Begeman191a6b12008-07-14 18:02:46 +00005523 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005524 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005525 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005526
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005527 // Handle the case of equivalent AltiVec and GCC vector types
5528 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5529 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005530 if (lhsType->isExtVectorType()) {
5531 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5532 return lhsType;
5533 }
5534
5535 if (!isCompAssign)
5536 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005537 return rhsType;
5538 }
5539
Eli Friedman1408bc92011-06-23 18:10:35 +00005540 if (getLangOptions().LaxVectorConversions &&
5541 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5542 // If we are allowing lax vector conversions, and LHS and RHS are both
5543 // vectors, the total size only needs to be the same. This is a
5544 // bitcast; no bits are changed but the result type is different.
5545 // FIXME: Should we really be allowing this?
5546 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5547 return lhsType;
5548 }
5549
Nate Begemanbd956c42009-06-28 02:36:38 +00005550 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5551 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5552 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005553 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005554 swapped = true;
5555 std::swap(rex, lex);
5556 std::swap(rhsType, lhsType);
5557 }
Mike Stump11289f42009-09-09 15:08:12 +00005558
Nate Begeman886448d2009-06-28 19:12:57 +00005559 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005560 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005561 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005562 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005563 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5564 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005565 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005566 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005567 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005568 if (swapped) std::swap(rex, lex);
5569 return lhsType;
5570 }
5571 }
5572 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5573 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005574 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5575 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005576 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005577 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005578 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005579 if (swapped) std::swap(rex, lex);
5580 return lhsType;
5581 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005582 }
5583 }
Mike Stump11289f42009-09-09 15:08:12 +00005584
Nate Begeman886448d2009-06-28 19:12:57 +00005585 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005586 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005587 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005588 << lex.get()->getType() << rex.get()->getType()
5589 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005590 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005591}
5592
Chris Lattnerfaa54172010-01-12 21:23:57 +00005593QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005594 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5595 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005596 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005597
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005598 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005599 if (lex.isInvalid() || rex.isInvalid())
5600 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005601
John Wiegley01296292011-04-08 18:41:53 +00005602 if (!lex.get()->getType()->isArithmeticType() ||
5603 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005604 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005605
Chris Lattnerfaa54172010-01-12 21:23:57 +00005606 // Check for division by zero.
5607 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005608 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5609 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5610 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005611
Chris Lattnerfaa54172010-01-12 21:23:57 +00005612 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005613}
5614
Chris Lattnerfaa54172010-01-12 21:23:57 +00005615QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005616 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5617 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5618 if (lex.get()->getType()->hasIntegerRepresentation() &&
5619 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005620 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005621 return InvalidOperands(Loc, lex, rex);
5622 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005623
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005624 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005625 if (lex.isInvalid() || rex.isInvalid())
5626 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005627
John Wiegley01296292011-04-08 18:41:53 +00005628 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005629 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005630
Chris Lattnerfaa54172010-01-12 21:23:57 +00005631 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005632 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5633 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5634 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005635
Chris Lattnerfaa54172010-01-12 21:23:57 +00005636 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005637}
5638
Chandler Carruthc9332212011-06-27 08:02:19 +00005639/// \brief Diagnose invalid arithmetic on two void pointers.
5640static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5641 Expr *LHS, Expr *RHS) {
5642 S.Diag(Loc, S.getLangOptions().CPlusPlus
5643 ? diag::err_typecheck_pointer_arith_void_type
5644 : diag::ext_gnu_void_ptr)
5645 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5646}
5647
5648/// \brief Diagnose invalid arithmetic on a void pointer.
5649static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5650 Expr *Pointer) {
5651 S.Diag(Loc, S.getLangOptions().CPlusPlus
5652 ? diag::err_typecheck_pointer_arith_void_type
5653 : diag::ext_gnu_void_ptr)
5654 << 0 /* one pointer */ << Pointer->getSourceRange();
5655}
5656
5657/// \brief Diagnose invalid arithmetic on two function pointers.
5658static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5659 Expr *LHS, Expr *RHS) {
5660 assert(LHS->getType()->isAnyPointerType());
5661 assert(RHS->getType()->isAnyPointerType());
5662 S.Diag(Loc, S.getLangOptions().CPlusPlus
5663 ? diag::err_typecheck_pointer_arith_function_type
5664 : diag::ext_gnu_ptr_func_arith)
5665 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5666 // We only show the second type if it differs from the first.
5667 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5668 RHS->getType())
5669 << RHS->getType()->getPointeeType()
5670 << LHS->getSourceRange() << RHS->getSourceRange();
5671}
5672
5673/// \brief Diagnose invalid arithmetic on a function pointer.
5674static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5675 Expr *Pointer) {
5676 assert(Pointer->getType()->isAnyPointerType());
5677 S.Diag(Loc, S.getLangOptions().CPlusPlus
5678 ? diag::err_typecheck_pointer_arith_function_type
5679 : diag::ext_gnu_ptr_func_arith)
5680 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5681 << 0 /* one pointer, so only one type */
5682 << Pointer->getSourceRange();
5683}
5684
5685/// \brief Check the validity of an arithmetic pointer operand.
5686///
5687/// If the operand has pointer type, this code will check for pointer types
5688/// which are invalid in arithmetic operations. These will be diagnosed
5689/// appropriately, including whether or not the use is supported as an
5690/// extension.
5691///
5692/// \returns True when the operand is valid to use (even if as an extension).
5693static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5694 Expr *Operand) {
5695 if (!Operand->getType()->isAnyPointerType()) return true;
5696
5697 QualType PointeeTy = Operand->getType()->getPointeeType();
5698 if (PointeeTy->isVoidType()) {
5699 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5700 return !S.getLangOptions().CPlusPlus;
5701 }
5702 if (PointeeTy->isFunctionType()) {
5703 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5704 return !S.getLangOptions().CPlusPlus;
5705 }
5706
5707 if ((Operand->getType()->isPointerType() &&
5708 !Operand->getType()->isDependentType()) ||
5709 Operand->getType()->isObjCObjectPointerType()) {
5710 QualType PointeeTy = Operand->getType()->getPointeeType();
5711 if (S.RequireCompleteType(
5712 Loc, PointeeTy,
5713 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5714 << PointeeTy << Operand->getSourceRange()))
5715 return false;
5716 }
5717
5718 return true;
5719}
5720
5721/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5722/// operands.
5723///
5724/// This routine will diagnose any invalid arithmetic on pointer operands much
5725/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5726/// for emitting a single diagnostic even for operations where both LHS and RHS
5727/// are (potentially problematic) pointers.
5728///
5729/// \returns True when the operand is valid to use (even if as an extension).
5730static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5731 Expr *LHS, Expr *RHS) {
5732 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5733 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5734 if (!isLHSPointer && !isRHSPointer) return true;
5735
5736 QualType LHSPointeeTy, RHSPointeeTy;
5737 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5738 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5739
5740 // Check for arithmetic on pointers to incomplete types.
5741 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5742 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5743 if (isLHSVoidPtr || isRHSVoidPtr) {
5744 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5745 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5746 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5747
5748 return !S.getLangOptions().CPlusPlus;
5749 }
5750
5751 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5752 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5753 if (isLHSFuncPtr || isRHSFuncPtr) {
5754 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5755 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5756 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5757
5758 return !S.getLangOptions().CPlusPlus;
5759 }
5760
5761 Expr *Operands[] = { LHS, RHS };
5762 for (unsigned i = 0; i < 2; ++i) {
5763 Expr *Operand = Operands[i];
5764 if ((Operand->getType()->isPointerType() &&
5765 !Operand->getType()->isDependentType()) ||
5766 Operand->getType()->isObjCObjectPointerType()) {
5767 QualType PointeeTy = Operand->getType()->getPointeeType();
5768 if (S.RequireCompleteType(
5769 Loc, PointeeTy,
5770 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5771 << PointeeTy << Operand->getSourceRange()))
5772 return false;
5773 }
5774 }
5775 return true;
5776}
5777
Chris Lattnerfaa54172010-01-12 21:23:57 +00005778QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005779 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5780 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005781 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005782 if (CompLHSTy) *CompLHSTy = compType;
5783 return compType;
5784 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005785
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005786 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005787 if (lex.isInvalid() || rex.isInvalid())
5788 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005789
Steve Naroffe4718892007-04-27 18:30:00 +00005790 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005791 if (lex.get()->getType()->isArithmeticType() &&
5792 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005793 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005794 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005795 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005796
Eli Friedman8e122982008-05-18 18:08:51 +00005797 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005798 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005799 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005800 std::swap(PExp, IExp);
5801
Steve Naroff6b712a72009-07-14 18:25:06 +00005802 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005803 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005804 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5805 return QualType();
5806
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005807 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005808
Chris Lattner12bdebb2009-04-24 23:50:08 +00005809 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005810 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005811 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5812 << PointeeTy << PExp->getSourceRange();
5813 return QualType();
5814 }
Mike Stump11289f42009-09-09 15:08:12 +00005815
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005816 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005817 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005818 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005819 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005820 if (LHSTy->isPromotableIntegerType())
5821 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005822 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005823 *CompLHSTy = LHSTy;
5824 }
Eli Friedman8e122982008-05-18 18:08:51 +00005825 return PExp->getType();
5826 }
5827 }
5828
Chris Lattner326f7572008-11-18 01:30:42 +00005829 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005830}
5831
Chris Lattner2a3569b2008-04-07 05:30:13 +00005832// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005833QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005834 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005835 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005836 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005837 if (CompLHSTy) *CompLHSTy = compType;
5838 return compType;
5839 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005840
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005841 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005842 if (lex.isInvalid() || rex.isInvalid())
5843 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005844
Chris Lattner4d62f422007-12-09 21:53:25 +00005845 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005846
Chris Lattner4d62f422007-12-09 21:53:25 +00005847 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005848 if (lex.get()->getType()->isArithmeticType() &&
5849 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005850 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005851 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005852 }
Mike Stump11289f42009-09-09 15:08:12 +00005853
Chris Lattner4d62f422007-12-09 21:53:25 +00005854 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005855 if (lex.get()->getType()->isAnyPointerType()) {
5856 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005857
Chris Lattner12bdebb2009-04-24 23:50:08 +00005858 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005859 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005860 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005861 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005862 return QualType();
5863 }
Mike Stump11289f42009-09-09 15:08:12 +00005864
Chris Lattner4d62f422007-12-09 21:53:25 +00005865 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005866 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005867 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5868 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005869
John Wiegley01296292011-04-08 18:41:53 +00005870 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5871 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005872 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005873
Chris Lattner4d62f422007-12-09 21:53:25 +00005874 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005875 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005876 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005877
Eli Friedman168fe152009-05-16 13:54:38 +00005878 if (getLangOptions().CPlusPlus) {
5879 // Pointee types must be the same: C++ [expr.add]
5880 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5881 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005882 << lex.get()->getType() << rex.get()->getType()
5883 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005884 return QualType();
5885 }
5886 } else {
5887 // Pointee types must be compatible C99 6.5.6p3
5888 if (!Context.typesAreCompatible(
5889 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5890 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5891 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005892 << lex.get()->getType() << rex.get()->getType()
5893 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005894 return QualType();
5895 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005896 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005897
Chandler Carruthc9332212011-06-27 08:02:19 +00005898 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5899 lex.get(), rex.get()))
5900 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005901
John Wiegley01296292011-04-08 18:41:53 +00005902 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005903 return Context.getPointerDiffType();
5904 }
5905 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005906
Chris Lattner326f7572008-11-18 01:30:42 +00005907 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005908}
5909
Douglas Gregor0bf31402010-10-08 23:50:27 +00005910static bool isScopedEnumerationType(QualType T) {
5911 if (const EnumType *ET = dyn_cast<EnumType>(T))
5912 return ET->getDecl()->isScoped();
5913 return false;
5914}
5915
John Wiegley01296292011-04-08 18:41:53 +00005916static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005917 SourceLocation Loc, unsigned Opc,
5918 QualType LHSTy) {
5919 llvm::APSInt Right;
5920 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005921 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005922 return;
5923
5924 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005925 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005926 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005927 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005928 return;
5929 }
5930 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005931 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005932 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005933 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005934 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005935 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005936 return;
5937 }
5938 if (Opc != BO_Shl)
5939 return;
5940
5941 // When left shifting an ICE which is signed, we can check for overflow which
5942 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5943 // integers have defined behavior modulo one more than the maximum value
5944 // representable in the result type, so never warn for those.
5945 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005946 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005947 LHSTy->hasUnsignedIntegerRepresentation())
5948 return;
5949 llvm::APInt ResultBits =
5950 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5951 if (LeftBits.uge(ResultBits))
5952 return;
5953 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5954 Result = Result.shl(Right);
5955
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005956 // Print the bit representation of the signed integer as an unsigned
5957 // hexadecimal number.
5958 llvm::SmallString<40> HexResult;
5959 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5960
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005961 // If we are only missing a sign bit, this is less likely to result in actual
5962 // bugs -- if the result is cast back to an unsigned type, it will have the
5963 // expected value. Thus we place this behind a different warning that can be
5964 // turned off separately if needed.
5965 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005966 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5967 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005968 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005969 return;
5970 }
5971
5972 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005973 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005974 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005975}
5976
Chris Lattner2a3569b2008-04-07 05:30:13 +00005977// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00005978QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005979 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005980 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00005981 if (!lex.get()->getType()->hasIntegerRepresentation() ||
5982 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005983 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005984
Douglas Gregor0bf31402010-10-08 23:50:27 +00005985 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5986 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00005987 if (isScopedEnumerationType(lex.get()->getType()) ||
5988 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00005989 return InvalidOperands(Loc, lex, rex);
5990 }
5991
Nate Begemane46ee9a2009-10-25 02:26:48 +00005992 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00005993 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005994 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00005995
Chris Lattner5c11c412007-12-12 05:47:28 +00005996 // Shifts don't perform usual arithmetic conversions, they just do integer
5997 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005998
John McCall57cdd882010-12-16 19:28:59 +00005999 // For the LHS, do usual unary conversions, but then reset them away
6000 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006001 ExprResult old_lex = lex;
6002 lex = UsualUnaryConversions(lex.take());
6003 if (lex.isInvalid())
6004 return QualType();
6005 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006006 if (isCompAssign) lex = old_lex;
6007
6008 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006009 rex = UsualUnaryConversions(rex.take());
6010 if (rex.isInvalid())
6011 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006012
Ryan Flynnf53fab82009-08-07 16:20:20 +00006013 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006014 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006015
Chris Lattner5c11c412007-12-12 05:47:28 +00006016 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006017 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006018}
6019
Chandler Carruth17773fc2010-07-10 12:30:03 +00006020static bool IsWithinTemplateSpecialization(Decl *D) {
6021 if (DeclContext *DC = D->getDeclContext()) {
6022 if (isa<ClassTemplateSpecializationDecl>(DC))
6023 return true;
6024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6025 return FD->isFunctionTemplateSpecialization();
6026 }
6027 return false;
6028}
6029
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006030// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00006031QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006032 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006033 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006034
Chris Lattner9a152e22009-12-05 05:40:13 +00006035 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006036 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006037 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006038
John Wiegley01296292011-04-08 18:41:53 +00006039 QualType lType = lex.get()->getType();
6040 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006041
John Wiegley01296292011-04-08 18:41:53 +00006042 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6043 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006044 QualType LHSStrippedType = LHSStripped->getType();
6045 QualType RHSStrippedType = RHSStripped->getType();
6046
Douglas Gregor1beec452011-03-12 01:48:56 +00006047
6048
Chandler Carruth712563b2011-02-17 08:37:06 +00006049 // Two different enums will raise a warning when compared.
6050 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6051 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6052 if (LHSEnumType->getDecl()->getIdentifier() &&
6053 RHSEnumType->getDecl()->getIdentifier() &&
6054 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6055 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6056 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006057 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006058 }
6059 }
6060 }
6061
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006062 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006063 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006064 !lex.get()->getLocStart().isMacroID() &&
6065 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006066 // For non-floating point types, check for self-comparisons of the form
6067 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6068 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006069 //
6070 // NOTE: Don't warn about comparison expressions resulting from macro
6071 // expansion. Also don't warn about comparisons which are only self
6072 // comparisons within a template specialization. The warnings should catch
6073 // obvious cases in the definition of the template anyways. The idea is to
6074 // warn when the typed comparison operator will always evaluate to the same
6075 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006076 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006077 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006078 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006079 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006080 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006081 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006082 << (Opc == BO_EQ
6083 || Opc == BO_LE
6084 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006085 } else if (lType->isArrayType() && rType->isArrayType() &&
6086 !DRL->getDecl()->getType()->isReferenceType() &&
6087 !DRR->getDecl()->getType()->isReferenceType()) {
6088 // what is it always going to eval to?
6089 char always_evals_to;
6090 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006091 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006092 always_evals_to = 0; // false
6093 break;
John McCalle3027922010-08-25 11:45:40 +00006094 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006095 always_evals_to = 1; // true
6096 break;
6097 default:
6098 // best we can say is 'a constant'
6099 always_evals_to = 2; // e.g. array1 <= array2
6100 break;
6101 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006102 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006103 << 1 // array
6104 << always_evals_to);
6105 }
6106 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006107 }
Mike Stump11289f42009-09-09 15:08:12 +00006108
Chris Lattner222b8bd2009-03-08 19:39:53 +00006109 if (isa<CastExpr>(LHSStripped))
6110 LHSStripped = LHSStripped->IgnoreParenCasts();
6111 if (isa<CastExpr>(RHSStripped))
6112 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006113
Chris Lattner222b8bd2009-03-08 19:39:53 +00006114 // Warn about comparisons against a string constant (unless the other
6115 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006116 Expr *literalString = 0;
6117 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006118 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006119 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006120 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006121 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006122 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006123 } else if ((isa<StringLiteral>(RHSStripped) ||
6124 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006125 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006126 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006127 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006128 literalStringStripped = RHSStripped;
6129 }
6130
6131 if (literalString) {
6132 std::string resultComparison;
6133 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006134 case BO_LT: resultComparison = ") < 0"; break;
6135 case BO_GT: resultComparison = ") > 0"; break;
6136 case BO_LE: resultComparison = ") <= 0"; break;
6137 case BO_GE: resultComparison = ") >= 0"; break;
6138 case BO_EQ: resultComparison = ") == 0"; break;
6139 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006140 default: assert(false && "Invalid comparison operator");
6141 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006142
Ted Kremenek3427fac2011-02-23 01:52:04 +00006143 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006144 PDiag(diag::warn_stringcompare)
6145 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006146 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006147 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006148 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006149
Douglas Gregorec170db2010-06-08 19:50:34 +00006150 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006151 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006152 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006153 if (lex.isInvalid() || rex.isInvalid())
6154 return QualType();
6155 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006156 else {
John Wiegley01296292011-04-08 18:41:53 +00006157 lex = UsualUnaryConversions(lex.take());
6158 if (lex.isInvalid())
6159 return QualType();
6160
6161 rex = UsualUnaryConversions(rex.take());
6162 if (rex.isInvalid())
6163 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006164 }
6165
John Wiegley01296292011-04-08 18:41:53 +00006166 lType = lex.get()->getType();
6167 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006168
Douglas Gregorca63811b2008-11-19 03:25:36 +00006169 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006170 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006171
Chris Lattnerb620c342007-08-26 01:18:55 +00006172 if (isRelational) {
6173 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006174 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006175 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006176 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006177 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006178 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006179
Chris Lattnerb620c342007-08-26 01:18:55 +00006180 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006181 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006182 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006183
John Wiegley01296292011-04-08 18:41:53 +00006184 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006185 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006186 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006187 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006188
Douglas Gregorf267edd2010-06-15 21:38:40 +00006189 // All of the following pointer-related warnings are GCC extensions, except
6190 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006191 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006192 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006193 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006194 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006195 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006196
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006197 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006198 if (LCanPointeeTy == RCanPointeeTy)
6199 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006200 if (!isRelational &&
6201 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6202 // Valid unless comparison between non-null pointer and function pointer
6203 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006204 // In a SFINAE context, we treat this as a hard error to maintain
6205 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006206 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6207 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006208 Diag(Loc,
6209 isSFINAEContext()?
6210 diag::err_typecheck_comparison_of_fptr_to_void
6211 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006212 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006213
6214 if (isSFINAEContext())
6215 return QualType();
6216
John Wiegley01296292011-04-08 18:41:53 +00006217 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006218 return ResultTy;
6219 }
6220 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006221
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006222 // C++ [expr.rel]p2:
6223 // [...] Pointer conversions (4.10) and qualification
6224 // conversions (4.4) are performed on pointer operands (or on
6225 // a pointer operand and a null pointer constant) to bring
6226 // them to their composite pointer type. [...]
6227 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006228 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006229 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006230 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006231 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006232 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006233 if (T.isNull()) {
6234 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006235 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006236 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006237 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006238 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006239 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006240 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006241 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006242 }
6243
John Wiegley01296292011-04-08 18:41:53 +00006244 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6245 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006246 return ResultTy;
6247 }
Eli Friedman16c209612009-08-23 00:27:47 +00006248 // C99 6.5.9p2 and C99 6.5.8p2
6249 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6250 RCanPointeeTy.getUnqualifiedType())) {
6251 // Valid unless a relational comparison of function pointers
6252 if (isRelational && LCanPointeeTy->isFunctionType()) {
6253 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006254 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006255 }
6256 } else if (!isRelational &&
6257 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6258 // Valid unless comparison between non-null pointer and function pointer
6259 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6260 && !LHSIsNull && !RHSIsNull) {
6261 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006262 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006263 }
6264 } else {
6265 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006266 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006267 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006268 }
John McCall7684dde2011-03-11 04:25:25 +00006269 if (LCanPointeeTy != RCanPointeeTy) {
6270 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006271 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006272 else
John Wiegley01296292011-04-08 18:41:53 +00006273 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006274 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006275 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006276 }
Mike Stump11289f42009-09-09 15:08:12 +00006277
Sebastian Redl576fd422009-05-10 18:38:11 +00006278 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006279 // Comparison of nullptr_t with itself.
6280 if (lType->isNullPtrType() && rType->isNullPtrType())
6281 return ResultTy;
6282
Mike Stump11289f42009-09-09 15:08:12 +00006283 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006284 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006285 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006286 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006287 (!isRelational &&
6288 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006289 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006290 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006291 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006292 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006293 return ResultTy;
6294 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006295 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006296 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006297 (!isRelational &&
6298 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006299 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006300 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006301 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006302 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006303 return ResultTy;
6304 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006305
6306 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006307 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006308 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6309 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006310 // In addition, pointers to members can be compared, or a pointer to
6311 // member and a null pointer constant. Pointer to member conversions
6312 // (4.11) and qualification conversions (4.4) are performed to bring
6313 // them to a common type. If one operand is a null pointer constant,
6314 // the common type is the type of the other operand. Otherwise, the
6315 // common type is a pointer to member type similar (4.4) to the type
6316 // of one of the operands, with a cv-qualification signature (4.4)
6317 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006318 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006319 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006320 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006321 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006322 if (T.isNull()) {
6323 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006324 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006325 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006326 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006327 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006328 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006329 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006330 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006331 }
Mike Stump11289f42009-09-09 15:08:12 +00006332
John Wiegley01296292011-04-08 18:41:53 +00006333 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6334 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006335 return ResultTy;
6336 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006337
6338 // Handle scoped enumeration types specifically, since they don't promote
6339 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006340 if (lex.get()->getType()->isEnumeralType() &&
6341 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006342 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006343 }
Mike Stump11289f42009-09-09 15:08:12 +00006344
Steve Naroff081c7422008-09-04 15:10:53 +00006345 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006346 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006347 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6348 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006349
Steve Naroff081c7422008-09-04 15:10:53 +00006350 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006351 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006352 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006353 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006354 }
John Wiegley01296292011-04-08 18:41:53 +00006355 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006356 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006357 }
John Wiegley01296292011-04-08 18:41:53 +00006358
Steve Naroffe18f94c2008-09-28 01:11:11 +00006359 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006360 if (!isRelational
6361 && ((lType->isBlockPointerType() && rType->isPointerType())
6362 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006363 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006364 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006365 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006366 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006367 ->getPointeeType()->isVoidType())))
6368 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006369 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006370 }
John McCall7684dde2011-03-11 04:25:25 +00006371 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006372 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006373 else
John Wiegley01296292011-04-08 18:41:53 +00006374 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006375 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006376 }
Steve Naroff081c7422008-09-04 15:10:53 +00006377
John McCall7684dde2011-03-11 04:25:25 +00006378 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6379 const PointerType *LPT = lType->getAs<PointerType>();
6380 const PointerType *RPT = rType->getAs<PointerType>();
6381 if (LPT || RPT) {
6382 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6383 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006384
Steve Naroff753567f2008-11-17 19:49:16 +00006385 if (!LPtrToVoid && !RPtrToVoid &&
6386 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006387 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006388 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006389 }
John McCall7684dde2011-03-11 04:25:25 +00006390 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006391 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006392 else
John Wiegley01296292011-04-08 18:41:53 +00006393 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006394 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006395 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006396 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006397 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006398 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006399 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006400 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006401 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006402 else
John Wiegley01296292011-04-08 18:41:53 +00006403 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006404 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006405 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006406 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006407 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6408 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006409 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006410 bool isError = false;
6411 if ((LHSIsNull && lType->isIntegerType()) ||
6412 (RHSIsNull && rType->isIntegerType())) {
6413 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006414 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006415 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006416 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006417 else if (getLangOptions().CPlusPlus) {
6418 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6419 isError = true;
6420 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006421 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006422
Chris Lattnerd99bd522009-08-23 00:03:44 +00006423 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006424 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006425 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006426 if (isError)
6427 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006428 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006429
6430 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006431 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006432 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006433 else
John Wiegley01296292011-04-08 18:41:53 +00006434 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006435 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006436 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006437 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006438
Steve Naroff4b191572008-09-04 16:56:14 +00006439 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006440 if (!isRelational && RHSIsNull
6441 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006442 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006443 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006444 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006445 if (!isRelational && LHSIsNull
6446 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006447 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006448 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006449 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006450
Chris Lattner326f7572008-11-18 01:30:42 +00006451 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006452}
6453
Nate Begeman191a6b12008-07-14 18:02:46 +00006454/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006455/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006456/// like a scalar comparison, a vector comparison produces a vector of integer
6457/// types.
John Wiegley01296292011-04-08 18:41:53 +00006458QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006459 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006460 bool isRelational) {
6461 // Check to make sure we're operating on vectors of the same type and width,
6462 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006463 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006464 if (vType.isNull())
6465 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006466
John Wiegley01296292011-04-08 18:41:53 +00006467 QualType lType = lex.get()->getType();
6468 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006469
Anton Yartsev530deb92011-03-27 15:36:07 +00006470 // If AltiVec, the comparison results in a numeric type, i.e.
6471 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006472 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006473 return Context.getLogicalOperationType();
6474
Nate Begeman191a6b12008-07-14 18:02:46 +00006475 // For non-floating point types, check for self-comparisons of the form
6476 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6477 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006478 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006479 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6480 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006481 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006482 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006483 PDiag(diag::warn_comparison_always)
6484 << 0 // self-
6485 << 2 // "a constant"
6486 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006487 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006488
Nate Begeman191a6b12008-07-14 18:02:46 +00006489 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006490 if (!isRelational && lType->hasFloatingRepresentation()) {
6491 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006492 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006493 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006494
Nate Begeman191a6b12008-07-14 18:02:46 +00006495 // Return the type for the comparison, which is the same as vector type for
6496 // integer vectors, or an integer type of identical size and number of
6497 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006498 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006499 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006500
John McCall9dd450b2009-09-21 23:43:11 +00006501 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006502 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006503 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006504 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006505 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006506 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6507
Mike Stump4e1f26a2009-02-19 03:04:26 +00006508 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006509 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006510 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6511}
6512
Steve Naroff218bc2b2007-05-04 21:54:46 +00006513inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006514 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6515 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6516 if (lex.get()->getType()->hasIntegerRepresentation() &&
6517 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006518 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006519
6520 return InvalidOperands(Loc, lex, rex);
6521 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006522
John Wiegley01296292011-04-08 18:41:53 +00006523 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6524 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6525 if (lexResult.isInvalid() || rexResult.isInvalid())
6526 return QualType();
6527 lex = lexResult.take();
6528 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
John Wiegley01296292011-04-08 18:41:53 +00006530 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6531 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006532 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006533 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006534}
6535
Steve Naroff218bc2b2007-05-04 21:54:46 +00006536inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006537 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006538
6539 // Diagnose cases where the user write a logical and/or but probably meant a
6540 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6541 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006542 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6543 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006544 // Don't warn in macros or template instantiations.
6545 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006546 // If the RHS can be constant folded, and if it constant folds to something
6547 // that isn't 0 or 1 (which indicate a potential logical operation that
6548 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006549 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006550 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006551 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6552 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6553 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6554 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6555 << rex.get()->getSourceRange()
6556 << (Opc == BO_LAnd ? "&&" : "||")
6557 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006558 }
6559 }
Chris Lattner8406c512010-07-13 19:41:32 +00006560
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006561 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006562 lex = UsualUnaryConversions(lex.take());
6563 if (lex.isInvalid())
6564 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006565
John Wiegley01296292011-04-08 18:41:53 +00006566 rex = UsualUnaryConversions(rex.take());
6567 if (rex.isInvalid())
6568 return QualType();
6569
6570 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006571 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006572
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006573 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006574 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006575
John McCall4a2429a2010-06-04 00:29:51 +00006576 // The following is safe because we only use this method for
6577 // non-overloadable operands.
6578
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006579 // C++ [expr.log.and]p1
6580 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006581 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006582 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6583 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006584 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006585 lex = move(lexRes);
6586
6587 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6588 if (rexRes.isInvalid())
6589 return InvalidOperands(Loc, lex, rex);
6590 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006591
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006592 // C++ [expr.log.and]p2
6593 // C++ [expr.log.or]p2
6594 // The result is a bool.
6595 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006596}
6597
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006598/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6599/// is a read-only property; return true if so. A readonly property expression
6600/// depends on various declarations and thus must be treated specially.
6601///
Mike Stump11289f42009-09-09 15:08:12 +00006602static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006603 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6604 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006605 if (PropExpr->isImplicitProperty()) return false;
6606
6607 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6608 QualType BaseType = PropExpr->isSuperReceiver() ?
6609 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006610 PropExpr->getBase()->getType();
6611
John McCallb7bd14f2010-12-02 01:19:52 +00006612 if (const ObjCObjectPointerType *OPT =
6613 BaseType->getAsObjCInterfacePointerType())
6614 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6615 if (S.isPropertyReadonly(PDecl, IFace))
6616 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006617 }
6618 return false;
6619}
6620
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006621static bool IsConstProperty(Expr *E, Sema &S) {
6622 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6623 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6624 if (PropExpr->isImplicitProperty()) return false;
6625
6626 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6627 QualType T = PDecl->getType();
6628 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006629 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006630 CanQualType CT = S.Context.getCanonicalType(T);
6631 return CT.isConstQualified();
6632 }
6633 return false;
6634}
6635
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006636static bool IsReadonlyMessage(Expr *E, Sema &S) {
6637 if (E->getStmtClass() != Expr::MemberExprClass)
6638 return false;
6639 const MemberExpr *ME = cast<MemberExpr>(E);
6640 NamedDecl *Member = ME->getMemberDecl();
6641 if (isa<FieldDecl>(Member)) {
6642 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6643 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6644 return false;
6645 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6646 }
6647 return false;
6648}
6649
Chris Lattner30bd3272008-11-18 01:22:49 +00006650/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6651/// emit an error and return true. If so, return false.
6652static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006653 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006654 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006655 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006656 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6657 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006658 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6659 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006660 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6661 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006662 if (IsLV == Expr::MLV_Valid)
6663 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006664
Chris Lattner30bd3272008-11-18 01:22:49 +00006665 unsigned Diag = 0;
6666 bool NeedType = false;
6667 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006668 case Expr::MLV_ConstQualified:
6669 Diag = diag::err_typecheck_assign_const;
6670
John McCalld4631322011-06-17 06:42:21 +00006671 // In ARC, use some specialized diagnostics for occasions where we
6672 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006673 if (S.getLangOptions().ObjCAutoRefCount) {
6674 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6675 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6676 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6677
John McCalld4631322011-06-17 06:42:21 +00006678 // Use the normal diagnostic if it's pseudo-__strong but the
6679 // user actually wrote 'const'.
6680 if (var->isARCPseudoStrong() &&
6681 (!var->getTypeSourceInfo() ||
6682 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6683 // There are two pseudo-strong cases:
6684 // - self
John McCall31168b02011-06-15 23:02:42 +00006685 ObjCMethodDecl *method = S.getCurMethodDecl();
6686 if (method && var == method->getSelfDecl())
6687 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006688
6689 // - fast enumeration variables
6690 else
John McCall31168b02011-06-15 23:02:42 +00006691 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006692
John McCall31168b02011-06-15 23:02:42 +00006693 SourceRange Assign;
6694 if (Loc != OrigLoc)
6695 Assign = SourceRange(OrigLoc, OrigLoc);
6696 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6697 // We need to preserve the AST regardless, so migration tool
6698 // can do its job.
6699 return false;
6700 }
6701 }
6702 }
6703
6704 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006705 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006706 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6707 NeedType = true;
6708 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006709 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006710 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6711 NeedType = true;
6712 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006713 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006714 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6715 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006716 case Expr::MLV_Valid:
6717 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006718 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006719 case Expr::MLV_MemberFunction:
6720 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006721 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6722 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006723 case Expr::MLV_IncompleteType:
6724 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006725 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006726 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006727 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006728 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006729 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6730 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006731 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006732 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6733 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006734 case Expr::MLV_ReadonlyProperty:
6735 Diag = diag::error_readonly_property_assignment;
6736 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006737 case Expr::MLV_NoSetterProperty:
6738 Diag = diag::error_nosetter_property_assignment;
6739 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006740 case Expr::MLV_InvalidMessageExpression:
6741 Diag = diag::error_readonly_message_assignment;
6742 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006743 case Expr::MLV_SubObjCPropertySetting:
6744 Diag = diag::error_no_subobject_property_setting;
6745 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006746 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006747
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006748 SourceRange Assign;
6749 if (Loc != OrigLoc)
6750 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006751 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006752 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006753 else
Mike Stump11289f42009-09-09 15:08:12 +00006754 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006755 return true;
6756}
6757
6758
6759
6760// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006761QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006762 SourceLocation Loc,
6763 QualType CompoundType) {
6764 // Verify that LHS is a modifiable lvalue, and emit error if not.
6765 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006766 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006767
6768 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006769 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006770 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006771 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006772 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006773 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006774 if (LHS->getObjectKind() == OK_ObjCProperty) {
6775 ExprResult LHSResult = Owned(LHS);
6776 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6777 if (LHSResult.isInvalid())
6778 return QualType();
6779 LHS = LHSResult.take();
6780 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006781 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006782 if (RHS.isInvalid())
6783 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006784 // Special case of NSObject attributes on c-style pointer types.
6785 if (ConvTy == IncompatiblePointer &&
6786 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006787 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006788 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006789 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006790 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006791
John McCall7decc9e2010-11-18 06:31:45 +00006792 if (ConvTy == Compatible &&
6793 getLangOptions().ObjCNonFragileABI &&
6794 LHSType->isObjCObjectType())
6795 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6796 << LHSType;
6797
Chris Lattnerea714382008-08-21 18:04:13 +00006798 // If the RHS is a unary plus or minus, check to see if they = and + are
6799 // right next to each other. If so, the user may have typo'd "x =+ 4"
6800 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006801 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006802 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6803 RHSCheck = ICE->getSubExpr();
6804 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006805 if ((UO->getOpcode() == UO_Plus ||
6806 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006807 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006808 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006809 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6810 // And there is a space or other character before the subexpr of the
6811 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006812 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6813 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006814 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006815 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006816 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006817 }
Chris Lattnerea714382008-08-21 18:04:13 +00006818 }
John McCall31168b02011-06-15 23:02:42 +00006819
6820 if (ConvTy == Compatible) {
6821 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6822 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006823 else if (getLangOptions().ObjCAutoRefCount)
6824 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006825 }
Chris Lattnerea714382008-08-21 18:04:13 +00006826 } else {
6827 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006828 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006829 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006830
Chris Lattner326f7572008-11-18 01:30:42 +00006831 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006832 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006833 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006834
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006835 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006836 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006837 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006838
Steve Naroff98cf3e92007-06-06 18:38:38 +00006839 // C99 6.5.16p3: The type of an assignment expression is the type of the
6840 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006841 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006842 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6843 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006844 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006845 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006846 return (getLangOptions().CPlusPlus
6847 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006848}
6849
Chris Lattner326f7572008-11-18 01:30:42 +00006850// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006851static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006852 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006853 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006854
John McCall3aef3d82011-04-10 19:13:55 +00006855 LHS = S.CheckPlaceholderExpr(LHS.take());
6856 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006857 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006858 return QualType();
6859
John McCall73d36182010-10-12 07:14:40 +00006860 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6861 // operands, but not unary promotions.
6862 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006863
John McCall34376a62010-12-04 03:47:34 +00006864 // So we treat the LHS as a ignored value, and in C++ we allow the
6865 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006866 LHS = S.IgnoredValueConversions(LHS.take());
6867 if (LHS.isInvalid())
6868 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006869
6870 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006871 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6872 if (RHS.isInvalid())
6873 return QualType();
6874 if (!RHS.get()->getType()->isVoidType())
6875 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006876 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006877
John Wiegley01296292011-04-08 18:41:53 +00006878 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006879}
6880
Steve Naroff7a5af782007-07-13 16:58:59 +00006881/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6882/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006883static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6884 ExprValueKind &VK,
6885 SourceLocation OpLoc,
6886 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006887 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006888 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006889
Chris Lattner6b0cf142008-11-21 07:05:48 +00006890 QualType ResType = Op->getType();
6891 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006892
John McCall4bc41ae2010-11-18 19:01:18 +00006893 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006894 // Decrement of bool is not allowed.
6895 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006896 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006897 return QualType();
6898 }
6899 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006900 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006901 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006902 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006903 } else if (ResType->isAnyPointerType()) {
6904 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006905
Chris Lattner6b0cf142008-11-21 07:05:48 +00006906 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006907 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006908 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006909
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006910 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006911 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6912 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006913 << PointeeTy << Op->getSourceRange();
6914 return QualType();
6915 }
Eli Friedman090addd2010-01-03 00:20:48 +00006916 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006917 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006918 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006919 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006920 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006921 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006922 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006923 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6924 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006925 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6926 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006927 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006928 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006929 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006930 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006931 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006932 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006933 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006934 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006935 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006936 // In C++, a prefix increment is the same type as the operand. Otherwise
6937 // (in C or with postfix), the increment is the unqualified type of the
6938 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006939 if (isPrefix && S.getLangOptions().CPlusPlus) {
6940 VK = VK_LValue;
6941 return ResType;
6942 } else {
6943 VK = VK_RValue;
6944 return ResType.getUnqualifiedType();
6945 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006946}
6947
John Wiegley01296292011-04-08 18:41:53 +00006948ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006949 assert(E->getValueKind() == VK_LValue &&
6950 E->getObjectKind() == OK_ObjCProperty);
6951 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6952
Douglas Gregor33823722011-06-11 01:09:30 +00006953 QualType T = E->getType();
6954 QualType ReceiverType;
6955 if (PRE->isObjectReceiver())
6956 ReceiverType = PRE->getBase()->getType();
6957 else if (PRE->isSuperReceiver())
6958 ReceiverType = PRE->getSuperReceiverType();
6959 else
6960 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6961
John McCall34376a62010-12-04 03:47:34 +00006962 ExprValueKind VK = VK_RValue;
6963 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006964 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006965 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006966 T = getMessageSendResultType(ReceiverType, GetterMethod,
6967 PRE->isClassReceiver(),
6968 PRE->isSuperReceiver());
6969 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006970 }
6971 else {
6972 Diag(PRE->getLocation(), diag::err_getter_not_found)
6973 << PRE->getBase()->getType();
6974 }
John McCall34376a62010-12-04 03:47:34 +00006975 }
Douglas Gregor33823722011-06-11 01:09:30 +00006976
6977 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00006978 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00006979
6980 ExprResult Result = MaybeBindToTemporary(E);
6981 if (!Result.isInvalid())
6982 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00006983
6984 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00006985}
6986
John Wiegley01296292011-04-08 18:41:53 +00006987void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
6988 assert(LHS.get()->getValueKind() == VK_LValue &&
6989 LHS.get()->getObjectKind() == OK_ObjCProperty);
6990 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00006991
John McCall31168b02011-06-15 23:02:42 +00006992 bool Consumed = false;
6993
John Wiegley01296292011-04-08 18:41:53 +00006994 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00006995 // If using property-dot syntax notation for assignment, and there is a
6996 // setter, RHS expression is being passed to the setter argument. So,
6997 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00006998 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00006999 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7000 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007001 Consumed = (getLangOptions().ObjCAutoRefCount &&
7002 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007003
7004 // Otherwise, if the getter returns an l-value, just call that.
7005 } else {
John Wiegley01296292011-04-08 18:41:53 +00007006 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007007 ExprValueKind VK = Expr::getValueKindForType(Result);
7008 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007009 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7010 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007011 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007012 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007013 }
John McCall31168b02011-06-15 23:02:42 +00007014 } else if (getLangOptions().ObjCAutoRefCount) {
7015 const ObjCMethodDecl *setter
7016 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7017 if (setter) {
7018 ObjCMethodDecl::param_iterator P = setter->param_begin();
7019 LHSTy = (*P)->getType();
7020 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7021 }
John McCall34376a62010-12-04 03:47:34 +00007022 }
7023
John McCall31168b02011-06-15 23:02:42 +00007024 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7025 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007026 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007027 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007028 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007029 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007030 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007031 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7032 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7033 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007034 }
7035}
7036
7037
Anders Carlsson806700f2008-02-01 07:15:58 +00007038/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007039/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007040/// where the declaration is needed for type checking. We only need to
7041/// handle cases when the expression references a function designator
7042/// or is an lvalue. Here are some examples:
7043/// - &(x) => x
7044/// - &*****f => f for f a function designator.
7045/// - &s.xx => s
7046/// - &s.zz[1].yy -> s, if zz is an array
7047/// - *(x + 1) -> x, if x is an array
7048/// - &"123"[2] -> 0
7049/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007050static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007051 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007052 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007053 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007054 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007055 // If this is an arrow operator, the address is an offset from
7056 // the base's value, so the object the base refers to is
7057 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007058 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007059 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007060 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007061 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007062 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007063 // FIXME: This code shouldn't be necessary! We should catch the implicit
7064 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007065 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7066 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7067 if (ICE->getSubExpr()->getType()->isArrayType())
7068 return getPrimaryDecl(ICE->getSubExpr());
7069 }
7070 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007071 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007072 case Stmt::UnaryOperatorClass: {
7073 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007074
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007075 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007076 case UO_Real:
7077 case UO_Imag:
7078 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007079 return getPrimaryDecl(UO->getSubExpr());
7080 default:
7081 return 0;
7082 }
7083 }
Steve Naroff47500512007-04-19 23:00:49 +00007084 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007085 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007086 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007087 // If the result of an implicit cast is an l-value, we care about
7088 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007089 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007090 default:
7091 return 0;
7092 }
7093}
7094
7095/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007096/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007097/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007098/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007099/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007100/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007101/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007102static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7103 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007104 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007105 return S.Context.DependentTy;
7106 if (OrigOp->getType() == S.Context.OverloadTy)
7107 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007108 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7109 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007110 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7111 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7112 << OrigOp->getSourceRange();
7113 return QualType();
7114 }
John McCall8d08b9b2010-08-27 09:08:28 +00007115
John McCall2979fe02011-04-12 00:42:48 +00007116 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007117
John McCall8d08b9b2010-08-27 09:08:28 +00007118 // Make sure to ignore parentheses in subsequent checks
7119 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007120
John McCall4bc41ae2010-11-18 19:01:18 +00007121 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007122 // Implement C99-only parts of addressof rules.
7123 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007124 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007125 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7126 // (assuming the deref expression is valid).
7127 return uOp->getSubExpr()->getType();
7128 }
7129 // Technically, there should be a check for array subscript
7130 // expressions here, but the result of one is always an lvalue anyway.
7131 }
John McCallf3a88602011-02-03 08:15:49 +00007132 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007133 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007134
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007135 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007136 bool sfinae = S.isSFINAEContext();
7137 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7138 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007139 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007140 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007141 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007142 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007143 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007144 } else if (lval == Expr::LV_MemberFunction) {
7145 // If it's an instance method, make a member pointer.
7146 // The expression must have exactly the form &A::foo.
7147
7148 // If the underlying expression isn't a decl ref, give up.
7149 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007150 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007151 << OrigOp->getSourceRange();
7152 return QualType();
7153 }
7154 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7155 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7156
7157 // The id-expression was parenthesized.
7158 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007159 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007160 << OrigOp->getSourceRange();
7161
7162 // The method was named without a qualifier.
7163 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007164 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007165 << op->getSourceRange();
7166 }
7167
John McCall4bc41ae2010-11-18 19:01:18 +00007168 return S.Context.getMemberPointerType(op->getType(),
7169 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007170 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007171 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007172 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007173 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007174 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007175 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007176 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007177 return QualType();
7178 }
John McCall086a4642010-11-24 05:12:34 +00007179 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007180 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007181 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007182 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007183 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007184 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007185 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007186 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007187 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007188 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007189 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007190 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007191 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007192 << "property expression" << op->getSourceRange();
7193 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007194 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007195 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007196 // with the register storage-class specifier.
7197 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007198 // in C++ it is not error to take address of a register
7199 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007200 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007201 !S.getLangOptions().CPlusPlus) {
7202 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007203 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007204 return QualType();
7205 }
John McCalld14a8642009-11-21 08:51:07 +00007206 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007207 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007208 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007209 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007210 // Could be a pointer to member, though, if there is an explicit
7211 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007212 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007213 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007214 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007215 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007216 S.Diag(OpLoc,
7217 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007218 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007219 return QualType();
7220 }
Mike Stump11289f42009-09-09 15:08:12 +00007221
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007222 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7223 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007224 return S.Context.getMemberPointerType(op->getType(),
7225 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007226 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007227 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007228 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007229 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007230 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007231
Eli Friedmance7f9002009-05-16 23:27:50 +00007232 if (lval == Expr::LV_IncompleteVoidType) {
7233 // Taking the address of a void variable is technically illegal, but we
7234 // allow it in cases which are otherwise valid.
7235 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007236 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007237 }
7238
Steve Naroff47500512007-04-19 23:00:49 +00007239 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007240 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007241 return S.Context.getObjCObjectPointerType(op->getType());
7242 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007243}
7244
Chris Lattner9156f1b2010-07-05 19:17:26 +00007245/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007246static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7247 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007248 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007249 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007250
John Wiegley01296292011-04-08 18:41:53 +00007251 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7252 if (ConvResult.isInvalid())
7253 return QualType();
7254 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007255 QualType OpTy = Op->getType();
7256 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007257
7258 if (isa<CXXReinterpretCastExpr>(Op)) {
7259 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7260 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7261 Op->getSourceRange());
7262 }
7263
Chris Lattner9156f1b2010-07-05 19:17:26 +00007264 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7265 // is an incomplete type or void. It would be possible to warn about
7266 // dereferencing a void pointer, but it's completely well-defined, and such a
7267 // warning is unlikely to catch any mistakes.
7268 if (const PointerType *PT = OpTy->getAs<PointerType>())
7269 Result = PT->getPointeeType();
7270 else if (const ObjCObjectPointerType *OPT =
7271 OpTy->getAs<ObjCObjectPointerType>())
7272 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007273 else {
John McCall3aef3d82011-04-10 19:13:55 +00007274 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007275 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007276 if (PR.take() != Op)
7277 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007278 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007279
Chris Lattner9156f1b2010-07-05 19:17:26 +00007280 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007281 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007282 << OpTy << Op->getSourceRange();
7283 return QualType();
7284 }
John McCall4bc41ae2010-11-18 19:01:18 +00007285
7286 // Dereferences are usually l-values...
7287 VK = VK_LValue;
7288
7289 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007290 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007291 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007292
7293 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007294}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007295
John McCalle3027922010-08-25 11:45:40 +00007296static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007297 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007298 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007299 switch (Kind) {
7300 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007301 case tok::periodstar: Opc = BO_PtrMemD; break;
7302 case tok::arrowstar: Opc = BO_PtrMemI; break;
7303 case tok::star: Opc = BO_Mul; break;
7304 case tok::slash: Opc = BO_Div; break;
7305 case tok::percent: Opc = BO_Rem; break;
7306 case tok::plus: Opc = BO_Add; break;
7307 case tok::minus: Opc = BO_Sub; break;
7308 case tok::lessless: Opc = BO_Shl; break;
7309 case tok::greatergreater: Opc = BO_Shr; break;
7310 case tok::lessequal: Opc = BO_LE; break;
7311 case tok::less: Opc = BO_LT; break;
7312 case tok::greaterequal: Opc = BO_GE; break;
7313 case tok::greater: Opc = BO_GT; break;
7314 case tok::exclaimequal: Opc = BO_NE; break;
7315 case tok::equalequal: Opc = BO_EQ; break;
7316 case tok::amp: Opc = BO_And; break;
7317 case tok::caret: Opc = BO_Xor; break;
7318 case tok::pipe: Opc = BO_Or; break;
7319 case tok::ampamp: Opc = BO_LAnd; break;
7320 case tok::pipepipe: Opc = BO_LOr; break;
7321 case tok::equal: Opc = BO_Assign; break;
7322 case tok::starequal: Opc = BO_MulAssign; break;
7323 case tok::slashequal: Opc = BO_DivAssign; break;
7324 case tok::percentequal: Opc = BO_RemAssign; break;
7325 case tok::plusequal: Opc = BO_AddAssign; break;
7326 case tok::minusequal: Opc = BO_SubAssign; break;
7327 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7328 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7329 case tok::ampequal: Opc = BO_AndAssign; break;
7330 case tok::caretequal: Opc = BO_XorAssign; break;
7331 case tok::pipeequal: Opc = BO_OrAssign; break;
7332 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007333 }
7334 return Opc;
7335}
7336
John McCalle3027922010-08-25 11:45:40 +00007337static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007338 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007339 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007340 switch (Kind) {
7341 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007342 case tok::plusplus: Opc = UO_PreInc; break;
7343 case tok::minusminus: Opc = UO_PreDec; break;
7344 case tok::amp: Opc = UO_AddrOf; break;
7345 case tok::star: Opc = UO_Deref; break;
7346 case tok::plus: Opc = UO_Plus; break;
7347 case tok::minus: Opc = UO_Minus; break;
7348 case tok::tilde: Opc = UO_Not; break;
7349 case tok::exclaim: Opc = UO_LNot; break;
7350 case tok::kw___real: Opc = UO_Real; break;
7351 case tok::kw___imag: Opc = UO_Imag; break;
7352 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007353 }
7354 return Opc;
7355}
7356
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007357/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7358/// This warning is only emitted for builtin assignment operations. It is also
7359/// suppressed in the event of macro expansions.
7360static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7361 SourceLocation OpLoc) {
7362 if (!S.ActiveTemplateInstantiations.empty())
7363 return;
7364 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7365 return;
7366 lhs = lhs->IgnoreParenImpCasts();
7367 rhs = rhs->IgnoreParenImpCasts();
7368 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7369 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7370 if (!LeftDeclRef || !RightDeclRef ||
7371 LeftDeclRef->getLocation().isMacroID() ||
7372 RightDeclRef->getLocation().isMacroID())
7373 return;
7374 const ValueDecl *LeftDecl =
7375 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7376 const ValueDecl *RightDecl =
7377 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7378 if (LeftDecl != RightDecl)
7379 return;
7380 if (LeftDecl->getType().isVolatileQualified())
7381 return;
7382 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7383 if (RefTy->getPointeeType().isVolatileQualified())
7384 return;
7385
7386 S.Diag(OpLoc, diag::warn_self_assignment)
7387 << LeftDeclRef->getType()
7388 << lhs->getSourceRange() << rhs->getSourceRange();
7389}
7390
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007391/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7392/// operator @p Opc at location @c TokLoc. This routine only supports
7393/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007394ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007395 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007396 Expr *lhsExpr, Expr *rhsExpr) {
7397 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007398 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007399 // The following two variables are used for compound assignment operators
7400 QualType CompLHSTy; // Type of LHS after promotions for computation
7401 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007402 ExprValueKind VK = VK_RValue;
7403 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007404
Douglas Gregor1beec452011-03-12 01:48:56 +00007405 // Check if a 'foo<int>' involved in a binary op, identifies a single
7406 // function unambiguously (i.e. an lvalue ala 13.4)
7407 // But since an assignment can trigger target based overload, exclude it in
7408 // our blind search. i.e:
7409 // template<class T> void f(); template<class T, class U> void f(U);
7410 // f<int> == 0; // resolve f<int> blindly
7411 // void (*p)(int); p = f<int>; // resolve f<int> using target
7412 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007413 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007414 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007415 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007416
John McCall3aef3d82011-04-10 19:13:55 +00007417 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007418 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007419 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007420 }
7421
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007422 // The canonical way to check for a GNU null is with isNullPointerConstant,
7423 // but we use a bit of a hack here for speed; this is a relatively
7424 // hot path, and isNullPointerConstant is slow.
7425 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7426 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007427
7428 // Detect when a NULL constant is used improperly in an expression. These
7429 // are mainly cases where the null pointer is used as an integer instead
7430 // of a pointer.
7431 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007432 // Avoid analyzing cases where the result will either be invalid (and
7433 // diagnosed as such) or entirely valid and not something to warn about.
7434 QualType LeftType = lhs.get()->getType();
7435 QualType RightType = rhs.get()->getType();
7436 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7437 !LeftType->isFunctionType() &&
7438 !RightType->isBlockPointerType() &&
7439 !RightType->isMemberPointerType() &&
7440 !RightType->isFunctionType()) {
7441 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7442 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7443 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7444 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7445 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7446 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7447 // These are the operations that would not make sense with a null pointer
7448 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007449 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007450 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7451 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7452 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7453 Opc == BO_EQ || Opc == BO_NE) {
7454 // These are the operations that would not make sense with a null pointer
7455 // if the other expression the other expression is not a pointer.
7456 if (LeftNull != RightNull &&
7457 !LeftType->isAnyPointerType() &&
7458 !LeftType->canDecayToPointerType() &&
7459 !RightType->isAnyPointerType() &&
7460 !RightType->canDecayToPointerType()) {
7461 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7462 << (LeftNull ? lhs.get()->getSourceRange()
7463 : rhs.get()->getSourceRange());
7464 }
Richard Trieu701fb362011-06-16 21:36:56 +00007465 }
7466 }
7467 }
7468
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007469 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007470 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007471 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007472 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007473 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7474 VK = lhs.get()->getValueKind();
7475 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007476 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007477 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007478 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007479 break;
John McCalle3027922010-08-25 11:45:40 +00007480 case BO_PtrMemD:
7481 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007482 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007483 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007484 break;
John McCalle3027922010-08-25 11:45:40 +00007485 case BO_Mul:
7486 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007487 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007488 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007489 break;
John McCalle3027922010-08-25 11:45:40 +00007490 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007491 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7492 break;
John McCalle3027922010-08-25 11:45:40 +00007493 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007494 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7495 break;
John McCalle3027922010-08-25 11:45:40 +00007496 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007497 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7498 break;
John McCalle3027922010-08-25 11:45:40 +00007499 case BO_Shl:
7500 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007501 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007502 break;
John McCalle3027922010-08-25 11:45:40 +00007503 case BO_LE:
7504 case BO_LT:
7505 case BO_GE:
7506 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007507 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007508 break;
John McCalle3027922010-08-25 11:45:40 +00007509 case BO_EQ:
7510 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007511 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007512 break;
John McCalle3027922010-08-25 11:45:40 +00007513 case BO_And:
7514 case BO_Xor:
7515 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007516 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7517 break;
John McCalle3027922010-08-25 11:45:40 +00007518 case BO_LAnd:
7519 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007520 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007521 break;
John McCalle3027922010-08-25 11:45:40 +00007522 case BO_MulAssign:
7523 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007524 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007525 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007526 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007527 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7528 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007529 break;
John McCalle3027922010-08-25 11:45:40 +00007530 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007531 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7532 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007533 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7534 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007535 break;
John McCalle3027922010-08-25 11:45:40 +00007536 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007537 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007538 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7539 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007540 break;
John McCalle3027922010-08-25 11:45:40 +00007541 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007542 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007543 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7544 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007545 break;
John McCalle3027922010-08-25 11:45:40 +00007546 case BO_ShlAssign:
7547 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007548 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007549 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007550 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7551 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007552 break;
John McCalle3027922010-08-25 11:45:40 +00007553 case BO_AndAssign:
7554 case BO_XorAssign:
7555 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007556 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7557 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007558 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7559 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007560 break;
John McCalle3027922010-08-25 11:45:40 +00007561 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007562 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007563 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7564 VK = rhs.get()->getValueKind();
7565 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007566 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007567 break;
7568 }
John Wiegley01296292011-04-08 18:41:53 +00007569 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007570 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007571 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007572 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7573 ResultTy, VK, OK, OpLoc));
7574 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007575 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007576 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007577 }
John Wiegley01296292011-04-08 18:41:53 +00007578 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7579 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007580 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007581}
7582
Sebastian Redl44615072009-10-27 12:10:02 +00007583/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7584/// operators are mixed in a way that suggests that the programmer forgot that
7585/// comparison operators have higher precedence. The most typical example of
7586/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007587static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007588 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007589 typedef BinaryOperator BinOp;
7590 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7591 rhsopc = static_cast<BinOp::Opcode>(-1);
7592 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007593 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007594 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007595 rhsopc = BO->getOpcode();
7596
7597 // Subs are not binary operators.
7598 if (lhsopc == -1 && rhsopc == -1)
7599 return;
7600
7601 // Bitwise operations are sometimes used as eager logical ops.
7602 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007603 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7604 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007605 return;
7606
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007607 if (BinOp::isComparisonOp(lhsopc)) {
7608 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7609 << SourceRange(lhs->getLocStart(), OpLoc)
7610 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007611 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007612 Self.PDiag(diag::note_precedence_bitwise_silence)
7613 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007614 lhs->getSourceRange());
7615 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007616 Self.PDiag(diag::note_precedence_bitwise_first)
7617 << BinOp::getOpcodeStr(Opc),
7618 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007619 } else if (BinOp::isComparisonOp(rhsopc)) {
7620 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7621 << SourceRange(OpLoc, rhs->getLocEnd())
7622 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007623 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007624 Self.PDiag(diag::note_precedence_bitwise_silence)
7625 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007626 rhs->getSourceRange());
7627 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007628 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007629 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007630 SourceRange(lhs->getLocStart(),
7631 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007632 }
Sebastian Redl43028242009-10-26 15:24:15 +00007633}
7634
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007635/// \brief It accepts a '&' expr that is inside a '|' one.
7636/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7637/// in parentheses.
7638static void
7639EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7640 BinaryOperator *Bop) {
7641 assert(Bop->getOpcode() == BO_And);
7642 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7643 << Bop->getSourceRange() << OpLoc;
7644 SuggestParentheses(Self, Bop->getOperatorLoc(),
7645 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7646 Bop->getSourceRange());
7647}
7648
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007649/// \brief It accepts a '&&' expr that is inside a '||' one.
7650/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7651/// in parentheses.
7652static void
7653EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007654 BinaryOperator *Bop) {
7655 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007656 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7657 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007658 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007659 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007660 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007661}
7662
7663/// \brief Returns true if the given expression can be evaluated as a constant
7664/// 'true'.
7665static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7666 bool Res;
7667 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7668}
7669
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007670/// \brief Returns true if the given expression can be evaluated as a constant
7671/// 'false'.
7672static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7673 bool Res;
7674 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7675}
7676
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007677/// \brief Look for '&&' in the left hand of a '||' expr.
7678static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007679 Expr *OrLHS, Expr *OrRHS) {
7680 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007681 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007682 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7683 if (EvaluatesAsFalse(S, OrRHS))
7684 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007685 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7686 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7687 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7688 } else if (Bop->getOpcode() == BO_LOr) {
7689 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7690 // If it's "a || b && 1 || c" we didn't warn earlier for
7691 // "a || b && 1", but warn now.
7692 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7693 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7694 }
7695 }
7696 }
7697}
7698
7699/// \brief Look for '&&' in the right hand of a '||' expr.
7700static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007701 Expr *OrLHS, Expr *OrRHS) {
7702 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007703 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007704 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7705 if (EvaluatesAsFalse(S, OrLHS))
7706 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007707 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7708 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7709 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007710 }
7711 }
7712}
7713
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007714/// \brief Look for '&' in the left or right hand of a '|' expr.
7715static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7716 Expr *OrArg) {
7717 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7718 if (Bop->getOpcode() == BO_And)
7719 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7720 }
7721}
7722
Sebastian Redl43028242009-10-26 15:24:15 +00007723/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007724/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007725static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007726 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007727 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007728 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007729 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7730
7731 // Diagnose "arg1 & arg2 | arg3"
7732 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7733 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7734 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7735 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007736
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007737 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7738 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007739 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007740 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7741 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007742 }
Sebastian Redl43028242009-10-26 15:24:15 +00007743}
7744
Steve Naroff218bc2b2007-05-04 21:54:46 +00007745// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007746ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007747 tok::TokenKind Kind,
7748 Expr *lhs, Expr *rhs) {
7749 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007750 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7751 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007752
Sebastian Redl43028242009-10-26 15:24:15 +00007753 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7754 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7755
Douglas Gregor5287f092009-11-05 00:51:44 +00007756 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7757}
7758
John McCalldadc5752010-08-24 06:29:42 +00007759ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007760 BinaryOperatorKind Opc,
7761 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007762 if (getLangOptions().CPlusPlus) {
7763 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007764
John McCall622114c2010-12-06 05:26:58 +00007765 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7766 UseBuiltinOperator = false;
7767 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7768 UseBuiltinOperator = true;
7769 } else {
7770 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7771 !rhs->getType()->isOverloadableType();
7772 }
7773
7774 if (!UseBuiltinOperator) {
7775 // Find all of the overloaded operators visible from this
7776 // point. We perform both an operator-name lookup from the local
7777 // scope and an argument-dependent lookup based on the types of
7778 // the arguments.
7779 UnresolvedSet<16> Functions;
7780 OverloadedOperatorKind OverOp
7781 = BinaryOperator::getOverloadedOperator(Opc);
7782 if (S && OverOp != OO_None)
7783 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7784 Functions);
7785
7786 // Build the (potentially-overloaded, potentially-dependent)
7787 // binary operation.
7788 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7789 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007790 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007791
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007792 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007793 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007794}
7795
John McCalldadc5752010-08-24 06:29:42 +00007796ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007797 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007798 Expr *InputExpr) {
7799 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007800 ExprValueKind VK = VK_RValue;
7801 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007802 QualType resultType;
7803 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007804 case UO_PreInc:
7805 case UO_PreDec:
7806 case UO_PostInc:
7807 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007808 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007809 Opc == UO_PreInc ||
7810 Opc == UO_PostInc,
7811 Opc == UO_PreInc ||
7812 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007813 break;
John McCalle3027922010-08-25 11:45:40 +00007814 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007815 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007816 break;
John McCall31996342011-04-07 08:22:57 +00007817 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007818 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007819 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007820 Input = move(resolved);
7821 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7822 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007823 break;
John McCall31996342011-04-07 08:22:57 +00007824 }
John McCalle3027922010-08-25 11:45:40 +00007825 case UO_Plus:
7826 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007827 Input = UsualUnaryConversions(Input.take());
7828 if (Input.isInvalid()) return ExprError();
7829 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007830 if (resultType->isDependentType())
7831 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007832 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7833 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007834 break;
7835 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7836 resultType->isEnumeralType())
7837 break;
7838 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007839 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007840 resultType->isPointerType())
7841 break;
John McCall36226622010-10-12 02:09:17 +00007842 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007843 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007844 if (Input.isInvalid()) return ExprError();
7845 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007846 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007847
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007848 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007849 << resultType << Input.get()->getSourceRange());
7850
John McCalle3027922010-08-25 11:45:40 +00007851 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007852 Input = UsualUnaryConversions(Input.take());
7853 if (Input.isInvalid()) return ExprError();
7854 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007855 if (resultType->isDependentType())
7856 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007857 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7858 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7859 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007860 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007861 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007862 else if (resultType->hasIntegerRepresentation())
7863 break;
7864 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007865 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007866 if (Input.isInvalid()) return ExprError();
7867 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007868 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007870 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007871 }
Steve Naroff35d85152007-05-07 00:24:15 +00007872 break;
John Wiegley01296292011-04-08 18:41:53 +00007873
John McCalle3027922010-08-25 11:45:40 +00007874 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007875 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007876 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7877 if (Input.isInvalid()) return ExprError();
7878 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007879 if (resultType->isDependentType())
7880 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007881 if (resultType->isScalarType()) {
7882 // C99 6.5.3.3p1: ok, fallthrough;
7883 if (Context.getLangOptions().CPlusPlus) {
7884 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7885 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007886 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7887 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007888 }
John McCall36226622010-10-12 02:09:17 +00007889 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007890 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007891 if (Input.isInvalid()) return ExprError();
7892 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007893 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007894 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007895 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007896 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007897
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007898 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007899 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007900 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007901 break;
John McCalle3027922010-08-25 11:45:40 +00007902 case UO_Real:
7903 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007904 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007905 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007906 if (Input.isInvalid()) return ExprError();
7907 if (Input.get()->getValueKind() != VK_RValue &&
7908 Input.get()->getObjectKind() == OK_Ordinary)
7909 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007910 break;
John McCalle3027922010-08-25 11:45:40 +00007911 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007912 resultType = Input.get()->getType();
7913 VK = Input.get()->getValueKind();
7914 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007915 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007916 }
John Wiegley01296292011-04-08 18:41:53 +00007917 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007918 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007919
John Wiegley01296292011-04-08 18:41:53 +00007920 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007921 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007922}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007923
John McCalldadc5752010-08-24 06:29:42 +00007924ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007925 UnaryOperatorKind Opc,
7926 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007927 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007928 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007929 // Find all of the overloaded operators visible from this
7930 // point. We perform both an operator-name lookup from the local
7931 // scope and an argument-dependent lookup based on the types of
7932 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007933 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007934 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007935 if (S && OverOp != OO_None)
7936 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7937 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007938
John McCallb268a282010-08-23 23:25:46 +00007939 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007940 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007941
John McCallb268a282010-08-23 23:25:46 +00007942 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007943}
7944
Douglas Gregor5287f092009-11-05 00:51:44 +00007945// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007946ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007947 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007948 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007949}
7950
Steve Naroff66356bd2007-09-16 14:56:35 +00007951/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007952ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007953 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007954 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007955 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007956 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007957 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007958}
7959
John McCall31168b02011-06-15 23:02:42 +00007960/// Given the last statement in a statement-expression, check whether
7961/// the result is a producing expression (like a call to an
7962/// ns_returns_retained function) and, if so, rebuild it to hoist the
7963/// release out of the full-expression. Otherwise, return null.
7964/// Cannot fail.
7965static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7966 // Should always be wrapped with one of these.
7967 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7968 if (!cleanups) return 0;
7969
7970 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7971 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7972 return 0;
7973
7974 // Splice out the cast. This shouldn't modify any interesting
7975 // features of the statement.
7976 Expr *producer = cast->getSubExpr();
7977 assert(producer->getType() == cast->getType());
7978 assert(producer->getValueKind() == cast->getValueKind());
7979 cleanups->setSubExpr(producer);
7980 return cleanups;
7981}
7982
John McCalldadc5752010-08-24 06:29:42 +00007983ExprResult
John McCallb268a282010-08-23 23:25:46 +00007984Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007985 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007986 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7987 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7988
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007989 bool isFileScope
7990 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007991 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007992 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007993
Chris Lattner366727f2007-07-24 16:58:17 +00007994 // FIXME: there are a variety of strange constraints to enforce here, for
7995 // example, it is not possible to goto into a stmt expression apparently.
7996 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007997
Chris Lattner366727f2007-07-24 16:58:17 +00007998 // If there are sub stmts in the compound stmt, take the type of the last one
7999 // as the type of the stmtexpr.
8000 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008001 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008002 if (!Compound->body_empty()) {
8003 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008004 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008005 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008006 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8007 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008008 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008009 }
John McCall31168b02011-06-15 23:02:42 +00008010
John Wiegley01296292011-04-08 18:41:53 +00008011 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008012 // Do function/array conversion on the last expression, but not
8013 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008014 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8015 if (LastExpr.isInvalid())
8016 return ExprError();
8017 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008018
John Wiegley01296292011-04-08 18:41:53 +00008019 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008020 // In ARC, if the final expression ends in a consume, splice
8021 // the consume out and bind it later. In the alternate case
8022 // (when dealing with a retainable type), the result
8023 // initialization will create a produce. In both cases the
8024 // result will be +1, and we'll need to balance that out with
8025 // a bind.
8026 if (Expr *rebuiltLastStmt
8027 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8028 LastExpr = rebuiltLastStmt;
8029 } else {
8030 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008031 InitializedEntity::InitializeResult(LPLoc,
8032 Ty,
8033 false),
8034 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008035 LastExpr);
8036 }
8037
John Wiegley01296292011-04-08 18:41:53 +00008038 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008039 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008040 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008041 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008042 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008043 else
John Wiegley01296292011-04-08 18:41:53 +00008044 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008045 StmtExprMayBindToTemp = true;
8046 }
8047 }
8048 }
Chris Lattner944d3062008-07-26 19:51:01 +00008049 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008050
Eli Friedmanba961a92009-03-23 00:24:07 +00008051 // FIXME: Check that expression type is complete/non-abstract; statement
8052 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008053 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8054 if (StmtExprMayBindToTemp)
8055 return MaybeBindToTemporary(ResStmtExpr);
8056 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008057}
Steve Naroff78864672007-08-01 22:05:33 +00008058
John McCalldadc5752010-08-24 06:29:42 +00008059ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008060 TypeSourceInfo *TInfo,
8061 OffsetOfComponent *CompPtr,
8062 unsigned NumComponents,
8063 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008064 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008065 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008066 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008067
Chris Lattnerf17bd422007-08-30 17:45:32 +00008068 // We must have at least one component that refers to the type, and the first
8069 // one is known to be a field designator. Verify that the ArgTy represents
8070 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008071 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008072 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8073 << ArgTy << TypeRange);
8074
8075 // Type must be complete per C99 7.17p3 because a declaring a variable
8076 // with an incomplete type would be ill-formed.
8077 if (!Dependent
8078 && RequireCompleteType(BuiltinLoc, ArgTy,
8079 PDiag(diag::err_offsetof_incomplete_type)
8080 << TypeRange))
8081 return ExprError();
8082
Chris Lattner78502cf2007-08-31 21:49:13 +00008083 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8084 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008085 // FIXME: This diagnostic isn't actually visible because the location is in
8086 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008087 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008088 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8089 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008090
8091 bool DidWarnAboutNonPOD = false;
8092 QualType CurrentType = ArgTy;
8093 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8094 llvm::SmallVector<OffsetOfNode, 4> Comps;
8095 llvm::SmallVector<Expr*, 4> Exprs;
8096 for (unsigned i = 0; i != NumComponents; ++i) {
8097 const OffsetOfComponent &OC = CompPtr[i];
8098 if (OC.isBrackets) {
8099 // Offset of an array sub-field. TODO: Should we allow vector elements?
8100 if (!CurrentType->isDependentType()) {
8101 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8102 if(!AT)
8103 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8104 << CurrentType);
8105 CurrentType = AT->getElementType();
8106 } else
8107 CurrentType = Context.DependentTy;
8108
8109 // The expression must be an integral expression.
8110 // FIXME: An integral constant expression?
8111 Expr *Idx = static_cast<Expr*>(OC.U.E);
8112 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8113 !Idx->getType()->isIntegerType())
8114 return ExprError(Diag(Idx->getLocStart(),
8115 diag::err_typecheck_subscript_not_integer)
8116 << Idx->getSourceRange());
8117
8118 // Record this array index.
8119 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8120 Exprs.push_back(Idx);
8121 continue;
8122 }
8123
8124 // Offset of a field.
8125 if (CurrentType->isDependentType()) {
8126 // We have the offset of a field, but we can't look into the dependent
8127 // type. Just record the identifier of the field.
8128 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8129 CurrentType = Context.DependentTy;
8130 continue;
8131 }
8132
8133 // We need to have a complete type to look into.
8134 if (RequireCompleteType(OC.LocStart, CurrentType,
8135 diag::err_offsetof_incomplete_type))
8136 return ExprError();
8137
8138 // Look for the designated field.
8139 const RecordType *RC = CurrentType->getAs<RecordType>();
8140 if (!RC)
8141 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8142 << CurrentType);
8143 RecordDecl *RD = RC->getDecl();
8144
8145 // C++ [lib.support.types]p5:
8146 // The macro offsetof accepts a restricted set of type arguments in this
8147 // International Standard. type shall be a POD structure or a POD union
8148 // (clause 9).
8149 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8150 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008151 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008152 PDiag(diag::warn_offsetof_non_pod_type)
8153 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8154 << CurrentType))
8155 DidWarnAboutNonPOD = true;
8156 }
8157
8158 // Look for the field.
8159 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8160 LookupQualifiedName(R, RD);
8161 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008162 IndirectFieldDecl *IndirectMemberDecl = 0;
8163 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008164 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008165 MemberDecl = IndirectMemberDecl->getAnonField();
8166 }
8167
Douglas Gregor882211c2010-04-28 22:16:22 +00008168 if (!MemberDecl)
8169 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8170 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8171 OC.LocEnd));
8172
Douglas Gregor10982ea2010-04-28 22:36:06 +00008173 // C99 7.17p3:
8174 // (If the specified member is a bit-field, the behavior is undefined.)
8175 //
8176 // We diagnose this as an error.
8177 if (MemberDecl->getBitWidth()) {
8178 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8179 << MemberDecl->getDeclName()
8180 << SourceRange(BuiltinLoc, RParenLoc);
8181 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8182 return ExprError();
8183 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008184
8185 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008186 if (IndirectMemberDecl)
8187 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008188
Douglas Gregord1702062010-04-29 00:18:15 +00008189 // If the member was found in a base class, introduce OffsetOfNodes for
8190 // the base class indirections.
8191 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8192 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008193 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008194 CXXBasePath &Path = Paths.front();
8195 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8196 B != BEnd; ++B)
8197 Comps.push_back(OffsetOfNode(B->Base));
8198 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008199
Francois Pichet783dd6e2010-11-21 06:08:52 +00008200 if (IndirectMemberDecl) {
8201 for (IndirectFieldDecl::chain_iterator FI =
8202 IndirectMemberDecl->chain_begin(),
8203 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8204 assert(isa<FieldDecl>(*FI));
8205 Comps.push_back(OffsetOfNode(OC.LocStart,
8206 cast<FieldDecl>(*FI), OC.LocEnd));
8207 }
8208 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008209 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008210
Douglas Gregor882211c2010-04-28 22:16:22 +00008211 CurrentType = MemberDecl->getType().getNonReferenceType();
8212 }
8213
8214 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8215 TInfo, Comps.data(), Comps.size(),
8216 Exprs.data(), Exprs.size(), RParenLoc));
8217}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008218
John McCalldadc5752010-08-24 06:29:42 +00008219ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008220 SourceLocation BuiltinLoc,
8221 SourceLocation TypeLoc,
8222 ParsedType argty,
8223 OffsetOfComponent *CompPtr,
8224 unsigned NumComponents,
8225 SourceLocation RPLoc) {
8226
Douglas Gregor882211c2010-04-28 22:16:22 +00008227 TypeSourceInfo *ArgTInfo;
8228 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8229 if (ArgTy.isNull())
8230 return ExprError();
8231
Eli Friedman06dcfd92010-08-05 10:15:45 +00008232 if (!ArgTInfo)
8233 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8234
8235 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8236 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008237}
8238
8239
John McCalldadc5752010-08-24 06:29:42 +00008240ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008241 Expr *CondExpr,
8242 Expr *LHSExpr, Expr *RHSExpr,
8243 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008244 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8245
John McCall7decc9e2010-11-18 06:31:45 +00008246 ExprValueKind VK = VK_RValue;
8247 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008248 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008249 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008250 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008251 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008252 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008253 } else {
8254 // The conditional expression is required to be a constant expression.
8255 llvm::APSInt condEval(32);
8256 SourceLocation ExpLoc;
8257 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008258 return ExprError(Diag(ExpLoc,
8259 diag::err_typecheck_choose_expr_requires_constant)
8260 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008261
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008262 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008263 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8264
8265 resType = ActiveExpr->getType();
8266 ValueDependent = ActiveExpr->isValueDependent();
8267 VK = ActiveExpr->getValueKind();
8268 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008269 }
8270
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008271 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008272 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008273 resType->isDependentType(),
8274 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008275}
8276
Steve Naroffc540d662008-09-03 18:15:37 +00008277//===----------------------------------------------------------------------===//
8278// Clang Extensions.
8279//===----------------------------------------------------------------------===//
8280
8281/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008282void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008283 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8284 PushBlockScope(BlockScope, Block);
8285 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008286 if (BlockScope)
8287 PushDeclContext(BlockScope, Block);
8288 else
8289 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008290}
8291
Mike Stump82f071f2009-02-04 22:31:32 +00008292void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008293 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008294 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008295 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008296
John McCall8cb7bdf2010-06-04 23:28:52 +00008297 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008298 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008299
John McCall3882ace2011-01-05 12:14:39 +00008300 // GetTypeForDeclarator always produces a function type for a block
8301 // literal signature. Furthermore, it is always a FunctionProtoType
8302 // unless the function was written with a typedef.
8303 assert(T->isFunctionType() &&
8304 "GetTypeForDeclarator made a non-function block signature");
8305
8306 // Look for an explicit signature in that function type.
8307 FunctionProtoTypeLoc ExplicitSignature;
8308
8309 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8310 if (isa<FunctionProtoTypeLoc>(tmp)) {
8311 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8312
8313 // Check whether that explicit signature was synthesized by
8314 // GetTypeForDeclarator. If so, don't save that as part of the
8315 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008316 if (ExplicitSignature.getLocalRangeBegin() ==
8317 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008318 // This would be much cheaper if we stored TypeLocs instead of
8319 // TypeSourceInfos.
8320 TypeLoc Result = ExplicitSignature.getResultLoc();
8321 unsigned Size = Result.getFullDataSize();
8322 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8323 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8324
8325 ExplicitSignature = FunctionProtoTypeLoc();
8326 }
John McCalla3ccba02010-06-04 11:21:44 +00008327 }
Mike Stump11289f42009-09-09 15:08:12 +00008328
John McCall3882ace2011-01-05 12:14:39 +00008329 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8330 CurBlock->FunctionType = T;
8331
8332 const FunctionType *Fn = T->getAs<FunctionType>();
8333 QualType RetTy = Fn->getResultType();
8334 bool isVariadic =
8335 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8336
John McCall8e346702010-06-04 19:02:56 +00008337 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008338
John McCalla3ccba02010-06-04 11:21:44 +00008339 // Don't allow returning a objc interface by value.
8340 if (RetTy->isObjCObjectType()) {
8341 Diag(ParamInfo.getSourceRange().getBegin(),
8342 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8343 return;
8344 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008345
John McCalla3ccba02010-06-04 11:21:44 +00008346 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008347 // return type. TODO: what should we do with declarators like:
8348 // ^ * { ... }
8349 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008350 if (RetTy != Context.DependentTy)
8351 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008352
John McCalla3ccba02010-06-04 11:21:44 +00008353 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008354 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008355 if (ExplicitSignature) {
8356 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8357 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008358 if (Param->getIdentifier() == 0 &&
8359 !Param->isImplicit() &&
8360 !Param->isInvalidDecl() &&
8361 !getLangOptions().CPlusPlus)
8362 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008363 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008364 }
John McCalla3ccba02010-06-04 11:21:44 +00008365
8366 // Fake up parameter variables if we have a typedef, like
8367 // ^ fntype { ... }
8368 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8369 for (FunctionProtoType::arg_type_iterator
8370 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8371 ParmVarDecl *Param =
8372 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8373 ParamInfo.getSourceRange().getBegin(),
8374 *I);
John McCall8e346702010-06-04 19:02:56 +00008375 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008376 }
Steve Naroffc540d662008-09-03 18:15:37 +00008377 }
John McCalla3ccba02010-06-04 11:21:44 +00008378
John McCall8e346702010-06-04 19:02:56 +00008379 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008380 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008381 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008382 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8383 CurBlock->TheDecl->param_end(),
8384 /*CheckParameterNames=*/false);
8385 }
8386
John McCalla3ccba02010-06-04 11:21:44 +00008387 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008388 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008389
John McCall8e346702010-06-04 19:02:56 +00008390 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008391 Diag(ParamInfo.getAttributes()->getLoc(),
8392 diag::warn_attribute_sentinel_not_variadic) << 1;
8393 // FIXME: remove the attribute.
8394 }
8395
8396 // Put the parameter variables in scope. We can bail out immediately
8397 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008398 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008399 return;
8400
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008401 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008402 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8403 (*AI)->setOwningFunction(CurBlock->TheDecl);
8404
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008405 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008406 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008407 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008408
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008409 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008410 }
John McCallf7b2fb52010-01-22 00:28:27 +00008411 }
Steve Naroffc540d662008-09-03 18:15:37 +00008412}
8413
8414/// ActOnBlockError - If there is an error parsing a block, this callback
8415/// is invoked to pop the information about the block from the action impl.
8416void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008417 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008418 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008419 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008420}
8421
8422/// ActOnBlockStmtExpr - This is called when the body of a block statement
8423/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008424ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008425 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008426 // If blocks are disabled, emit an error.
8427 if (!LangOpts.Blocks)
8428 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008429
Douglas Gregor9a28e842010-03-01 23:15:13 +00008430 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008431
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008432 PopDeclContext();
8433
Steve Naroffc540d662008-09-03 18:15:37 +00008434 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008435 if (!BSI->ReturnType.isNull())
8436 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008437
Mike Stump3bf1ab42009-07-28 22:04:01 +00008438 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008439 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008440
John McCallc63de662011-02-02 13:00:07 +00008441 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008442 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8443 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008444
John McCall8e346702010-06-04 19:02:56 +00008445 // If the user wrote a function type in some form, try to use that.
8446 if (!BSI->FunctionType.isNull()) {
8447 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8448
8449 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8450 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8451
8452 // Turn protoless block types into nullary block types.
8453 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008454 FunctionProtoType::ExtProtoInfo EPI;
8455 EPI.ExtInfo = Ext;
8456 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008457
8458 // Otherwise, if we don't need to change anything about the function type,
8459 // preserve its sugar structure.
8460 } else if (FTy->getResultType() == RetTy &&
8461 (!NoReturn || FTy->getNoReturnAttr())) {
8462 BlockTy = BSI->FunctionType;
8463
8464 // Otherwise, make the minimal modifications to the function type.
8465 } else {
8466 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008467 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8468 EPI.TypeQuals = 0; // FIXME: silently?
8469 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008470 BlockTy = Context.getFunctionType(RetTy,
8471 FPT->arg_type_begin(),
8472 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008473 EPI);
John McCall8e346702010-06-04 19:02:56 +00008474 }
8475
8476 // If we don't have a function type, just build one from nothing.
8477 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008478 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008479 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008480 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008481 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008482
John McCall8e346702010-06-04 19:02:56 +00008483 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8484 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008485 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008486
Chris Lattner45542ea2009-04-19 05:28:12 +00008487 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008488 if (getCurFunction()->NeedsScopeChecking() &&
8489 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008490 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008491
Chris Lattner60f84492011-02-17 23:58:47 +00008492 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008493
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008494 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8495 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8496 const VarDecl *variable = ci->getVariable();
8497 QualType T = variable->getType();
8498 QualType::DestructionKind destructKind = T.isDestructedType();
8499 if (destructKind != QualType::DK_none)
8500 getCurFunction()->setHasBranchProtectedScope();
8501 }
8502
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008503 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8504 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8505 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8506
Douglas Gregor9a28e842010-03-01 23:15:13 +00008507 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008508}
8509
John McCalldadc5752010-08-24 06:29:42 +00008510ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008511 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008512 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008513 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008514 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008515 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008516}
8517
John McCalldadc5752010-08-24 06:29:42 +00008518ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008519 Expr *E, TypeSourceInfo *TInfo,
8520 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008521 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008522
Eli Friedman121ba0c2008-08-09 23:32:40 +00008523 // Get the va_list type
8524 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008525 if (VaListType->isArrayType()) {
8526 // Deal with implicit array decay; for example, on x86-64,
8527 // va_list is an array, but it's supposed to decay to
8528 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008529 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008530 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008531 ExprResult Result = UsualUnaryConversions(E);
8532 if (Result.isInvalid())
8533 return ExprError();
8534 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008535 } else {
8536 // Otherwise, the va_list argument must be an l-value because
8537 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008538 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008539 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008540 return ExprError();
8541 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008542
Douglas Gregorad3150c2009-05-19 23:10:31 +00008543 if (!E->isTypeDependent() &&
8544 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008545 return ExprError(Diag(E->getLocStart(),
8546 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008547 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008549
David Majnemerc75d1a12011-06-14 05:17:32 +00008550 if (!TInfo->getType()->isDependentType()) {
8551 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8552 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8553 << TInfo->getTypeLoc().getSourceRange()))
8554 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008555
David Majnemerc75d1a12011-06-14 05:17:32 +00008556 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8557 TInfo->getType(),
8558 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8559 << TInfo->getTypeLoc().getSourceRange()))
8560 return ExprError();
8561
John McCall31168b02011-06-15 23:02:42 +00008562 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00008563 Diag(TInfo->getTypeLoc().getBeginLoc(),
8564 diag::warn_second_parameter_to_va_arg_not_pod)
8565 << TInfo->getType()
8566 << TInfo->getTypeLoc().getSourceRange();
Eli Friedman6290ae42011-07-11 21:45:59 +00008567
8568 // Check for va_arg where arguments of the given type will be promoted
8569 // (i.e. this va_arg is guaranteed to have undefined behavior).
8570 QualType PromoteType;
8571 if (TInfo->getType()->isPromotableIntegerType()) {
8572 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8573 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8574 PromoteType = QualType();
8575 }
8576 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8577 PromoteType = Context.DoubleTy;
8578 if (!PromoteType.isNull())
8579 Diag(TInfo->getTypeLoc().getBeginLoc(),
8580 diag::warn_second_parameter_to_va_arg_never_compatible)
8581 << TInfo->getType()
8582 << PromoteType
8583 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008584 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008585
Abramo Bagnara27db2392010-08-10 10:06:15 +00008586 QualType T = TInfo->getType().getNonLValueExprType(Context);
8587 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008588}
8589
John McCalldadc5752010-08-24 06:29:42 +00008590ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008591 // The type of __null will be int or long, depending on the size of
8592 // pointers on the target.
8593 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008594 unsigned pw = Context.Target.getPointerWidth(0);
8595 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008596 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008597 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008598 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008599 else if (pw == Context.Target.getLongLongWidth())
8600 Ty = Context.LongLongTy;
8601 else {
8602 assert(!"I don't know size of pointer!");
8603 Ty = Context.IntTy;
8604 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008605
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008606 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008607}
8608
Alexis Huntc46382e2010-04-28 23:02:27 +00008609static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008610 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008611 if (!SemaRef.getLangOptions().ObjC1)
8612 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008613
Anders Carlssonace5d072009-11-10 04:46:30 +00008614 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8615 if (!PT)
8616 return;
8617
8618 // Check if the destination is of type 'id'.
8619 if (!PT->isObjCIdType()) {
8620 // Check if the destination is the 'NSString' interface.
8621 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8622 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8623 return;
8624 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008625
Anders Carlssonace5d072009-11-10 04:46:30 +00008626 // Strip off any parens and casts.
8627 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8628 if (!SL || SL->isWide())
8629 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008630
Douglas Gregora771f462010-03-31 17:46:05 +00008631 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008632}
8633
Chris Lattner9bad62c2008-01-04 18:04:52 +00008634bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8635 SourceLocation Loc,
8636 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008637 Expr *SrcExpr, AssignmentAction Action,
8638 bool *Complained) {
8639 if (Complained)
8640 *Complained = false;
8641
Chris Lattner9bad62c2008-01-04 18:04:52 +00008642 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008643 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008644 bool isInvalid = false;
8645 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008646 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008647
Chris Lattner9bad62c2008-01-04 18:04:52 +00008648 switch (ConvTy) {
8649 default: assert(0 && "Unknown conversion type");
8650 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008651 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008652 DiagKind = diag::ext_typecheck_convert_pointer_int;
8653 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008654 case IntToPointer:
8655 DiagKind = diag::ext_typecheck_convert_int_pointer;
8656 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008657 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008658 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008659 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008660 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8661 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +00008662 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008663 case IncompatiblePointerSign:
8664 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8665 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008666 case FunctionVoidPointer:
8667 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8668 break;
John McCall4fff8f62011-02-01 00:10:29 +00008669 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008670 // Perform array-to-pointer decay if necessary.
8671 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8672
John McCall4fff8f62011-02-01 00:10:29 +00008673 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8674 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8675 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8676 DiagKind = diag::err_typecheck_incompatible_address_space;
8677 break;
John McCall31168b02011-06-15 23:02:42 +00008678
8679
8680 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008681 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008682 break;
John McCall4fff8f62011-02-01 00:10:29 +00008683 }
8684
8685 llvm_unreachable("unknown error case for discarding qualifiers!");
8686 // fallthrough
8687 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008688 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008689 // If the qualifiers lost were because we were applying the
8690 // (deprecated) C++ conversion from a string literal to a char*
8691 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8692 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008693 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008694 // bit of refactoring (so that the second argument is an
8695 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008696 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008697 // C++ semantics.
8698 if (getLangOptions().CPlusPlus &&
8699 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8700 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008701 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8702 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008703 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008704 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008705 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008706 case IntToBlockPointer:
8707 DiagKind = diag::err_int_to_block_pointer;
8708 break;
8709 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008710 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008711 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008712 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008713 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008714 // it can give a more specific diagnostic.
8715 DiagKind = diag::warn_incompatible_qualified_id;
8716 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008717 case IncompatibleVectors:
8718 DiagKind = diag::warn_incompatible_vectors;
8719 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008720 case IncompatibleObjCWeakRef:
8721 DiagKind = diag::err_arc_weak_unavailable_assign;
8722 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008723 case Incompatible:
8724 DiagKind = diag::err_typecheck_convert_incompatible;
8725 isInvalid = true;
8726 break;
8727 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008728
Douglas Gregorc68e1402010-04-09 00:35:39 +00008729 QualType FirstType, SecondType;
8730 switch (Action) {
8731 case AA_Assigning:
8732 case AA_Initializing:
8733 // The destination type comes first.
8734 FirstType = DstType;
8735 SecondType = SrcType;
8736 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008737
Douglas Gregorc68e1402010-04-09 00:35:39 +00008738 case AA_Returning:
8739 case AA_Passing:
8740 case AA_Converting:
8741 case AA_Sending:
8742 case AA_Casting:
8743 // The source type comes first.
8744 FirstType = SrcType;
8745 SecondType = DstType;
8746 break;
8747 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008748
Douglas Gregorc68e1402010-04-09 00:35:39 +00008749 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008750 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +00008751 if (CheckInferredResultType)
8752 EmitRelatedResultTypeNote(SrcExpr);
8753
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008754 if (Complained)
8755 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008756 return isInvalid;
8757}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008758
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008759bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008760 llvm::APSInt ICEResult;
8761 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8762 if (Result)
8763 *Result = ICEResult;
8764 return false;
8765 }
8766
Anders Carlssone54e8a12008-11-30 19:50:32 +00008767 Expr::EvalResult EvalResult;
8768
Mike Stump4e1f26a2009-02-19 03:04:26 +00008769 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008770 EvalResult.HasSideEffects) {
8771 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8772
8773 if (EvalResult.Diag) {
8774 // We only show the note if it's not the usual "invalid subexpression"
8775 // or if it's actually in a subexpression.
8776 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8777 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8778 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8779 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008780
Anders Carlssone54e8a12008-11-30 19:50:32 +00008781 return true;
8782 }
8783
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008784 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8785 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008786
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008787 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008788 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8789 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008790 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008791
Anders Carlssone54e8a12008-11-30 19:50:32 +00008792 if (Result)
8793 *Result = EvalResult.Val.getInt();
8794 return false;
8795}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008796
Douglas Gregorff790f12009-11-26 00:44:06 +00008797void
Mike Stump11289f42009-09-09 15:08:12 +00008798Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008799 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008800 ExpressionEvaluationContextRecord(NewContext,
8801 ExprTemporaries.size(),
8802 ExprNeedsCleanups));
8803 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008804}
8805
Mike Stump11289f42009-09-09 15:08:12 +00008806void
Douglas Gregorff790f12009-11-26 00:44:06 +00008807Sema::PopExpressionEvaluationContext() {
8808 // Pop the current expression evaluation context off the stack.
8809 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8810 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008811
Douglas Gregorfab31f42009-12-12 07:57:52 +00008812 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8813 if (Rec.PotentiallyReferenced) {
8814 // Mark any remaining declarations in the current position of the stack
8815 // as "referenced". If they were not meant to be referenced, semantic
8816 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008817 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008818 I = Rec.PotentiallyReferenced->begin(),
8819 IEnd = Rec.PotentiallyReferenced->end();
8820 I != IEnd; ++I)
8821 MarkDeclarationReferenced(I->first, I->second);
8822 }
8823
8824 if (Rec.PotentiallyDiagnosed) {
8825 // Emit any pending diagnostics.
8826 for (PotentiallyEmittedDiagnostics::iterator
8827 I = Rec.PotentiallyDiagnosed->begin(),
8828 IEnd = Rec.PotentiallyDiagnosed->end();
8829 I != IEnd; ++I)
8830 Diag(I->first, I->second);
8831 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008832 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008833
8834 // When are coming out of an unevaluated context, clear out any
8835 // temporaries that we may have created as part of the evaluation of
8836 // the expression in that context: they aren't relevant because they
8837 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008838 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008839 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8840 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008841 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8842
8843 // Otherwise, merge the contexts together.
8844 } else {
8845 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8846 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008847
8848 // Destroy the popped expression evaluation record.
8849 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008850}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008851
John McCall31168b02011-06-15 23:02:42 +00008852void Sema::DiscardCleanupsInEvaluationContext() {
8853 ExprTemporaries.erase(
8854 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8855 ExprTemporaries.end());
8856 ExprNeedsCleanups = false;
8857}
8858
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008859/// \brief Note that the given declaration was referenced in the source code.
8860///
8861/// This routine should be invoke whenever a given declaration is referenced
8862/// in the source code, and where that reference occurred. If this declaration
8863/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8864/// C99 6.9p3), then the declaration will be marked as used.
8865///
8866/// \param Loc the location where the declaration was referenced.
8867///
8868/// \param D the declaration that has been referenced by the source code.
8869void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8870 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008871
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008872 D->setReferenced();
8873
Douglas Gregorebada0772010-06-17 23:14:26 +00008874 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008875 return;
Mike Stump11289f42009-09-09 15:08:12 +00008876
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008877 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8878 // template or not. The reason for this is that unevaluated expressions
8879 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8880 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008881 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008882 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008883 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008884 return;
8885 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008886
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008887 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8888 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008889
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008890 // Do not mark anything as "used" within a dependent context; wait for
8891 // an instantiation.
8892 if (CurContext->isDependentContext())
8893 return;
Mike Stump11289f42009-09-09 15:08:12 +00008894
Douglas Gregorff790f12009-11-26 00:44:06 +00008895 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008896 case Unevaluated:
8897 // We are in an expression that is not potentially evaluated; do nothing.
8898 return;
Mike Stump11289f42009-09-09 15:08:12 +00008899
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008900 case PotentiallyEvaluated:
8901 // We are in a potentially-evaluated expression, so this declaration is
8902 // "used"; handle this below.
8903 break;
Mike Stump11289f42009-09-09 15:08:12 +00008904
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008905 case PotentiallyPotentiallyEvaluated:
8906 // We are in an expression that may be potentially evaluated; queue this
8907 // declaration reference until we know whether the expression is
8908 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008909 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008910 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008911
8912 case PotentiallyEvaluatedIfUsed:
8913 // Referenced declarations will only be used if the construct in the
8914 // containing expression is used.
8915 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008916 }
Mike Stump11289f42009-09-09 15:08:12 +00008917
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008918 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008919 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008920 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8921 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008922 return;
8923 if (!Constructor->isUsed(false))
8924 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008925 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008926 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008927 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00008928 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008929 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008930
Douglas Gregor88d292c2010-05-13 16:44:06 +00008931 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008932 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00008933 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008934 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008935 if (Destructor->isVirtual())
8936 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008937 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00008938 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008939 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008940 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008941 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008942 } else if (MethodDecl->isVirtual())
8943 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008944 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008945 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00008946 // Recursive functions should be marked when used from another function.
8947 if (CurContext == Function) return;
8948
Mike Stump11289f42009-09-09 15:08:12 +00008949 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008950 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008951 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008952 bool AlreadyInstantiated = false;
8953 if (FunctionTemplateSpecializationInfo *SpecInfo
8954 = Function->getTemplateSpecializationInfo()) {
8955 if (SpecInfo->getPointOfInstantiation().isInvalid())
8956 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008957 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008958 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008959 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008960 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008961 = Function->getMemberSpecializationInfo()) {
8962 if (MSInfo->getPointOfInstantiation().isInvalid())
8963 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008964 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008965 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008966 AlreadyInstantiated = true;
8967 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008968
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008969 if (!AlreadyInstantiated) {
8970 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8971 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8972 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8973 Loc));
8974 else
Chandler Carruth54080172010-08-25 08:44:16 +00008975 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008976 }
John McCall83779672011-02-19 02:53:41 +00008977 } else {
8978 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008979 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8980 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008981 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008982 MarkDeclarationReferenced(Loc, *i);
8983 }
John McCall83779672011-02-19 02:53:41 +00008984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008985
John McCall83779672011-02-19 02:53:41 +00008986 // Keep track of used but undefined functions.
8987 if (!Function->isPure() && !Function->hasBody() &&
8988 Function->getLinkage() != ExternalLinkage) {
8989 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
8990 if (old.isInvalid()) old = Loc;
8991 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008992
John McCall83779672011-02-19 02:53:41 +00008993 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008994 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008995 }
Mike Stump11289f42009-09-09 15:08:12 +00008996
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008997 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008998 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008999 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009000 Var->getInstantiatedFromStaticDataMember()) {
9001 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9002 assert(MSInfo && "Missing member specialization information?");
9003 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9004 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9005 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009006 // This is a modification of an existing AST node. Notify listeners.
9007 if (ASTMutationListener *L = getASTMutationListener())
9008 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009009 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009010 }
9011 }
Mike Stump11289f42009-09-09 15:08:12 +00009012
John McCall15dd4042011-02-21 19:25:48 +00009013 // Keep track of used but undefined variables. We make a hole in
9014 // the warning for static const data members with in-line
9015 // initializers.
John McCall83779672011-02-19 02:53:41 +00009016 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009017 && Var->getLinkage() != ExternalLinkage
9018 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009019 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9020 if (old.isInvalid()) old = Loc;
9021 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009022
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009023 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009024 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009025 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009026}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009027
Douglas Gregor5597ab42010-05-07 23:12:07 +00009028namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009029 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009030 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009031 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009032 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9033 Sema &S;
9034 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009035
Douglas Gregor5597ab42010-05-07 23:12:07 +00009036 public:
9037 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009038
Douglas Gregor5597ab42010-05-07 23:12:07 +00009039 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009040
9041 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9042 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009043 };
9044}
9045
Chandler Carruthaf80f662010-06-09 08:17:30 +00009046bool MarkReferencedDecls::TraverseTemplateArgument(
9047 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009048 if (Arg.getKind() == TemplateArgument::Declaration) {
9049 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9050 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009051
9052 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009053}
9054
Chandler Carruthaf80f662010-06-09 08:17:30 +00009055bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009056 if (ClassTemplateSpecializationDecl *Spec
9057 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9058 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009059 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009060 }
9061
Chandler Carruthc65667c2010-06-10 10:31:57 +00009062 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009063}
9064
9065void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9066 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009067 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009068}
9069
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009070namespace {
9071 /// \brief Helper class that marks all of the declarations referenced by
9072 /// potentially-evaluated subexpressions as "referenced".
9073 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9074 Sema &S;
9075
9076 public:
9077 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9078
9079 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9080
9081 void VisitDeclRefExpr(DeclRefExpr *E) {
9082 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9083 }
9084
9085 void VisitMemberExpr(MemberExpr *E) {
9086 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009087 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009088 }
9089
9090 void VisitCXXNewExpr(CXXNewExpr *E) {
9091 if (E->getConstructor())
9092 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9093 if (E->getOperatorNew())
9094 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9095 if (E->getOperatorDelete())
9096 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009097 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009098 }
9099
9100 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9101 if (E->getOperatorDelete())
9102 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009103 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9104 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9105 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9106 S.MarkDeclarationReferenced(E->getLocStart(),
9107 S.LookupDestructor(Record));
9108 }
9109
Douglas Gregor32b3de52010-09-11 23:32:50 +00009110 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009111 }
9112
9113 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9114 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009115 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009116 }
9117
9118 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9119 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9120 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009121
9122 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9123 Visit(E->getExpr());
9124 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009125 };
9126}
9127
9128/// \brief Mark any declarations that appear within this expression or any
9129/// potentially-evaluated subexpressions as "referenced".
9130void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9131 EvaluatedExprMarker(*this).Visit(E);
9132}
9133
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009134/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9135/// of the program being compiled.
9136///
9137/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009138/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009139/// possibility that the code will actually be executable. Code in sizeof()
9140/// expressions, code used only during overload resolution, etc., are not
9141/// potentially evaluated. This routine will suppress such diagnostics or,
9142/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009143/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009144/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009145///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009146/// This routine should be used for all diagnostics that describe the run-time
9147/// behavior of a program, such as passing a non-POD value through an ellipsis.
9148/// Failure to do so will likely result in spurious diagnostics or failures
9149/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009150bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009151 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009152 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009153 case Unevaluated:
9154 // The argument will never be evaluated, so don't complain.
9155 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009156
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009157 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009158 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009159 if (stmt && getCurFunctionOrMethodDecl()) {
9160 FunctionScopes.back()->PossiblyUnreachableDiags.
9161 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9162 }
9163 else
9164 Diag(Loc, PD);
9165
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009166 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009167
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009168 case PotentiallyPotentiallyEvaluated:
9169 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9170 break;
9171 }
9172
9173 return false;
9174}
9175
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009176bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9177 CallExpr *CE, FunctionDecl *FD) {
9178 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9179 return false;
9180
9181 PartialDiagnostic Note =
9182 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9183 << FD->getDeclName() : PDiag();
9184 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009185
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009186 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009187 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009188 PDiag(diag::err_call_function_incomplete_return)
9189 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009190 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009191 << CE->getSourceRange(),
9192 std::make_pair(NoteLoc, Note)))
9193 return true;
9194
9195 return false;
9196}
9197
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009198// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009199// will prevent this condition from triggering, which is what we want.
9200void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9201 SourceLocation Loc;
9202
John McCall0506e4a2009-11-11 02:41:58 +00009203 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009204 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009205
John McCalld5707ab2009-10-12 21:59:07 +00009206 if (isa<BinaryOperator>(E)) {
9207 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009208 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009209 return;
9210
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009211 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9212
John McCallb0e419e2009-11-12 00:06:05 +00009213 // Greylist some idioms by putting them into a warning subcategory.
9214 if (ObjCMessageExpr *ME
9215 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9216 Selector Sel = ME->getSelector();
9217
John McCallb0e419e2009-11-12 00:06:05 +00009218 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009219 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009220 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9221
9222 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009223 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009224 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9225 }
John McCall0506e4a2009-11-11 02:41:58 +00009226
John McCalld5707ab2009-10-12 21:59:07 +00009227 Loc = Op->getOperatorLoc();
9228 } else if (isa<CXXOperatorCallExpr>(E)) {
9229 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009230 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009231 return;
9232
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009233 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009234 Loc = Op->getOperatorLoc();
9235 } else {
9236 // Not an assignment.
9237 return;
9238 }
9239
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009240 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009241
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009242 SourceLocation Open = E->getSourceRange().getBegin();
9243 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9244 Diag(Loc, diag::note_condition_assign_silence)
9245 << FixItHint::CreateInsertion(Open, "(")
9246 << FixItHint::CreateInsertion(Close, ")");
9247
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009248 if (IsOrAssign)
9249 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9250 << FixItHint::CreateReplacement(Loc, "!=");
9251 else
9252 Diag(Loc, diag::note_condition_assign_to_comparison)
9253 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009254}
9255
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009256/// \brief Redundant parentheses over an equality comparison can indicate
9257/// that the user intended an assignment used as condition.
9258void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009259 // Don't warn if the parens came from a macro.
9260 SourceLocation parenLoc = parenE->getLocStart();
9261 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9262 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009263 // Don't warn for dependent expressions.
9264 if (parenE->isTypeDependent())
9265 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009266
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009267 Expr *E = parenE->IgnoreParens();
9268
9269 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009270 if (opE->getOpcode() == BO_EQ &&
9271 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9272 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009273 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009274
Ted Kremenekae022092011-02-02 02:20:30 +00009275 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009276 Diag(Loc, diag::note_equality_comparison_silence)
9277 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9278 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009279 Diag(Loc, diag::note_equality_comparison_to_assign)
9280 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009281 }
9282}
9283
John Wiegley01296292011-04-08 18:41:53 +00009284ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009285 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009286 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9287 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009288
John McCall0009fcc2011-04-26 20:42:42 +00009289 ExprResult result = CheckPlaceholderExpr(E);
9290 if (result.isInvalid()) return ExprError();
9291 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009292
John McCall0009fcc2011-04-26 20:42:42 +00009293 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009294 if (getLangOptions().CPlusPlus)
9295 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9296
John Wiegley01296292011-04-08 18:41:53 +00009297 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9298 if (ERes.isInvalid())
9299 return ExprError();
9300 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009301
9302 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009303 if (!T->isScalarType()) { // C99 6.8.4.1p1
9304 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9305 << T << E->getSourceRange();
9306 return ExprError();
9307 }
John McCalld5707ab2009-10-12 21:59:07 +00009308 }
9309
John Wiegley01296292011-04-08 18:41:53 +00009310 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009311}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009312
John McCalldadc5752010-08-24 06:29:42 +00009313ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9314 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009315 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009316 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009317
9318 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009319}
John McCall36e7fe32010-10-12 00:20:44 +00009320
John McCall31996342011-04-07 08:22:57 +00009321namespace {
John McCall2979fe02011-04-12 00:42:48 +00009322 /// A visitor for rebuilding a call to an __unknown_any expression
9323 /// to have an appropriate type.
9324 struct RebuildUnknownAnyFunction
9325 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9326
9327 Sema &S;
9328
9329 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9330
9331 ExprResult VisitStmt(Stmt *S) {
9332 llvm_unreachable("unexpected statement!");
9333 return ExprError();
9334 }
9335
9336 ExprResult VisitExpr(Expr *expr) {
9337 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9338 << expr->getSourceRange();
9339 return ExprError();
9340 }
9341
9342 /// Rebuild an expression which simply semantically wraps another
9343 /// expression which it shares the type and value kind of.
9344 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9345 ExprResult subResult = Visit(expr->getSubExpr());
9346 if (subResult.isInvalid()) return ExprError();
9347
9348 Expr *subExpr = subResult.take();
9349 expr->setSubExpr(subExpr);
9350 expr->setType(subExpr->getType());
9351 expr->setValueKind(subExpr->getValueKind());
9352 assert(expr->getObjectKind() == OK_Ordinary);
9353 return expr;
9354 }
9355
9356 ExprResult VisitParenExpr(ParenExpr *paren) {
9357 return rebuildSugarExpr(paren);
9358 }
9359
9360 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9361 return rebuildSugarExpr(op);
9362 }
9363
9364 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9365 ExprResult subResult = Visit(op->getSubExpr());
9366 if (subResult.isInvalid()) return ExprError();
9367
9368 Expr *subExpr = subResult.take();
9369 op->setSubExpr(subExpr);
9370 op->setType(S.Context.getPointerType(subExpr->getType()));
9371 assert(op->getValueKind() == VK_RValue);
9372 assert(op->getObjectKind() == OK_Ordinary);
9373 return op;
9374 }
9375
9376 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9377 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9378
9379 expr->setType(decl->getType());
9380
9381 assert(expr->getValueKind() == VK_RValue);
9382 if (S.getLangOptions().CPlusPlus &&
9383 !(isa<CXXMethodDecl>(decl) &&
9384 cast<CXXMethodDecl>(decl)->isInstance()))
9385 expr->setValueKind(VK_LValue);
9386
9387 return expr;
9388 }
9389
9390 ExprResult VisitMemberExpr(MemberExpr *mem) {
9391 return resolveDecl(mem, mem->getMemberDecl());
9392 }
9393
9394 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9395 return resolveDecl(ref, ref->getDecl());
9396 }
9397 };
9398}
9399
9400/// Given a function expression of unknown-any type, try to rebuild it
9401/// to have a function type.
9402static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9403 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9404 if (result.isInvalid()) return ExprError();
9405 return S.DefaultFunctionArrayConversion(result.take());
9406}
9407
9408namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009409 /// A visitor for rebuilding an expression of type __unknown_anytype
9410 /// into one which resolves the type directly on the referring
9411 /// expression. Strict preservation of the original source
9412 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009413 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009414 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009415
9416 Sema &S;
9417
9418 /// The current destination type.
9419 QualType DestType;
9420
9421 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9422 : S(S), DestType(castType) {}
9423
John McCall39439732011-04-09 22:50:59 +00009424 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009425 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009426 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009427 }
9428
John McCall2d2e8702011-04-11 07:02:50 +00009429 ExprResult VisitExpr(Expr *expr) {
9430 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9431 << expr->getSourceRange();
9432 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009433 }
9434
John McCall2d2e8702011-04-11 07:02:50 +00009435 ExprResult VisitCallExpr(CallExpr *call);
9436 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9437
John McCall39439732011-04-09 22:50:59 +00009438 /// Rebuild an expression which simply semantically wraps another
9439 /// expression which it shares the type and value kind of.
9440 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9441 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009442 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009443 Expr *subExpr = subResult.take();
9444 expr->setSubExpr(subExpr);
9445 expr->setType(subExpr->getType());
9446 expr->setValueKind(subExpr->getValueKind());
9447 assert(expr->getObjectKind() == OK_Ordinary);
9448 return expr;
9449 }
John McCall31996342011-04-07 08:22:57 +00009450
John McCall39439732011-04-09 22:50:59 +00009451 ExprResult VisitParenExpr(ParenExpr *paren) {
9452 return rebuildSugarExpr(paren);
9453 }
9454
9455 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9456 return rebuildSugarExpr(op);
9457 }
9458
John McCall2979fe02011-04-12 00:42:48 +00009459 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9460 const PointerType *ptr = DestType->getAs<PointerType>();
9461 if (!ptr) {
9462 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9463 << op->getSourceRange();
9464 return ExprError();
9465 }
9466 assert(op->getValueKind() == VK_RValue);
9467 assert(op->getObjectKind() == OK_Ordinary);
9468 op->setType(DestType);
9469
9470 // Build the sub-expression as if it were an object of the pointee type.
9471 DestType = ptr->getPointeeType();
9472 ExprResult subResult = Visit(op->getSubExpr());
9473 if (subResult.isInvalid()) return ExprError();
9474 op->setSubExpr(subResult.take());
9475 return op;
9476 }
9477
John McCall2d2e8702011-04-11 07:02:50 +00009478 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009479
John McCall2979fe02011-04-12 00:42:48 +00009480 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009481
John McCall2979fe02011-04-12 00:42:48 +00009482 ExprResult VisitMemberExpr(MemberExpr *mem) {
9483 return resolveDecl(mem, mem->getMemberDecl());
9484 }
John McCall39439732011-04-09 22:50:59 +00009485
9486 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009487 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009488 }
9489 };
9490}
9491
John McCall2d2e8702011-04-11 07:02:50 +00009492/// Rebuilds a call expression which yielded __unknown_anytype.
9493ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9494 Expr *callee = call->getCallee();
9495
9496 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009497 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009498 FK_FunctionPointer,
9499 FK_BlockPointer
9500 };
9501
9502 FnKind kind;
9503 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009504 if (type == S.Context.BoundMemberTy) {
9505 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9506 kind = FK_MemberFunction;
9507 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009508 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9509 type = ptr->getPointeeType();
9510 kind = FK_FunctionPointer;
9511 } else {
9512 type = type->castAs<BlockPointerType>()->getPointeeType();
9513 kind = FK_BlockPointer;
9514 }
9515 const FunctionType *fnType = type->castAs<FunctionType>();
9516
9517 // Verify that this is a legal result type of a function.
9518 if (DestType->isArrayType() || DestType->isFunctionType()) {
9519 unsigned diagID = diag::err_func_returning_array_function;
9520 if (kind == FK_BlockPointer)
9521 diagID = diag::err_block_returning_array_function;
9522
9523 S.Diag(call->getExprLoc(), diagID)
9524 << DestType->isFunctionType() << DestType;
9525 return ExprError();
9526 }
9527
9528 // Otherwise, go ahead and set DestType as the call's result.
9529 call->setType(DestType.getNonLValueExprType(S.Context));
9530 call->setValueKind(Expr::getValueKindForType(DestType));
9531 assert(call->getObjectKind() == OK_Ordinary);
9532
9533 // Rebuild the function type, replacing the result type with DestType.
9534 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9535 DestType = S.Context.getFunctionType(DestType,
9536 proto->arg_type_begin(),
9537 proto->getNumArgs(),
9538 proto->getExtProtoInfo());
9539 else
9540 DestType = S.Context.getFunctionNoProtoType(DestType,
9541 fnType->getExtInfo());
9542
9543 // Rebuild the appropriate pointer-to-function type.
9544 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009545 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009546 // Nothing to do.
9547 break;
9548
9549 case FK_FunctionPointer:
9550 DestType = S.Context.getPointerType(DestType);
9551 break;
9552
9553 case FK_BlockPointer:
9554 DestType = S.Context.getBlockPointerType(DestType);
9555 break;
9556 }
9557
9558 // Finally, we can recurse.
9559 ExprResult calleeResult = Visit(callee);
9560 if (!calleeResult.isUsable()) return ExprError();
9561 call->setCallee(calleeResult.take());
9562
9563 // Bind a temporary if necessary.
9564 return S.MaybeBindToTemporary(call);
9565}
9566
9567ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009568 // Verify that this is a legal result type of a call.
9569 if (DestType->isArrayType() || DestType->isFunctionType()) {
9570 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9571 << DestType->isFunctionType() << DestType;
9572 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009573 }
9574
John McCall3f4138c2011-07-13 17:56:40 +00009575 // Rewrite the method result type if available.
9576 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9577 assert(method->getResultType() == S.Context.UnknownAnyTy);
9578 method->setResultType(DestType);
9579 }
John McCall2979fe02011-04-12 00:42:48 +00009580
John McCall2d2e8702011-04-11 07:02:50 +00009581 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009582 msg->setType(DestType.getNonReferenceType());
9583 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009584
John McCall2979fe02011-04-12 00:42:48 +00009585 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009586}
9587
9588ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009589 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009590 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009591 assert(ice->getValueKind() == VK_RValue);
9592 assert(ice->getObjectKind() == OK_Ordinary);
9593
John McCall2979fe02011-04-12 00:42:48 +00009594 ice->setType(DestType);
9595
John McCall2d2e8702011-04-11 07:02:50 +00009596 // Rebuild the sub-expression as the pointee (function) type.
9597 DestType = DestType->castAs<PointerType>()->getPointeeType();
9598
9599 ExprResult result = Visit(ice->getSubExpr());
9600 if (!result.isUsable()) return ExprError();
9601
9602 ice->setSubExpr(result.take());
9603 return S.Owned(ice);
9604}
9605
John McCall2979fe02011-04-12 00:42:48 +00009606ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009607 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009608 QualType type = DestType;
9609
9610 // We know how to make this work for certain kinds of decls:
9611
9612 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009613 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009614 // This is true because FunctionDecls must always have function
9615 // type, so we can't be resolving the entire thing at once.
9616 assert(type->isFunctionType());
9617
John McCall4adb38c2011-04-27 00:36:17 +00009618 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9619 if (method->isInstance()) {
9620 valueKind = VK_RValue;
9621 type = S.Context.BoundMemberTy;
9622 }
9623
John McCall2d2e8702011-04-11 07:02:50 +00009624 // Function references aren't l-values in C.
9625 if (!S.getLangOptions().CPlusPlus)
9626 valueKind = VK_RValue;
9627
9628 // - variables
9629 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009630 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9631 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009632 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009633 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9634 << decl << expr->getSourceRange();
9635 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009636 }
9637
9638 // - nothing else
9639 } else {
9640 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9641 << decl << expr->getSourceRange();
9642 return ExprError();
9643 }
9644
John McCall2979fe02011-04-12 00:42:48 +00009645 decl->setType(DestType);
9646 expr->setType(type);
9647 expr->setValueKind(valueKind);
9648 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009649}
9650
John McCall31996342011-04-07 08:22:57 +00009651/// Check a cast of an unknown-any type. We intentionally only
9652/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009653ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9654 Expr *castExpr, CastKind &castKind,
9655 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009656 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009657 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9658 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009659
John McCall39439732011-04-09 22:50:59 +00009660 castExpr = result.take();
9661 VK = castExpr->getValueKind();
9662 castKind = CK_NoOp;
9663
9664 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009665}
9666
9667static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9668 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009669 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009670 while (true) {
9671 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009672 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009673 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009674 diagID = diag::err_uncasted_call_of_unknown_any;
9675 } else {
John McCall31996342011-04-07 08:22:57 +00009676 break;
John McCall2d2e8702011-04-11 07:02:50 +00009677 }
John McCall31996342011-04-07 08:22:57 +00009678 }
9679
John McCall2d2e8702011-04-11 07:02:50 +00009680 SourceLocation loc;
9681 NamedDecl *d;
9682 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9683 loc = ref->getLocation();
9684 d = ref->getDecl();
9685 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9686 loc = mem->getMemberLoc();
9687 d = mem->getMemberDecl();
9688 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9689 diagID = diag::err_uncasted_call_of_unknown_any;
9690 loc = msg->getSelectorLoc();
9691 d = msg->getMethodDecl();
9692 assert(d && "unknown method returning __unknown_any?");
9693 } else {
9694 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9695 << e->getSourceRange();
9696 return ExprError();
9697 }
9698
9699 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009700
9701 // Never recoverable.
9702 return ExprError();
9703}
9704
John McCall36e7fe32010-10-12 00:20:44 +00009705/// Check for operands with placeholder types and complain if found.
9706/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009707ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009708 // Placeholder types are always *exactly* the appropriate builtin type.
9709 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009710
John McCall31996342011-04-07 08:22:57 +00009711 // Overloaded expressions.
9712 if (type == Context.OverloadTy)
9713 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009714 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009715 QualType(),
9716 diag::err_ovl_unresolvable);
9717
John McCall0009fcc2011-04-26 20:42:42 +00009718 // Bound member functions.
9719 if (type == Context.BoundMemberTy) {
9720 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9721 << E->getSourceRange();
9722 return ExprError();
9723 }
9724
John McCall31996342011-04-07 08:22:57 +00009725 // Expressions of unknown type.
9726 if (type == Context.UnknownAnyTy)
9727 return diagnoseUnknownAnyExpr(*this, E);
9728
9729 assert(!type->isPlaceholderType());
9730 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009731}
Richard Trieu2c850c02011-04-21 21:44:26 +00009732
9733bool Sema::CheckCaseExpression(Expr *expr) {
9734 if (expr->isTypeDependent())
9735 return true;
9736 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9737 return expr->getType()->isIntegralOrEnumerationType();
9738 return false;
9739}