blob: 4a9b4bcfdf07999d46acb7886a2c49744e906ec0 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000042
David Chisnall9f57c292009-08-17 16:35:33 +000043
Douglas Gregor171c45a2009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor171c45a2009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000058///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000064 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000065 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000068 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith30482bc2011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000084 }
85
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000090 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 return true;
92 }
Douglas Gregorde681d42009-02-24 04:26:15 +000093 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000094
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000107 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
108 if (Message.empty()) {
109 if (!UnknownObjCClass)
110 Diag(Loc, diag::err_unavailable) << D->getDeclName();
111 else
112 Diag(Loc, diag::warn_unavailable_fwdclass_message)
113 << D->getDeclName();
114 }
115 else
116 Diag(Loc, diag::err_unavailable_message)
117 << D->getDeclName() << Message;
118 Diag(D->getLocation(), diag::note_unavailable_here)
119 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000120 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 break;
122 }
123
Anders Carlsson73067a02010-10-22 23:37:08 +0000124 // Warn if this is used but marked unused.
125 if (D->hasAttr<UnusedAttr>())
126 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
127
Douglas Gregor171c45a2009-02-18 21:56:37 +0000128 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000129}
130
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000131/// \brief Retrieve the message suffix that should be added to a
132/// diagnostic complaining about the given function being deleted or
133/// unavailable.
134std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
135 // FIXME: C++0x implicitly-deleted special member functions could be
136 // detected here so that we could improve diagnostics to say, e.g.,
137 // "base class 'A' had a deleted copy constructor".
138 if (FD->isDeleted())
139 return std::string();
140
141 std::string Message;
142 if (FD->getAvailability(&Message))
143 return ": " + Message;
144
145 return std::string();
146}
147
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000148/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000149/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000150/// attribute. It warns if call does not have the sentinel argument.
151///
152void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000153 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000154 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000155 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000157
158 // FIXME: In C++0x, if any of the arguments are parameter pack
159 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000160 int sentinelPos = attr->getSentinel();
161 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000162
Mike Stump87c57ac2009-05-16 07:39:55 +0000163 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
164 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000165 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000166 bool warnNotEnoughArgs = false;
167 int isMethod = 0;
168 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
169 // skip over named parameters.
170 ObjCMethodDecl::param_iterator P, E = MD->param_end();
171 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (P != E || i >= NumArgs);
178 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000179 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000180 // skip over named parameters.
181 ObjCMethodDecl::param_iterator P, E = FD->param_end();
182 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
183 if (nullPos)
184 --nullPos;
185 else
186 ++i;
187 }
188 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000189 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000190 // block or function pointer call.
191 QualType Ty = V->getType();
192 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000193 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000194 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
195 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000196 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
197 unsigned NumArgsInProto = Proto->getNumArgs();
198 unsigned k;
199 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
200 if (nullPos)
201 --nullPos;
202 else
203 ++i;
204 }
205 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
206 }
207 if (Ty->isBlockPointerType())
208 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000209 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000210 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000211 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 return;
213
214 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000215 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000216 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000217 return;
218 }
219 int sentinel = i;
220 while (sentinelPos > 0 && i < NumArgs-1) {
221 --sentinelPos;
222 ++i;
223 }
224 if (sentinelPos > 0) {
225 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000226 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000227 return;
228 }
229 while (i < NumArgs-1) {
230 ++i;
231 ++sentinel;
232 }
233 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000234 if (!sentinelExpr) return;
235 if (sentinelExpr->isTypeDependent()) return;
236 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000237
238 // nullptr_t is always treated as null.
239 if (sentinelExpr->getType()->isNullPtrType()) return;
240
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000241 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000242 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
243 Expr::NPC_ValueDependentIsNull))
244 return;
245
246 // Unfortunately, __null has type 'int'.
247 if (isa<GNUNullExpr>(sentinelExpr)) return;
248
249 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
250 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000251}
252
Douglas Gregor87f95b02009-02-26 21:00:50 +0000253SourceRange Sema::getExprRange(ExprTy *E) const {
254 Expr *Ex = (Expr *)E;
255 return Ex? Ex->getSourceRange() : SourceRange();
256}
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258//===----------------------------------------------------------------------===//
259// Standard Promotions and Conversions
260//===----------------------------------------------------------------------===//
261
Chris Lattner513165e2008-07-25 21:10:04 +0000262/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000263ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000264 QualType Ty = E->getType();
265 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
266
Chris Lattner513165e2008-07-25 21:10:04 +0000267 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000268 E = ImpCastExprToType(E, Context.getPointerType(Ty),
269 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000270 else if (Ty->isArrayType()) {
271 // In C90 mode, arrays only promote to pointers if the array expression is
272 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
273 // type 'array of type' is converted to an expression that has type 'pointer
274 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
275 // that has type 'array of type' ...". The relevant change is "an lvalue"
276 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000277 //
278 // C++ 4.2p1:
279 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
280 // T" can be converted to an rvalue of type "pointer to T".
281 //
John McCall086a4642010-11-24 05:12:34 +0000282 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000283 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
284 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000285 }
John Wiegley01296292011-04-08 18:41:53 +0000286 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000287}
288
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000289static void CheckForNullPointerDereference(Sema &S, Expr *E) {
290 // Check to see if we are dereferencing a null pointer. If so,
291 // and if not volatile-qualified, this is undefined behavior that the
292 // optimizer will delete, so warn about it. People sometimes try to use this
293 // to get a deterministic trap and are surprised by clang's behavior. This
294 // only handles the pattern "*null", which is a very syntactic check.
295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
296 if (UO->getOpcode() == UO_Deref &&
297 UO->getSubExpr()->IgnoreParenCasts()->
298 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
299 !UO->getType().isVolatileQualified()) {
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::warn_indirection_through_null)
302 << UO->getSubExpr()->getSourceRange());
303 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
304 S.PDiag(diag::note_indirection_through_null));
305 }
306}
307
John Wiegley01296292011-04-08 18:41:53 +0000308ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000309 // C++ [conv.lval]p1:
310 // A glvalue of a non-function, non-array type T can be
311 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000312 if (!E->isGLValue()) return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000313 QualType T = E->getType();
314 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000315
John McCall27584242010-12-06 20:48:59 +0000316 // Create a load out of an ObjCProperty l-value, if necessary.
317 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000318 ExprResult Res = ConvertPropertyForRValue(E);
319 if (Res.isInvalid())
320 return Owned(E);
321 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000322 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000323 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000324 }
John McCall27584242010-12-06 20:48:59 +0000325
326 // We don't want to throw lvalue-to-rvalue casts on top of
327 // expressions of certain types in C++.
328 if (getLangOptions().CPlusPlus &&
329 (E->getType() == Context.OverloadTy ||
330 T->isDependentType() ||
331 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000332 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000333
334 // The C standard is actually really unclear on this point, and
335 // DR106 tells us what the result should be but not why. It's
336 // generally best to say that void types just doesn't undergo
337 // lvalue-to-rvalue at all. Note that expressions of unqualified
338 // 'void' type are never l-values, but qualified void can be.
339 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000340 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000341
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000342 CheckForNullPointerDereference(*this, E);
343
John McCall27584242010-12-06 20:48:59 +0000344 // C++ [conv.lval]p1:
345 // [...] If T is a non-class type, the type of the prvalue is the
346 // cv-unqualified version of T. Otherwise, the type of the
347 // rvalue is T.
348 //
349 // C99 6.3.2.1p2:
350 // If the lvalue has qualified type, the value has the unqualified
351 // version of the type of the lvalue; otherwise, the value has the
352 // type of the lvalue.
353 if (T.hasQualifiers())
354 T = T.getUnqualifiedType();
355
Ted Kremenekdf26df72011-03-01 18:41:00 +0000356 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000357
John Wiegley01296292011-04-08 18:41:53 +0000358 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
359 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000360}
361
John Wiegley01296292011-04-08 18:41:53 +0000362ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
363 ExprResult Res = DefaultFunctionArrayConversion(E);
364 if (Res.isInvalid())
365 return ExprError();
366 Res = DefaultLvalueConversion(Res.take());
367 if (Res.isInvalid())
368 return ExprError();
369 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000370}
371
372
Chris Lattner513165e2008-07-25 21:10:04 +0000373/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000374/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000375/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000376/// apply if the array is an argument to the sizeof or address (&) operators.
377/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000378ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000379 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000380 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
381 if (Res.isInvalid())
382 return Owned(E);
383 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000384
385 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000386 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000387
388 // Try to perform integral promotions if the object has a theoretically
389 // promotable type.
390 if (Ty->isIntegralOrUnscopedEnumerationType()) {
391 // C99 6.3.1.1p2:
392 //
393 // The following may be used in an expression wherever an int or
394 // unsigned int may be used:
395 // - an object or expression with an integer type whose integer
396 // conversion rank is less than or equal to the rank of int
397 // and unsigned int.
398 // - A bit-field of type _Bool, int, signed int, or unsigned int.
399 //
400 // If an int can represent all values of the original type, the
401 // value is converted to an int; otherwise, it is converted to an
402 // unsigned int. These are called the integer promotions. All
403 // other types are unchanged by the integer promotions.
404
405 QualType PTy = Context.isPromotableBitField(E);
406 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000407 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
408 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000409 }
410 if (Ty->isPromotableIntegerType()) {
411 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000412 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
413 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000414 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000415 }
John Wiegley01296292011-04-08 18:41:53 +0000416 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000417}
418
Chris Lattner2ce500f2008-07-25 22:25:12 +0000419/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000420/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000421/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000422ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
423 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000424 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000425
John Wiegley01296292011-04-08 18:41:53 +0000426 ExprResult Res = UsualUnaryConversions(E);
427 if (Res.isInvalid())
428 return Owned(E);
429 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000430
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000432 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000433 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
434
435 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000436}
437
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000438/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
439/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000440/// interfaces passed by value.
441ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000442 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000443 ExprResult ExprRes = CheckPlaceholderExpr(E);
444 if (ExprRes.isInvalid())
445 return ExprError();
446
447 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000448 if (ExprRes.isInvalid())
449 return ExprError();
450 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000451
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000452 // __builtin_va_start takes the second argument as a "varargs" argument, but
453 // it doesn't actually do anything with it. It doesn't need to be non-pod
454 // etc.
455 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000456 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000457
Douglas Gregor347e0f22011-05-21 19:26:31 +0000458 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000459 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000460 DiagRuntimeBehavior(E->getLocStart(), 0,
461 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
462 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000463 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000464
John McCall31168b02011-06-15 23:02:42 +0000465 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000466 // C++0x [expr.call]p7:
467 // Passing a potentially-evaluated argument of class type (Clause 9)
468 // having a non-trivial copy constructor, a non-trivial move constructor,
469 // or a non-trivial destructor, with no corresponding parameter,
470 // is conditionally-supported with implementation-defined semantics.
471 bool TrivialEnough = false;
472 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
473 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
474 if (Record->hasTrivialCopyConstructor() &&
475 Record->hasTrivialMoveConstructor() &&
476 Record->hasTrivialDestructor())
477 TrivialEnough = true;
478 }
479 }
John McCall31168b02011-06-15 23:02:42 +0000480
481 if (!TrivialEnough &&
482 getLangOptions().ObjCAutoRefCount &&
483 E->getType()->isObjCLifetimeType())
484 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000485
486 if (TrivialEnough) {
487 // Nothing to diagnose. This is okay.
488 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000489 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000490 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000491 << CT)) {
492 // Turn this into a trap.
493 CXXScopeSpec SS;
494 UnqualifiedId Name;
495 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
496 E->getLocStart());
497 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
498 if (TrapFn.isInvalid())
499 return ExprError();
500
501 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
502 MultiExprArg(), E->getLocEnd());
503 if (Call.isInvalid())
504 return ExprError();
505
506 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
507 Call.get(), E);
508 if (Comma.isInvalid())
509 return ExprError();
510
511 E = Comma.get();
512 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000513 }
514
John Wiegley01296292011-04-08 18:41:53 +0000515 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000516}
517
Chris Lattner513165e2008-07-25 21:10:04 +0000518/// UsualArithmeticConversions - Performs various conversions that are common to
519/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000520/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000521/// responsible for emitting appropriate error diagnostics.
522/// FIXME: verify the conversion rules for "complex int" are consistent with
523/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000524QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000525 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000526 if (!isCompAssign) {
527 lhsExpr = UsualUnaryConversions(lhsExpr.take());
528 if (lhsExpr.isInvalid())
529 return QualType();
530 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000531
John Wiegley01296292011-04-08 18:41:53 +0000532 rhsExpr = UsualUnaryConversions(rhsExpr.take());
533 if (rhsExpr.isInvalid())
534 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000535
Mike Stump11289f42009-09-09 15:08:12 +0000536 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000537 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000538 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000539 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000540 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000541 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000542
543 // If both types are identical, no conversion is needed.
544 if (lhs == rhs)
545 return lhs;
546
547 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
548 // The caller can deal with this (e.g. pointer + int).
549 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
550 return lhs;
551
John McCalld005ac92010-11-13 08:17:45 +0000552 // Apply unary and bitfield promotions to the LHS's type.
553 QualType lhs_unpromoted = lhs;
554 if (lhs->isPromotableIntegerType())
555 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000556 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000557 if (!LHSBitfieldPromoteTy.isNull())
558 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000559 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000560 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000561
John McCalld005ac92010-11-13 08:17:45 +0000562 // If both types are identical, no conversion is needed.
563 if (lhs == rhs)
564 return lhs;
565
566 // At this point, we have two different arithmetic types.
567
568 // Handle complex types first (C99 6.3.1.8p1).
569 bool LHSComplexFloat = lhs->isComplexType();
570 bool RHSComplexFloat = rhs->isComplexType();
571 if (LHSComplexFloat || RHSComplexFloat) {
572 // if we have an integer operand, the result is the complex type.
573
John McCallc5e62b42010-11-13 09:02:35 +0000574 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
575 if (rhs->isIntegerType()) {
576 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000577 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
578 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000579 } else {
580 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000581 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000582 }
John McCalld005ac92010-11-13 08:17:45 +0000583 return lhs;
584 }
585
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
587 if (!isCompAssign) {
588 // int -> float -> _Complex float
589 if (lhs->isIntegerType()) {
590 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000591 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
592 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000593 } else {
594 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000595 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000596 }
597 }
John McCalld005ac92010-11-13 08:17:45 +0000598 return rhs;
599 }
600
601 // This handles complex/complex, complex/float, or float/complex.
602 // When both operands are complex, the shorter operand is converted to the
603 // type of the longer, and that is the type of the result. This corresponds
604 // to what is done when combining two real floating-point operands.
605 // The fun begins when size promotion occur across type domains.
606 // From H&S 6.3.4: When one operand is complex and the other is a real
607 // floating-point type, the less precise type is converted, within it's
608 // real or complex domain, to the precision of the other type. For example,
609 // when combining a "long double" with a "double _Complex", the
610 // "double _Complex" is promoted to "long double _Complex".
611 int order = Context.getFloatingTypeOrder(lhs, rhs);
612
613 // If both are complex, just cast to the more precise type.
614 if (LHSComplexFloat && RHSComplexFloat) {
615 if (order > 0) {
616 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000618 return lhs;
619
620 } else if (order < 0) {
621 // _Complex float -> _Complex double
622 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626 return lhs;
627 }
628
629 // If just the LHS is complex, the RHS needs to be converted,
630 // and the LHS might need to be promoted.
631 if (LHSComplexFloat) {
632 if (order > 0) { // LHS is wider
633 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000634 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000635 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
636 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000637 return lhs;
638 }
639
640 // RHS is at least as wide. Find its corresponding complex type.
641 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
642
643 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000644 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645
646 // _Complex float -> _Complex double
647 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000648 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000649
650 return result;
651 }
652
653 // Just the RHS is complex, so the LHS needs to be converted
654 // and the RHS might need to be promoted.
655 assert(RHSComplexFloat);
656
657 if (order < 0) { // RHS is wider
658 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000659 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000660 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000661 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
662 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000663 }
John McCalld005ac92010-11-13 08:17:45 +0000664 return rhs;
665 }
666
667 // LHS is at least as wide. Find its corresponding complex type.
668 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
669
670 // double -> _Complex double
671 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000672 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000673
674 // _Complex float -> _Complex double
675 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000676 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000677
678 return result;
679 }
680
681 // Now handle "real" floating types (i.e. float, double, long double).
682 bool LHSFloat = lhs->isRealFloatingType();
683 bool RHSFloat = rhs->isRealFloatingType();
684 if (LHSFloat || RHSFloat) {
685 // If we have two real floating types, convert the smaller operand
686 // to the bigger result.
687 if (LHSFloat && RHSFloat) {
688 int order = Context.getFloatingTypeOrder(lhs, rhs);
689 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000690 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000691 return lhs;
692 }
693
694 assert(order < 0 && "illegal float comparison");
695 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000697 return rhs;
698 }
699
700 // If we have an integer operand, the result is the real floating type.
701 if (LHSFloat) {
702 if (rhs->isIntegerType()) {
703 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000704 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000705 return lhs;
706 }
707
708 // Convert both sides to the appropriate complex float.
709 assert(rhs->isComplexIntegerType());
710 QualType result = Context.getComplexType(lhs);
711
712 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000713 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000714
715 // float -> _Complex float
716 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000717 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000718
719 return result;
720 }
721
722 assert(RHSFloat);
723 if (lhs->isIntegerType()) {
724 // Convert lhs to the rhs floating point type.
725 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000726 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000727 return rhs;
728 }
729
730 // Convert both sides to the appropriate complex float.
731 assert(lhs->isComplexIntegerType());
732 QualType result = Context.getComplexType(rhs);
733
734 // _Complex int -> _Complex float
735 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000736 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000737
738 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000740
741 return result;
742 }
743
744 // Handle GCC complex int extension.
745 // FIXME: if the operands are (int, _Complex long), we currently
746 // don't promote the complex. Also, signedness?
747 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
748 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
749 if (lhsComplexInt && rhsComplexInt) {
750 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
751 rhsComplexInt->getElementType());
752 assert(order && "inequal types with equal element ordering");
753 if (order > 0) {
754 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000755 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000756 return lhs;
757 }
758
759 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000760 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000761 return rhs;
762 } else if (lhsComplexInt) {
763 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000764 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000765 return lhs;
766 } else if (rhsComplexInt) {
767 // int -> _Complex int
768 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000769 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000770 return rhs;
771 }
772
773 // Finally, we have two differing integer types.
774 // The rules for this case are in C99 6.3.1.8
775 int compare = Context.getIntegerTypeOrder(lhs, rhs);
776 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
777 rhsSigned = rhs->hasSignedIntegerRepresentation();
778 if (lhsSigned == rhsSigned) {
779 // Same signedness; use the higher-ranked type
780 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000781 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000782 return lhs;
783 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000784 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000785 return rhs;
786 } else if (compare != (lhsSigned ? 1 : -1)) {
787 // The unsigned type has greater than or equal rank to the
788 // signed type, so use the unsigned type
789 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000790 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000791 return lhs;
792 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000793 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000794 return rhs;
795 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
796 // The two types are different widths; if we are here, that
797 // means the signed type is larger than the unsigned type, so
798 // use the signed type.
799 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000800 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000801 return lhs;
802 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000803 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000804 return rhs;
805 } else {
806 // The signed type is higher-ranked than the unsigned type,
807 // but isn't actually any bigger (like unsigned int and long
808 // on most 32-bit systems). Use the unsigned type corresponding
809 // to the signed type.
810 QualType result =
811 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000812 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000813 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000814 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000815 return result;
816 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000817}
818
Chris Lattner513165e2008-07-25 21:10:04 +0000819//===----------------------------------------------------------------------===//
820// Semantic Analysis for various Expression Types
821//===----------------------------------------------------------------------===//
822
823
Peter Collingbourne91147592011-04-15 00:35:48 +0000824ExprResult
825Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
826 SourceLocation DefaultLoc,
827 SourceLocation RParenLoc,
828 Expr *ControllingExpr,
829 MultiTypeArg types,
830 MultiExprArg exprs) {
831 unsigned NumAssocs = types.size();
832 assert(NumAssocs == exprs.size());
833
834 ParsedType *ParsedTypes = types.release();
835 Expr **Exprs = exprs.release();
836
837 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
838 for (unsigned i = 0; i < NumAssocs; ++i) {
839 if (ParsedTypes[i])
840 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
841 else
842 Types[i] = 0;
843 }
844
845 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
846 ControllingExpr, Types, Exprs,
847 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000848 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000849 return ER;
850}
851
852ExprResult
853Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
854 SourceLocation DefaultLoc,
855 SourceLocation RParenLoc,
856 Expr *ControllingExpr,
857 TypeSourceInfo **Types,
858 Expr **Exprs,
859 unsigned NumAssocs) {
860 bool TypeErrorFound = false,
861 IsResultDependent = ControllingExpr->isTypeDependent(),
862 ContainsUnexpandedParameterPack
863 = ControllingExpr->containsUnexpandedParameterPack();
864
865 for (unsigned i = 0; i < NumAssocs; ++i) {
866 if (Exprs[i]->containsUnexpandedParameterPack())
867 ContainsUnexpandedParameterPack = true;
868
869 if (Types[i]) {
870 if (Types[i]->getType()->containsUnexpandedParameterPack())
871 ContainsUnexpandedParameterPack = true;
872
873 if (Types[i]->getType()->isDependentType()) {
874 IsResultDependent = true;
875 } else {
876 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
877 // complete object type other than a variably modified type."
878 unsigned D = 0;
879 if (Types[i]->getType()->isIncompleteType())
880 D = diag::err_assoc_type_incomplete;
881 else if (!Types[i]->getType()->isObjectType())
882 D = diag::err_assoc_type_nonobject;
883 else if (Types[i]->getType()->isVariablyModifiedType())
884 D = diag::err_assoc_type_variably_modified;
885
886 if (D != 0) {
887 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
888 << Types[i]->getTypeLoc().getSourceRange()
889 << Types[i]->getType();
890 TypeErrorFound = true;
891 }
892
893 // C1X 6.5.1.1p2 "No two generic associations in the same generic
894 // selection shall specify compatible types."
895 for (unsigned j = i+1; j < NumAssocs; ++j)
896 if (Types[j] && !Types[j]->getType()->isDependentType() &&
897 Context.typesAreCompatible(Types[i]->getType(),
898 Types[j]->getType())) {
899 Diag(Types[j]->getTypeLoc().getBeginLoc(),
900 diag::err_assoc_compatible_types)
901 << Types[j]->getTypeLoc().getSourceRange()
902 << Types[j]->getType()
903 << Types[i]->getType();
904 Diag(Types[i]->getTypeLoc().getBeginLoc(),
905 diag::note_compat_assoc)
906 << Types[i]->getTypeLoc().getSourceRange()
907 << Types[i]->getType();
908 TypeErrorFound = true;
909 }
910 }
911 }
912 }
913 if (TypeErrorFound)
914 return ExprError();
915
916 // If we determined that the generic selection is result-dependent, don't
917 // try to compute the result expression.
918 if (IsResultDependent)
919 return Owned(new (Context) GenericSelectionExpr(
920 Context, KeyLoc, ControllingExpr,
921 Types, Exprs, NumAssocs, DefaultLoc,
922 RParenLoc, ContainsUnexpandedParameterPack));
923
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000925 unsigned DefaultIndex = -1U;
926 for (unsigned i = 0; i < NumAssocs; ++i) {
927 if (!Types[i])
928 DefaultIndex = i;
929 else if (Context.typesAreCompatible(ControllingExpr->getType(),
930 Types[i]->getType()))
931 CompatIndices.push_back(i);
932 }
933
934 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
935 // type compatible with at most one of the types named in its generic
936 // association list."
937 if (CompatIndices.size() > 1) {
938 // We strip parens here because the controlling expression is typically
939 // parenthesized in macro definitions.
940 ControllingExpr = ControllingExpr->IgnoreParens();
941 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
942 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
943 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000944 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000945 E = CompatIndices.end(); I != E; ++I) {
946 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
947 diag::note_compat_assoc)
948 << Types[*I]->getTypeLoc().getSourceRange()
949 << Types[*I]->getType();
950 }
951 return ExprError();
952 }
953
954 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
955 // its controlling expression shall have type compatible with exactly one of
956 // the types named in its generic association list."
957 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
958 // We strip parens here because the controlling expression is typically
959 // parenthesized in macro definitions.
960 ControllingExpr = ControllingExpr->IgnoreParens();
961 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
962 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
963 return ExprError();
964 }
965
966 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
967 // type name that is compatible with the type of the controlling expression,
968 // then the result expression of the generic selection is the expression
969 // in that generic association. Otherwise, the result expression of the
970 // generic selection is the expression in the default generic association."
971 unsigned ResultIndex =
972 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
973
974 return Owned(new (Context) GenericSelectionExpr(
975 Context, KeyLoc, ControllingExpr,
976 Types, Exprs, NumAssocs, DefaultLoc,
977 RParenLoc, ContainsUnexpandedParameterPack,
978 ResultIndex));
979}
980
Steve Naroff83895f72007-09-16 03:34:24 +0000981/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000982/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
983/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
984/// multiple tokens. However, the common case is that StringToks points to one
985/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000986///
John McCalldadc5752010-08-24 06:29:42 +0000987ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000988Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000989 assert(NumStringToks && "Must have at least one string!");
990
Chris Lattner8a24e582009-01-16 18:51:42 +0000991 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000992 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000993 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000994
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000995 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000996 for (unsigned i = 0; i != NumStringToks; ++i)
997 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000998
Chris Lattner36fc8792008-02-11 00:02:17 +0000999 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001000 if (Literal.AnyWide)
1001 StrTy = Context.getWCharType();
1002 else if (Literal.Pascal)
1003 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001004
1005 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001006 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001007 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001008
Chris Lattner36fc8792008-02-11 00:02:17 +00001009 // Get an array type for the string, according to C99 6.4.5. This includes
1010 // the nul terminator character as well as the string length for pascal
1011 // strings.
1012 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001013 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001014 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattner5b183d82006-11-10 05:03:26 +00001016 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001017 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Anders Carlsson75245402011-04-14 00:40:03 +00001018 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001019 &StringTokLocs[0],
1020 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001021}
1022
John McCallc63de662011-02-02 13:00:07 +00001023enum CaptureResult {
1024 /// No capture is required.
1025 CR_NoCapture,
1026
1027 /// A capture is required.
1028 CR_Capture,
1029
John McCall351762c2011-02-07 10:33:21 +00001030 /// A by-ref capture is required.
1031 CR_CaptureByRef,
1032
John McCallc63de662011-02-02 13:00:07 +00001033 /// An error occurred when trying to capture the given variable.
1034 CR_Error
1035};
1036
1037/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001038///
John McCallc63de662011-02-02 13:00:07 +00001039/// \param var - the variable referenced
1040/// \param DC - the context which we couldn't capture through
1041static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001042diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001043 VarDecl *var, DeclContext *DC) {
1044 switch (S.ExprEvalContexts.back().Context) {
1045 case Sema::Unevaluated:
1046 // The argument will never be evaluated, so don't complain.
1047 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001048
John McCallc63de662011-02-02 13:00:07 +00001049 case Sema::PotentiallyEvaluated:
1050 case Sema::PotentiallyEvaluatedIfUsed:
1051 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001052
John McCallc63de662011-02-02 13:00:07 +00001053 case Sema::PotentiallyPotentiallyEvaluated:
1054 // FIXME: delay these!
1055 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
John McCallc63de662011-02-02 13:00:07 +00001058 // Don't diagnose about capture if we're not actually in code right
1059 // now; in general, there are more appropriate places that will
1060 // diagnose this.
1061 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1062
John McCall92d627e2011-03-22 23:15:50 +00001063 // Certain madnesses can happen with parameter declarations, which
1064 // we want to ignore.
1065 if (isa<ParmVarDecl>(var)) {
1066 // - If the parameter still belongs to the translation unit, then
1067 // we're actually just using one parameter in the declaration of
1068 // the next. This is useful in e.g. VLAs.
1069 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1070 return CR_NoCapture;
1071
1072 // - This particular madness can happen in ill-formed default
1073 // arguments; claim it's okay and let downstream code handle it.
1074 if (S.CurContext == var->getDeclContext()->getParent())
1075 return CR_NoCapture;
1076 }
John McCallc63de662011-02-02 13:00:07 +00001077
1078 DeclarationName functionName;
1079 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1080 functionName = fn->getDeclName();
1081 // FIXME: variable from enclosing block that we couldn't capture from!
1082
1083 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1084 << var->getIdentifier() << functionName;
1085 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1086 << var->getIdentifier();
1087
1088 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001089}
1090
John McCall351762c2011-02-07 10:33:21 +00001091/// There is a well-formed capture at a particular scope level;
1092/// propagate it through all the nested blocks.
1093static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1094 const BlockDecl::Capture &capture) {
1095 VarDecl *var = capture.getVariable();
1096
1097 // Update all the inner blocks with the capture information.
1098 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1099 i != e; ++i) {
1100 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1101 innerBlock->Captures.push_back(
1102 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1103 /*nested*/ true, capture.getCopyExpr()));
1104 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1105 }
1106
1107 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1108}
1109
1110/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001111/// given value in the current context requires a variable capture.
1112///
1113/// This also keeps the captures set in the BlockScopeInfo records
1114/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001115static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001116 ValueDecl *value) {
1117 // Only variables ever require capture.
1118 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001119 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001120
1121 // Fast path: variables from the current context never require capture.
1122 DeclContext *DC = S.CurContext;
1123 if (var->getDeclContext() == DC) return CR_NoCapture;
1124
1125 // Only variables with local storage require capture.
1126 // FIXME: What about 'const' variables in C++?
1127 if (!var->hasLocalStorage()) return CR_NoCapture;
1128
1129 // Otherwise, we need to capture.
1130
1131 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001132 do {
1133 // Only blocks (and eventually C++0x closures) can capture; other
1134 // scopes don't work.
1135 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001136 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001137
1138 BlockScopeInfo *blockScope =
1139 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1140 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1141
John McCall351762c2011-02-07 10:33:21 +00001142 // Check whether we've already captured it in this block. If so,
1143 // we're done.
1144 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1145 return propagateCapture(S, functionScopesIndex,
1146 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001147
1148 functionScopesIndex--;
1149 DC = cast<BlockDecl>(DC)->getDeclContext();
1150 } while (var->getDeclContext() != DC);
1151
John McCall351762c2011-02-07 10:33:21 +00001152 // Okay, we descended all the way to the block that defines the variable.
1153 // Actually try to capture it.
1154 QualType type = var->getType();
1155
1156 // Prohibit variably-modified types.
1157 if (type->isVariablyModifiedType()) {
1158 S.Diag(loc, diag::err_ref_vm_type);
1159 S.Diag(var->getLocation(), diag::note_declared_at);
1160 return CR_Error;
1161 }
1162
1163 // Prohibit arrays, even in __block variables, but not references to
1164 // them.
1165 if (type->isArrayType()) {
1166 S.Diag(loc, diag::err_ref_array_type);
1167 S.Diag(var->getLocation(), diag::note_declared_at);
1168 return CR_Error;
1169 }
1170
1171 S.MarkDeclarationReferenced(loc, var);
1172
1173 // The BlocksAttr indicates the variable is bound by-reference.
1174 bool byRef = var->hasAttr<BlocksAttr>();
1175
1176 // Build a copy expression.
1177 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001178 const RecordType *rtype;
1179 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1180 (rtype = type->getAs<RecordType>())) {
1181
1182 // The capture logic needs the destructor, so make sure we mark it.
1183 // Usually this is unnecessary because most local variables have
1184 // their destructors marked at declaration time, but parameters are
1185 // an exception because it's technically only the call site that
1186 // actually requires the destructor.
1187 if (isa<ParmVarDecl>(var))
1188 S.FinalizeVarWithDestructor(var, rtype);
1189
John McCall351762c2011-02-07 10:33:21 +00001190 // According to the blocks spec, the capture of a variable from
1191 // the stack requires a const copy constructor. This is not true
1192 // of the copy/move done to move a __block variable to the heap.
1193 type.addConst();
1194
1195 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1196 ExprResult result =
1197 S.PerformCopyInitialization(
1198 InitializedEntity::InitializeBlock(var->getLocation(),
1199 type, false),
1200 loc, S.Owned(declRef));
1201
1202 // Build a full-expression copy expression if initialization
1203 // succeeded and used a non-trivial constructor. Recover from
1204 // errors by pretending that the copy isn't necessary.
1205 if (!result.isInvalid() &&
1206 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1207 result = S.MaybeCreateExprWithCleanups(result);
1208 copyExpr = result.take();
1209 }
1210 }
1211
1212 // We're currently at the declarer; go back to the closure.
1213 functionScopesIndex++;
1214 BlockScopeInfo *blockScope =
1215 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1216
1217 // Build a valid capture in this scope.
1218 blockScope->Captures.push_back(
1219 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1220 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1221
1222 // Propagate that to inner captures if necessary.
1223 return propagateCapture(S, functionScopesIndex,
1224 blockScope->Captures.back());
1225}
1226
1227static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1228 const DeclarationNameInfo &NameInfo,
1229 bool byRef) {
1230 assert(isa<VarDecl>(vd) && "capturing non-variable");
1231
1232 VarDecl *var = cast<VarDecl>(vd);
1233 assert(var->hasLocalStorage() && "capturing non-local");
1234 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1235
1236 QualType exprType = var->getType().getNonReferenceType();
1237
1238 BlockDeclRefExpr *BDRE;
1239 if (!byRef) {
1240 // The variable will be bound by copy; make it const within the
1241 // closure, but record that this was done in the expression.
1242 bool constAdded = !exprType.isConstQualified();
1243 exprType.addConst();
1244
1245 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1246 NameInfo.getLoc(), false,
1247 constAdded);
1248 } else {
1249 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1250 NameInfo.getLoc(), true);
1251 }
1252
1253 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001254}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001255
John McCalldadc5752010-08-24 06:29:42 +00001256ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001258 SourceLocation Loc,
1259 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001260 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001261 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001262}
1263
John McCallf4cd4f92011-02-09 01:13:10 +00001264/// BuildDeclRefExpr - Build an expression that references a
1265/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001266ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001267Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001268 const DeclarationNameInfo &NameInfo,
1269 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001270 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001271
John McCall086a4642010-11-24 05:12:34 +00001272 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001273 SS? SS->getWithLocInContext(Context)
1274 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001275 D, NameInfo, Ty, VK);
1276
1277 // Just in case we're building an illegal pointer-to-member.
1278 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1279 E->setObjectKind(OK_BitField);
1280
1281 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001282}
1283
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001284/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001285/// possibly a list of template arguments.
1286///
1287/// If this produces template arguments, it is permitted to call
1288/// DecomposeTemplateName.
1289///
1290/// This actually loses a lot of source location information for
1291/// non-standard name kinds; we should consider preserving that in
1292/// some way.
Douglas Gregor5476205b2011-06-23 00:49:38 +00001293void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1294 TemplateArgumentListInfo &Buffer,
1295 DeclarationNameInfo &NameInfo,
1296 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001297 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1298 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1299 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1300
Douglas Gregor5476205b2011-06-23 00:49:38 +00001301 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001302 Id.TemplateId->getTemplateArgs(),
1303 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001304 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001305 TemplateArgsPtr.release();
1306
John McCall3e56fd42010-08-23 07:28:44 +00001307 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001308 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001309 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001310 TemplateArgs = &Buffer;
1311 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001312 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001313 TemplateArgs = 0;
1314 }
1315}
1316
John McCalld681c392009-12-16 08:11:27 +00001317/// Diagnose an empty lookup.
1318///
1319/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001320bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1321 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001322 DeclarationName Name = R.getLookupName();
1323
John McCalld681c392009-12-16 08:11:27 +00001324 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001325 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001326 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1327 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001328 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001329 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001330 diagnostic_suggest = diag::err_undeclared_use_suggest;
1331 }
John McCalld681c392009-12-16 08:11:27 +00001332
Douglas Gregor598b08f2009-12-31 05:20:13 +00001333 // If the original lookup was an unqualified lookup, fake an
1334 // unqualified lookup. This is useful when (for example) the
1335 // original lookup would not have found something because it was a
1336 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001337 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001338 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001339 if (isa<CXXRecordDecl>(DC)) {
1340 LookupQualifiedName(R, DC);
1341
1342 if (!R.empty()) {
1343 // Don't give errors about ambiguities in this lookup.
1344 R.suppressDiagnostics();
1345
1346 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1347 bool isInstance = CurMethod &&
1348 CurMethod->isInstance() &&
1349 DC == CurMethod->getParent();
1350
1351 // Give a code modification hint to insert 'this->'.
1352 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1353 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001354 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001355 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1356 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001357 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001358 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001359 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 Diag(R.getNameLoc(), diagnostic) << Name
1361 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1362 QualType DepThisType = DepMethod->getThisType(Context);
1363 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1364 R.getNameLoc(), DepThisType, false);
1365 TemplateArgumentListInfo TList;
1366 if (ULE->hasExplicitTemplateArgs())
1367 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001368
Douglas Gregore16af532011-02-28 18:50:33 +00001369 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001370 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001371 CXXDependentScopeMemberExpr *DepExpr =
1372 CXXDependentScopeMemberExpr::Create(
1373 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001374 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001375 R.getLookupNameInfo(), &TList);
1376 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001377 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001378 // FIXME: we should be able to handle this case too. It is correct
1379 // to add this-> here. This is a workaround for PR7947.
1380 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001381 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001382 } else {
John McCalld681c392009-12-16 08:11:27 +00001383 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001384 }
John McCalld681c392009-12-16 08:11:27 +00001385
1386 // Do we really want to note all of these?
1387 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1388 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1389
1390 // Tell the callee to try to recover.
1391 return false;
1392 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001393
1394 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001395 }
1396 }
1397
Douglas Gregor598b08f2009-12-31 05:20:13 +00001398 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001399 TypoCorrection Corrected;
1400 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1401 S, &SS, NULL, false, CTC))) {
1402 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1403 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1404 R.setLookupName(Corrected.getCorrection());
1405
Hans Wennborg38198de2011-07-12 08:45:31 +00001406 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001407 R.addDecl(ND);
1408 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001409 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001410 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1411 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001412 else
1413 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001414 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001415 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001416 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1417 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001418 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001419 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001420
1421 // Tell the callee to try to recover.
1422 return false;
1423 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001424
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001425 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001426 // FIXME: If we ended up with a typo for a type name or
1427 // Objective-C class name, we're in trouble because the parser
1428 // is in the wrong place to recover. Suggest the typo
1429 // correction, but don't make it a fix-it since we're not going
1430 // to recover well anyway.
1431 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001432 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001433 else
1434 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001435 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001436 << SS.getRange();
1437
1438 // Don't try to recover; it won't work.
1439 return true;
1440 }
1441 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001442 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001444 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001445 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001446 else
Douglas Gregor25363982010-01-01 00:15:04 +00001447 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001448 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001449 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001450 return true;
1451 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001452 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001453 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001454
1455 // Emit a special diagnostic for failed member lookups.
1456 // FIXME: computing the declaration context might fail here (?)
1457 if (!SS.isEmpty()) {
1458 Diag(R.getNameLoc(), diag::err_no_member)
1459 << Name << computeDeclContext(SS, false)
1460 << SS.getRange();
1461 return true;
1462 }
1463
John McCalld681c392009-12-16 08:11:27 +00001464 // Give up, we can't recover.
1465 Diag(R.getNameLoc(), diagnostic) << Name;
1466 return true;
1467}
1468
Douglas Gregor05fcf842010-11-02 20:36:02 +00001469ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1470 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001471 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1472 if (!IDecl)
1473 return 0;
1474 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1475 if (!ClassImpDecl)
1476 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001477 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001478 if (!property)
1479 return 0;
1480 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001481 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1482 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001483 return 0;
1484 return property;
1485}
1486
Douglas Gregor05fcf842010-11-02 20:36:02 +00001487bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1488 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1489 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1490 if (!IDecl)
1491 return false;
1492 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1493 if (!ClassImpDecl)
1494 return false;
1495 if (ObjCPropertyImplDecl *PIDecl
1496 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1497 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1498 PIDecl->getPropertyIvarDecl())
1499 return false;
1500
1501 return true;
1502}
1503
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001504ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1505 IdentifierInfo *II,
1506 SourceLocation NameLoc) {
1507 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001508 bool LookForIvars;
1509 if (Lookup.empty())
1510 LookForIvars = true;
1511 else if (CurMeth->isClassMethod())
1512 LookForIvars = false;
1513 else
1514 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001515 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1516 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001517 if (!LookForIvars)
1518 return 0;
1519
Fariborz Jahanian18722982010-07-17 00:59:30 +00001520 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1521 if (!IDecl)
1522 return 0;
1523 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001524 if (!ClassImpDecl)
1525 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001526 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001527 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001528 if (!property)
1529 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001530 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001531 DynamicImplSeen =
1532 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001533 // property implementation has a designated ivar. No need to assume a new
1534 // one.
1535 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1536 return 0;
1537 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001538 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001539 QualType PropType = Context.getCanonicalType(property->getType());
1540 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001541 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001542 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001543 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001544 (Expr *)0, true);
1545 ClassImpDecl->addDecl(Ivar);
1546 IDecl->makeDeclVisibleInContext(Ivar, false);
1547 property->setPropertyIvarDecl(Ivar);
1548 return Ivar;
1549 }
1550 return 0;
1551}
1552
John McCalldadc5752010-08-24 06:29:42 +00001553ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001554 CXXScopeSpec &SS,
1555 UnqualifiedId &Id,
1556 bool HasTrailingLParen,
1557 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001558 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1559 "cannot be direct & operand and have a trailing lparen");
1560
1561 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001562 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001563
John McCall10eae182009-11-30 22:42:35 +00001564 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001565
1566 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001567 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001568 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001569 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001570
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001571 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001572 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001573 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001574
John McCalle66edc12009-11-24 19:00:30 +00001575 // C++ [temp.dep.expr]p3:
1576 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001577 // -- an identifier that was declared with a dependent type,
1578 // (note: handled after lookup)
1579 // -- a template-id that is dependent,
1580 // (note: handled in BuildTemplateIdExpr)
1581 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001582 // -- a nested-name-specifier that contains a class-name that
1583 // names a dependent type.
1584 // Determine whether this is a member of an unknown specialization;
1585 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001586 bool DependentID = false;
1587 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1588 Name.getCXXNameType()->isDependentType()) {
1589 DependentID = true;
1590 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001591 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001592 if (RequireCompleteDeclContext(SS, DC))
1593 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001594 } else {
1595 DependentID = true;
1596 }
1597 }
1598
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001599 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001600 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001601 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001602
Fariborz Jahanian86151342010-07-22 23:33:21 +00001603 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001604 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001605 LookupResult R(*this, NameInfo,
1606 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1607 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001608 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001609 // Lookup the template name again to correctly establish the context in
1610 // which it was found. This is really unfortunate as we already did the
1611 // lookup to determine that it was a template name in the first place. If
1612 // this becomes a performance hit, we can work harder to preserve those
1613 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001614 bool MemberOfUnknownSpecialization;
1615 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1616 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001617
1618 if (MemberOfUnknownSpecialization ||
1619 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1620 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1621 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001622 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001623 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001624 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Douglas Gregora5226932011-02-04 13:35:07 +00001626 // If the result might be in a dependent base class, this is a dependent
1627 // id-expression.
1628 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1629 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1630 TemplateArgs);
1631
John McCalle66edc12009-11-24 19:00:30 +00001632 // If this reference is in an Objective-C method, then we need to do
1633 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001634 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001635 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001636 if (E.isInvalid())
1637 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001639 if (Expr *Ex = E.takeAs<Expr>())
1640 return Owned(Ex);
1641
1642 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001643 if (getLangOptions().ObjCDefaultSynthProperties &&
1644 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001645 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001646 if (const ObjCPropertyDecl *Property =
1647 canSynthesizeProvisionalIvar(II)) {
1648 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1649 Diag(Property->getLocation(), diag::note_property_declare);
1650 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001651 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1652 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001653 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001654 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001655 // for further use, this must be set to false if in class method.
1656 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001657 }
Chris Lattner59a25942008-03-31 00:36:02 +00001658 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001659
John McCalle66edc12009-11-24 19:00:30 +00001660 if (R.isAmbiguous())
1661 return ExprError();
1662
Douglas Gregor171c45a2009-02-18 21:56:37 +00001663 // Determine whether this name might be a candidate for
1664 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001665 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001666
John McCalle66edc12009-11-24 19:00:30 +00001667 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001668 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001669 // in C90, extension in C99, forbidden in C++).
1670 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1671 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1672 if (D) R.addDecl(D);
1673 }
1674
1675 // If this name wasn't predeclared and if this is not a function
1676 // call, diagnose the problem.
1677 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001678 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001679 return ExprError();
1680
1681 assert(!R.empty() &&
1682 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001683
1684 // If we found an Objective-C instance variable, let
1685 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001686 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001687 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1688 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001689 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001690 assert(E.isInvalid() || E.get());
1691 return move(E);
1692 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001693 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCalle66edc12009-11-24 19:00:30 +00001696 // This is guaranteed from this point on.
1697 assert(!R.empty() || ADL);
1698
John McCall2d74de92009-12-01 22:10:20 +00001699 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001700 // C++ [class.mfct.non-static]p3:
1701 // When an id-expression that is not part of a class member access
1702 // syntax and not used to form a pointer to member is used in the
1703 // body of a non-static member function of class X, if name lookup
1704 // resolves the name in the id-expression to a non-static non-type
1705 // member of some class C, the id-expression is transformed into a
1706 // class member access expression using (*this) as the
1707 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001708 //
1709 // But we don't actually need to do this for '&' operands if R
1710 // resolved to a function or overloaded function set, because the
1711 // expression is ill-formed if it actually works out to be a
1712 // non-static member function:
1713 //
1714 // C++ [expr.ref]p4:
1715 // Otherwise, if E1.E2 refers to a non-static member function. . .
1716 // [t]he expression can be used only as the left-hand operand of a
1717 // member function call.
1718 //
1719 // There are other safeguards against such uses, but it's important
1720 // to get this right here so that we don't end up making a
1721 // spuriously dependent expression if we're inside a dependent
1722 // instance method.
John McCall57500772009-12-16 12:17:52 +00001723 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001724 bool MightBeImplicitMember;
1725 if (!isAddressOfOperand)
1726 MightBeImplicitMember = true;
1727 else if (!SS.isEmpty())
1728 MightBeImplicitMember = false;
1729 else if (R.isOverloadedResult())
1730 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001731 else if (R.isUnresolvableResult())
1732 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001733 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001734 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1735 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001736
1737 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001738 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001739 }
1740
John McCalle66edc12009-11-24 19:00:30 +00001741 if (TemplateArgs)
1742 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001743
John McCalle66edc12009-11-24 19:00:30 +00001744 return BuildDeclarationNameExpr(SS, R, ADL);
1745}
1746
John McCall10eae182009-11-30 22:42:35 +00001747/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1748/// declaration name, generally during template instantiation.
1749/// There's a large number of things which don't need to be done along
1750/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001751ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001752Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001753 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001754 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001755 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001756 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001757
John McCall0b66eb32010-05-01 00:40:08 +00001758 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001759 return ExprError();
1760
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001761 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001762 LookupQualifiedName(R, DC);
1763
1764 if (R.isAmbiguous())
1765 return ExprError();
1766
1767 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001768 Diag(NameInfo.getLoc(), diag::err_no_member)
1769 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001770 return ExprError();
1771 }
1772
1773 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1774}
1775
1776/// LookupInObjCMethod - The parser has read a name in, and Sema has
1777/// detected that we're currently inside an ObjC method. Perform some
1778/// additional lookup.
1779///
1780/// Ideally, most of this would be done by lookup, but there's
1781/// actually quite a lot of extra work involved.
1782///
1783/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001784ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001785Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001786 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001787 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001788 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001789
John McCalle66edc12009-11-24 19:00:30 +00001790 // There are two cases to handle here. 1) scoped lookup could have failed,
1791 // in which case we should look for an ivar. 2) scoped lookup could have
1792 // found a decl, but that decl is outside the current instance method (i.e.
1793 // a global variable). In these two cases, we do a lookup for an ivar with
1794 // this name, if the lookup sucedes, we replace it our current decl.
1795
1796 // If we're in a class method, we don't normally want to look for
1797 // ivars. But if we don't find anything else, and there's an
1798 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001799 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001800
1801 bool LookForIvars;
1802 if (Lookup.empty())
1803 LookForIvars = true;
1804 else if (IsClassMethod)
1805 LookForIvars = false;
1806 else
1807 LookForIvars = (Lookup.isSingleResult() &&
1808 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001809 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001810 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001811 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001812 ObjCInterfaceDecl *ClassDeclared;
1813 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1814 // Diagnose using an ivar in a class method.
1815 if (IsClassMethod)
1816 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1817 << IV->getDeclName());
1818
1819 // If we're referencing an invalid decl, just return this as a silent
1820 // error node. The error diagnostic was already emitted on the decl.
1821 if (IV->isInvalidDecl())
1822 return ExprError();
1823
1824 // Check if referencing a field with __attribute__((deprecated)).
1825 if (DiagnoseUseOfDecl(IV, Loc))
1826 return ExprError();
1827
1828 // Diagnose the use of an ivar outside of the declaring class.
1829 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1830 ClassDeclared != IFace)
1831 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1832
1833 // FIXME: This should use a new expr for a direct reference, don't
1834 // turn this into Self->ivar, just return a BareIVarExpr or something.
1835 IdentifierInfo &II = Context.Idents.get("self");
1836 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001837 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001838 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001839 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001840 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001841 SelfName, false, false);
1842 if (SelfExpr.isInvalid())
1843 return ExprError();
1844
John Wiegley01296292011-04-08 18:41:53 +00001845 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1846 if (SelfExpr.isInvalid())
1847 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001848
John McCalle66edc12009-11-24 19:00:30 +00001849 MarkDeclarationReferenced(Loc, IV);
1850 return Owned(new (Context)
1851 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001852 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001853 }
Chris Lattner87313662010-04-12 05:10:17 +00001854 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001855 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001856 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001857 ObjCInterfaceDecl *ClassDeclared;
1858 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1859 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1860 IFace == ClassDeclared)
1861 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1862 }
1863 }
1864
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001865 if (Lookup.empty() && II && AllowBuiltinCreation) {
1866 // FIXME. Consolidate this with similar code in LookupName.
1867 if (unsigned BuiltinID = II->getBuiltinID()) {
1868 if (!(getLangOptions().CPlusPlus &&
1869 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1870 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1871 S, Lookup.isForRedeclaration(),
1872 Lookup.getNameLoc());
1873 if (D) Lookup.addDecl(D);
1874 }
1875 }
1876 }
John McCalle66edc12009-11-24 19:00:30 +00001877 // Sentinel value saying that we didn't do anything special.
1878 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001879}
John McCalld14a8642009-11-21 08:51:07 +00001880
John McCall16df1e52010-03-30 21:47:33 +00001881/// \brief Cast a base object to a member's actual type.
1882///
1883/// Logically this happens in three phases:
1884///
1885/// * First we cast from the base type to the naming class.
1886/// The naming class is the class into which we were looking
1887/// when we found the member; it's the qualifier type if a
1888/// qualifier was provided, and otherwise it's the base type.
1889///
1890/// * Next we cast from the naming class to the declaring class.
1891/// If the member we found was brought into a class's scope by
1892/// a using declaration, this is that class; otherwise it's
1893/// the class declaring the member.
1894///
1895/// * Finally we cast from the declaring class to the "true"
1896/// declaring class of the member. This conversion does not
1897/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001898ExprResult
1899Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001900 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001901 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001902 NamedDecl *Member) {
1903 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1904 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001905 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001906
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001907 QualType DestRecordType;
1908 QualType DestType;
1909 QualType FromRecordType;
1910 QualType FromType = From->getType();
1911 bool PointerConversions = false;
1912 if (isa<FieldDecl>(Member)) {
1913 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001914
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001915 if (FromType->getAs<PointerType>()) {
1916 DestType = Context.getPointerType(DestRecordType);
1917 FromRecordType = FromType->getPointeeType();
1918 PointerConversions = true;
1919 } else {
1920 DestType = DestRecordType;
1921 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001922 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001923 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1924 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001925 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001926
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001927 DestType = Method->getThisType(Context);
1928 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001929
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 if (FromType->getAs<PointerType>()) {
1931 FromRecordType = FromType->getPointeeType();
1932 PointerConversions = true;
1933 } else {
1934 FromRecordType = FromType;
1935 DestType = DestRecordType;
1936 }
1937 } else {
1938 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001939 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001940 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001941
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001942 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001943 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001944
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001945 // If the unqualified types are the same, no conversion is necessary.
1946 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001947 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001948
John McCall16df1e52010-03-30 21:47:33 +00001949 SourceRange FromRange = From->getSourceRange();
1950 SourceLocation FromLoc = FromRange.getBegin();
1951
John McCall2536c6d2010-08-25 10:28:54 +00001952 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001953
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001954 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 // class name.
1957 //
1958 // If the member was a qualified name and the qualified referred to a
1959 // specific base subobject type, we'll cast to that intermediate type
1960 // first and then to the object in which the member is declared. That allows
1961 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1962 //
1963 // class Base { public: int x; };
1964 // class Derived1 : public Base { };
1965 // class Derived2 : public Base { };
1966 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1967 //
1968 // void VeryDerived::f() {
1969 // x = 17; // error: ambiguous base subobjects
1970 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1971 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001973 QualType QType = QualType(Qualifier->getAsType(), 0);
1974 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1975 assert(QType->isRecordType() && "lookup done with non-record type");
1976
1977 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1978
1979 // In C++98, the qualifier type doesn't actually have to be a base
1980 // type of the object type, in which case we just ignore it.
1981 // Otherwise build the appropriate casts.
1982 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001983 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001984 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001985 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001986 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00001987
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001988 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001989 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00001990 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1991 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001992
1993 FromType = QType;
1994 FromRecordType = QRecordType;
1995
1996 // If the qualifier type was the same as the destination type,
1997 // we're done.
1998 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001999 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002000 }
2001 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002002
John McCall16df1e52010-03-30 21:47:33 +00002003 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002004
John McCall16df1e52010-03-30 21:47:33 +00002005 // If we actually found the member through a using declaration, cast
2006 // down to the using declaration's type.
2007 //
2008 // Pointer equality is fine here because only one declaration of a
2009 // class ever has member declarations.
2010 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2011 assert(isa<UsingShadowDecl>(FoundDecl));
2012 QualType URecordType = Context.getTypeDeclType(
2013 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2014
2015 // We only need to do this if the naming-class to declaring-class
2016 // conversion is non-trivial.
2017 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2018 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002019 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002020 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002021 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002022 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002023
John McCall16df1e52010-03-30 21:47:33 +00002024 QualType UType = URecordType;
2025 if (PointerConversions)
2026 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002027 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2028 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002029 FromType = UType;
2030 FromRecordType = URecordType;
2031 }
2032
2033 // We don't do access control for the conversion from the
2034 // declaring class to the true declaring class.
2035 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002036 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002037
John McCallcf142162010-08-07 06:22:56 +00002038 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002039 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2040 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002041 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002042 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002043
John Wiegley01296292011-04-08 18:41:53 +00002044 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2045 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002046}
Douglas Gregor3256d042009-06-30 15:47:41 +00002047
John McCalle66edc12009-11-24 19:00:30 +00002048bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002049 const LookupResult &R,
2050 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002051 // Only when used directly as the postfix-expression of a call.
2052 if (!HasTrailingLParen)
2053 return false;
2054
2055 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002056 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002057 return false;
2058
2059 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002060 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002061 return false;
2062
2063 // Turn off ADL when we find certain kinds of declarations during
2064 // normal lookup:
2065 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2066 NamedDecl *D = *I;
2067
2068 // C++0x [basic.lookup.argdep]p3:
2069 // -- a declaration of a class member
2070 // Since using decls preserve this property, we check this on the
2071 // original decl.
John McCall57500772009-12-16 12:17:52 +00002072 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002073 return false;
2074
2075 // C++0x [basic.lookup.argdep]p3:
2076 // -- a block-scope function declaration that is not a
2077 // using-declaration
2078 // NOTE: we also trigger this for function templates (in fact, we
2079 // don't check the decl type at all, since all other decl types
2080 // turn off ADL anyway).
2081 if (isa<UsingShadowDecl>(D))
2082 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2083 else if (D->getDeclContext()->isFunctionOrMethod())
2084 return false;
2085
2086 // C++0x [basic.lookup.argdep]p3:
2087 // -- a declaration that is neither a function or a function
2088 // template
2089 // And also for builtin functions.
2090 if (isa<FunctionDecl>(D)) {
2091 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2092
2093 // But also builtin functions.
2094 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2095 return false;
2096 } else if (!isa<FunctionTemplateDecl>(D))
2097 return false;
2098 }
2099
2100 return true;
2101}
2102
2103
John McCalld14a8642009-11-21 08:51:07 +00002104/// Diagnoses obvious problems with the use of the given declaration
2105/// as an expression. This is only actually called for lookups that
2106/// were not overloaded, and it doesn't promise that the declaration
2107/// will in fact be used.
2108static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002109 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002110 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2111 return true;
2112 }
2113
2114 if (isa<ObjCInterfaceDecl>(D)) {
2115 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2116 return true;
2117 }
2118
2119 if (isa<NamespaceDecl>(D)) {
2120 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2121 return true;
2122 }
2123
2124 return false;
2125}
2126
John McCalldadc5752010-08-24 06:29:42 +00002127ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002128Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002129 LookupResult &R,
2130 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002131 // If this is a single, fully-resolved result and we don't need ADL,
2132 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002133 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002134 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2135 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002136
2137 // We only need to check the declaration if there's exactly one
2138 // result, because in the overloaded case the results can only be
2139 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002140 if (R.isSingleResult() &&
2141 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002142 return ExprError();
2143
John McCall58cc69d2010-01-27 01:50:18 +00002144 // Otherwise, just build an unresolved lookup expression. Suppress
2145 // any lookup-related diagnostics; we'll hash these out later, when
2146 // we've picked a target.
2147 R.suppressDiagnostics();
2148
John McCalld14a8642009-11-21 08:51:07 +00002149 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002150 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002151 SS.getWithLocInContext(Context),
2152 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002153 NeedsADL, R.isOverloadedResult(),
2154 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002155
2156 return Owned(ULE);
2157}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002158
John McCalld14a8642009-11-21 08:51:07 +00002159/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002160ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002161Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002162 const DeclarationNameInfo &NameInfo,
2163 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002164 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002165 assert(!isa<FunctionTemplateDecl>(D) &&
2166 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002167
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002168 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002169 if (CheckDeclInExpr(*this, Loc, D))
2170 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002171
Douglas Gregore7488b92009-12-01 16:58:18 +00002172 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2173 // Specifically diagnose references to class templates that are missing
2174 // a template argument list.
2175 Diag(Loc, diag::err_template_decl_ref)
2176 << Template << SS.getRange();
2177 Diag(Template->getLocation(), diag::note_template_decl_here);
2178 return ExprError();
2179 }
2180
2181 // Make sure that we're referring to a value.
2182 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2183 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002184 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002185 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002186 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002187 return ExprError();
2188 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002189
Douglas Gregor171c45a2009-02-18 21:56:37 +00002190 // Check whether this declaration can be used. Note that we suppress
2191 // this check when we're going to perform argument-dependent lookup
2192 // on this function name, because this might not be the function
2193 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002194 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002195 return ExprError();
2196
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002197 // Only create DeclRefExpr's for valid Decl's.
2198 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002199 return ExprError();
2200
John McCallf3a88602011-02-03 08:15:49 +00002201 // Handle members of anonymous structs and unions. If we got here,
2202 // and the reference is to a class member indirect field, then this
2203 // must be the subject of a pointer-to-member expression.
2204 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2205 if (!indirectField->isCXXClassMember())
2206 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2207 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002208
Chris Lattner2a9d9892008-10-20 05:16:36 +00002209 // If the identifier reference is inside a block, and it refers to a value
2210 // that is outside the block, create a BlockDeclRefExpr instead of a
2211 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2212 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002213 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002214 // We do not do this for things like enum constants, global variables, etc,
2215 // as they do not get snapshotted.
2216 //
John McCall351762c2011-02-07 10:33:21 +00002217 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002218 case CR_Error:
2219 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002220
John McCallc63de662011-02-02 13:00:07 +00002221 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002222 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2223 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2224
2225 case CR_CaptureByRef:
2226 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2227 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002228
2229 case CR_NoCapture: {
2230 // If this reference is not in a block or if the referenced
2231 // variable is within the block, create a normal DeclRefExpr.
2232
2233 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002234 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002235
2236 switch (D->getKind()) {
2237 // Ignore all the non-ValueDecl kinds.
2238#define ABSTRACT_DECL(kind)
2239#define VALUE(type, base)
2240#define DECL(type, base) \
2241 case Decl::type:
2242#include "clang/AST/DeclNodes.inc"
2243 llvm_unreachable("invalid value decl kind");
2244 return ExprError();
2245
2246 // These shouldn't make it here.
2247 case Decl::ObjCAtDefsField:
2248 case Decl::ObjCIvar:
2249 llvm_unreachable("forming non-member reference to ivar?");
2250 return ExprError();
2251
2252 // Enum constants are always r-values and never references.
2253 // Unresolved using declarations are dependent.
2254 case Decl::EnumConstant:
2255 case Decl::UnresolvedUsingValue:
2256 valueKind = VK_RValue;
2257 break;
2258
2259 // Fields and indirect fields that got here must be for
2260 // pointer-to-member expressions; we just call them l-values for
2261 // internal consistency, because this subexpression doesn't really
2262 // exist in the high-level semantics.
2263 case Decl::Field:
2264 case Decl::IndirectField:
2265 assert(getLangOptions().CPlusPlus &&
2266 "building reference to field in C?");
2267
2268 // These can't have reference type in well-formed programs, but
2269 // for internal consistency we do this anyway.
2270 type = type.getNonReferenceType();
2271 valueKind = VK_LValue;
2272 break;
2273
2274 // Non-type template parameters are either l-values or r-values
2275 // depending on the type.
2276 case Decl::NonTypeTemplateParm: {
2277 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2278 type = reftype->getPointeeType();
2279 valueKind = VK_LValue; // even if the parameter is an r-value reference
2280 break;
2281 }
2282
2283 // For non-references, we need to strip qualifiers just in case
2284 // the template parameter was declared as 'const int' or whatever.
2285 valueKind = VK_RValue;
2286 type = type.getUnqualifiedType();
2287 break;
2288 }
2289
2290 case Decl::Var:
2291 // In C, "extern void blah;" is valid and is an r-value.
2292 if (!getLangOptions().CPlusPlus &&
2293 !type.hasQualifiers() &&
2294 type->isVoidType()) {
2295 valueKind = VK_RValue;
2296 break;
2297 }
2298 // fallthrough
2299
2300 case Decl::ImplicitParam:
2301 case Decl::ParmVar:
2302 // These are always l-values.
2303 valueKind = VK_LValue;
2304 type = type.getNonReferenceType();
2305 break;
2306
2307 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002308 const FunctionType *fty = type->castAs<FunctionType>();
2309
2310 // If we're referring to a function with an __unknown_anytype
2311 // result type, make the entire expression __unknown_anytype.
2312 if (fty->getResultType() == Context.UnknownAnyTy) {
2313 type = Context.UnknownAnyTy;
2314 valueKind = VK_RValue;
2315 break;
2316 }
2317
John McCallf4cd4f92011-02-09 01:13:10 +00002318 // Functions are l-values in C++.
2319 if (getLangOptions().CPlusPlus) {
2320 valueKind = VK_LValue;
2321 break;
2322 }
2323
2324 // C99 DR 316 says that, if a function type comes from a
2325 // function definition (without a prototype), that type is only
2326 // used for checking compatibility. Therefore, when referencing
2327 // the function, we pretend that we don't have the full function
2328 // type.
John McCall2979fe02011-04-12 00:42:48 +00002329 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2330 isa<FunctionProtoType>(fty))
2331 type = Context.getFunctionNoProtoType(fty->getResultType(),
2332 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002333
2334 // Functions are r-values in C.
2335 valueKind = VK_RValue;
2336 break;
2337 }
2338
2339 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002340 // If we're referring to a method with an __unknown_anytype
2341 // result type, make the entire expression __unknown_anytype.
2342 // This should only be possible with a type written directly.
2343 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2344 if (proto->getResultType() == Context.UnknownAnyTy) {
2345 type = Context.UnknownAnyTy;
2346 valueKind = VK_RValue;
2347 break;
2348 }
2349
John McCallf4cd4f92011-02-09 01:13:10 +00002350 // C++ methods are l-values if static, r-values if non-static.
2351 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2352 valueKind = VK_LValue;
2353 break;
2354 }
2355 // fallthrough
2356
2357 case Decl::CXXConversion:
2358 case Decl::CXXDestructor:
2359 case Decl::CXXConstructor:
2360 valueKind = VK_RValue;
2361 break;
2362 }
2363
2364 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2365 }
2366
John McCallc63de662011-02-02 13:00:07 +00002367 }
John McCall7decc9e2010-11-18 06:31:45 +00002368
John McCall351762c2011-02-07 10:33:21 +00002369 llvm_unreachable("unknown capture result");
2370 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002371}
Chris Lattnere168f762006-11-10 05:29:30 +00002372
John McCall2979fe02011-04-12 00:42:48 +00002373ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002374 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002375
Chris Lattnere168f762006-11-10 05:29:30 +00002376 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002377 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002378 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2379 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2380 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002381 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002382
Chris Lattnera81a0272008-01-12 08:14:25 +00002383 // Pre-defined identifiers are of type char[x], where x is the length of the
2384 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002385
Anders Carlsson2fb08242009-09-08 18:24:21 +00002386 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002387 if (!currentDecl && getCurBlock())
2388 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002389 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002390 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002391 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002392 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002393
Anders Carlsson0b209a82009-09-11 01:22:35 +00002394 QualType ResTy;
2395 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2396 ResTy = Context.DependentTy;
2397 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002398 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002399
Anders Carlsson0b209a82009-09-11 01:22:35 +00002400 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002401 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002402 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2403 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002404 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002405}
2406
John McCalldadc5752010-08-24 06:29:42 +00002407ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002408 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002409 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002410 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002411 if (Invalid)
2412 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002413
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002414 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2415 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002416 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002417 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002418
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002419 QualType Ty;
2420 if (!getLangOptions().CPlusPlus)
2421 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2422 else if (Literal.isWide())
2423 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002424 else if (Literal.isMultiChar())
2425 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002426 else
2427 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002428
Sebastian Redl20614a72009-01-20 22:23:13 +00002429 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2430 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002431 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002432}
2433
John McCalldadc5752010-08-24 06:29:42 +00002434ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002435 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002436 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2437 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002438 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002439 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002440 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002441 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002442 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002443
Chris Lattner23b7eb62007-06-15 23:05:46 +00002444 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002445 // Add padding so that NumericLiteralParser can overread by one character.
2446 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002447 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448
Chris Lattner67ca9252007-05-21 01:08:44 +00002449 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002450 bool Invalid = false;
2451 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2452 if (Invalid)
2453 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002454
Mike Stump11289f42009-09-09 15:08:12 +00002455 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002456 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002457 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002458 return ExprError();
2459
Chris Lattner1c20a172007-08-26 03:42:43 +00002460 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002461
Chris Lattner1c20a172007-08-26 03:42:43 +00002462 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002463 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002464 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002465 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002466 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002467 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002468 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002469 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002470
2471 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2472
John McCall53b93a02009-12-24 09:08:04 +00002473 using llvm::APFloat;
2474 APFloat Val(Format);
2475
2476 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002477
2478 // Overflow is always an error, but underflow is only an error if
2479 // we underflowed to zero (APFloat reports denormals as underflow).
2480 if ((result & APFloat::opOverflow) ||
2481 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002482 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002483 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002484 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002485 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002486 APFloat::getLargest(Format).toString(buffer);
2487 } else {
John McCall62abc942010-02-26 23:35:57 +00002488 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002489 APFloat::getSmallest(Format).toString(buffer);
2490 }
2491
2492 Diag(Tok.getLocation(), diagnostic)
2493 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002494 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002495 }
2496
2497 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002498 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002499
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002500 if (Ty == Context.DoubleTy) {
2501 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002502 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002503 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2504 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002505 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002506 }
2507 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002508 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002509 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002510 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002511 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002512
Neil Boothac582c52007-08-29 22:00:19 +00002513 // long long is a C99 feature.
2514 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002515 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002516 Diag(Tok.getLocation(), diag::ext_longlong);
2517
Chris Lattner67ca9252007-05-21 01:08:44 +00002518 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002519 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002520
Chris Lattner67ca9252007-05-21 01:08:44 +00002521 if (Literal.GetIntegerValue(ResultVal)) {
2522 // If this value didn't fit into uintmax_t, warn and force to ull.
2523 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002524 Ty = Context.UnsignedLongLongTy;
2525 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002526 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002527 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002528 // If this value fits into a ULL, try to figure out what else it fits into
2529 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530
Chris Lattner67ca9252007-05-21 01:08:44 +00002531 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2532 // be an unsigned int.
2533 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2534
2535 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002536 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002537 if (!Literal.isLong && !Literal.isLongLong) {
2538 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002539 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002540
Chris Lattner67ca9252007-05-21 01:08:44 +00002541 // Does it fit in a unsigned int?
2542 if (ResultVal.isIntN(IntSize)) {
2543 // Does it fit in a signed int?
2544 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002545 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002546 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002547 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002548 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002549 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002550 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002551
Chris Lattner67ca9252007-05-21 01:08:44 +00002552 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002553 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002554 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002555
Chris Lattner67ca9252007-05-21 01:08:44 +00002556 // Does it fit in a unsigned long?
2557 if (ResultVal.isIntN(LongSize)) {
2558 // Does it fit in a signed long?
2559 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002560 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002561 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002562 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002563 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002564 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002565 }
2566
Chris Lattner67ca9252007-05-21 01:08:44 +00002567 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002568 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002569 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Chris Lattner67ca9252007-05-21 01:08:44 +00002571 // Does it fit in a unsigned long long?
2572 if (ResultVal.isIntN(LongLongSize)) {
2573 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002574 // To be compatible with MSVC, hex integer literals ending with the
2575 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002576 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2577 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002578 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002579 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002580 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002581 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 }
2583 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002584
Chris Lattner67ca9252007-05-21 01:08:44 +00002585 // If we still couldn't decide a type, we probably have something that
2586 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002587 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002588 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002589 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002590 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002592
Chris Lattner55258cf2008-05-09 05:59:00 +00002593 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002594 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002595 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002596 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002597 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002598
Chris Lattner1c20a172007-08-26 03:42:43 +00002599 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2600 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002601 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002602 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002603
2604 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002605}
2606
John McCalldadc5752010-08-24 06:29:42 +00002607ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002608 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002609 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002610 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002611}
2612
Chandler Carruth62da79c2011-05-26 08:53:12 +00002613static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2614 SourceLocation Loc,
2615 SourceRange ArgRange) {
2616 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2617 // scalar or vector data type argument..."
2618 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2619 // type (C99 6.2.5p18) or void.
2620 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2621 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2622 << T << ArgRange;
2623 return true;
2624 }
2625
2626 assert((T->isVoidType() || !T->isIncompleteType()) &&
2627 "Scalar types should always be complete");
2628 return false;
2629}
2630
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002631static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2632 SourceLocation Loc,
2633 SourceRange ArgRange,
2634 UnaryExprOrTypeTrait TraitKind) {
2635 // C99 6.5.3.4p1:
2636 if (T->isFunctionType()) {
2637 // alignof(function) is allowed as an extension.
2638 if (TraitKind == UETT_SizeOf)
2639 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2640 return false;
2641 }
2642
2643 // Allow sizeof(void)/alignof(void) as an extension.
2644 if (T->isVoidType()) {
2645 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2646 return false;
2647 }
2648
2649 return true;
2650}
2651
2652static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2653 SourceLocation Loc,
2654 SourceRange ArgRange,
2655 UnaryExprOrTypeTrait TraitKind) {
2656 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2657 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2658 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2659 << T << (TraitKind == UETT_SizeOf)
2660 << ArgRange;
2661 return true;
2662 }
2663
2664 return false;
2665}
2666
Chandler Carruth14502c22011-05-26 08:53:10 +00002667/// \brief Check the constrains on expression operands to unary type expression
2668/// and type traits.
2669///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002670/// Completes any types necessary and validates the constraints on the operand
2671/// expression. The logic mostly mirrors the type-based overload, but may modify
2672/// the expression as it completes the type for that expression through template
2673/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002674bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2675 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002676 QualType ExprTy = Op->getType();
2677
2678 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2679 // the result is the size of the referenced type."
2680 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2681 // result shall be the alignment of the referenced type."
2682 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2683 ExprTy = Ref->getPointeeType();
2684
2685 if (ExprKind == UETT_VecStep)
2686 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2687 Op->getSourceRange());
2688
2689 // Whitelist some types as extensions
2690 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2691 Op->getSourceRange(), ExprKind))
2692 return false;
2693
2694 if (RequireCompleteExprType(Op,
2695 PDiag(diag::err_sizeof_alignof_incomplete_type)
2696 << ExprKind << Op->getSourceRange(),
2697 std::make_pair(SourceLocation(), PDiag(0))))
2698 return true;
2699
2700 // Completeing the expression's type may have changed it.
2701 ExprTy = Op->getType();
2702 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2703 ExprTy = Ref->getPointeeType();
2704
2705 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2706 Op->getSourceRange(), ExprKind))
2707 return true;
2708
Nico Weber0870deb2011-06-15 02:47:03 +00002709 if (ExprKind == UETT_SizeOf) {
2710 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2711 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2712 QualType OType = PVD->getOriginalType();
2713 QualType Type = PVD->getType();
2714 if (Type->isPointerType() && OType->isArrayType()) {
2715 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2716 << Type << OType;
2717 Diag(PVD->getLocation(), diag::note_declared_at);
2718 }
2719 }
2720 }
2721 }
2722
Chandler Carruth7c430c02011-05-27 01:33:31 +00002723 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002724}
2725
2726/// \brief Check the constraints on operands to unary expression and type
2727/// traits.
2728///
2729/// This will complete any types necessary, and validate the various constraints
2730/// on those operands.
2731///
Steve Naroff71b59a92007-06-04 22:22:31 +00002732/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002733/// C99 6.3.2.1p[2-4] all state:
2734/// Except when it is the operand of the sizeof operator ...
2735///
2736/// C++ [expr.sizeof]p4
2737/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2738/// standard conversions are not applied to the operand of sizeof.
2739///
2740/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002741bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2742 SourceLocation OpLoc,
2743 SourceRange ExprRange,
2744 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002745 if (exprType->isDependentType())
2746 return false;
2747
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002748 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2749 // the result is the size of the referenced type."
2750 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2751 // result shall be the alignment of the referenced type."
2752 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2753 exprType = Ref->getPointeeType();
2754
Chandler Carruth62da79c2011-05-26 08:53:12 +00002755 if (ExprKind == UETT_VecStep)
2756 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002757
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002758 // Whitelist some types as extensions
2759 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2760 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002761 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002762
Chris Lattner62975a72009-04-24 00:30:45 +00002763 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002764 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002765 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002766 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002767
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002768 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2769 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002770 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002771
Chris Lattner62975a72009-04-24 00:30:45 +00002772 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002773}
2774
Chandler Carruth14502c22011-05-26 08:53:10 +00002775static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002776 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002777
Mike Stump11289f42009-09-09 15:08:12 +00002778 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002779 if (isa<DeclRefExpr>(E))
2780 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002781
2782 // Cannot know anything else if the expression is dependent.
2783 if (E->isTypeDependent())
2784 return false;
2785
Douglas Gregor71235ec2009-05-02 02:18:30 +00002786 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002787 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2788 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002789 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002790 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002791
2792 // Alignment of a field access is always okay, so long as it isn't a
2793 // bit-field.
2794 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002795 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002796 return false;
2797
Chandler Carruth14502c22011-05-26 08:53:10 +00002798 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002799}
2800
Chandler Carruth14502c22011-05-26 08:53:10 +00002801bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002802 E = E->IgnoreParens();
2803
2804 // Cannot know anything else if the expression is dependent.
2805 if (E->isTypeDependent())
2806 return false;
2807
Chandler Carruth14502c22011-05-26 08:53:10 +00002808 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002809}
2810
Douglas Gregor0950e412009-03-13 21:01:28 +00002811/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002812ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002813Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2814 SourceLocation OpLoc,
2815 UnaryExprOrTypeTrait ExprKind,
2816 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002817 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002818 return ExprError();
2819
John McCallbcd03502009-12-07 02:54:59 +00002820 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002821
Douglas Gregor0950e412009-03-13 21:01:28 +00002822 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002823 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002824 return ExprError();
2825
2826 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002827 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2828 Context.getSizeType(),
2829 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002830}
2831
2832/// \brief Build a sizeof or alignof expression given an expression
2833/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002834ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002835Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2836 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002837 ExprResult PE = CheckPlaceholderExpr(E);
2838 if (PE.isInvalid())
2839 return ExprError();
2840
2841 E = PE.get();
2842
Douglas Gregor0950e412009-03-13 21:01:28 +00002843 // Verify that the operand is valid.
2844 bool isInvalid = false;
2845 if (E->isTypeDependent()) {
2846 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002847 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002848 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002849 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002850 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002851 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002852 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002853 isInvalid = true;
2854 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002855 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002856 }
2857
2858 if (isInvalid)
2859 return ExprError();
2860
2861 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002862 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002863 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002864 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002865}
2866
Peter Collingbournee190dee2011-03-11 19:24:49 +00002867/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2868/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002869/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002870ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002871Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2872 UnaryExprOrTypeTrait ExprKind, bool isType,
2873 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002874 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002875 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002876
Sebastian Redl6f282892008-11-11 17:56:53 +00002877 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002878 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002879 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002880 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002881 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002882
Douglas Gregor0950e412009-03-13 21:01:28 +00002883 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002884 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002885 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002886}
2887
John Wiegley01296292011-04-08 18:41:53 +00002888static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002889 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002890 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002891 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002892
John McCall34376a62010-12-04 03:47:34 +00002893 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002894 if (V.get()->getObjectKind() != OK_Ordinary) {
2895 V = S.DefaultLvalueConversion(V.take());
2896 if (V.isInvalid())
2897 return QualType();
2898 }
John McCall34376a62010-12-04 03:47:34 +00002899
Chris Lattnere267f5d2007-08-26 05:39:26 +00002900 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002901 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002902 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002903
Chris Lattnere267f5d2007-08-26 05:39:26 +00002904 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002905 if (V.get()->getType()->isArithmeticType())
2906 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002907
John McCall36226622010-10-12 02:09:17 +00002908 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002909 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002910 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002911 if (PR.get() != V.get()) {
2912 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002913 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002914 }
2915
Chris Lattnere267f5d2007-08-26 05:39:26 +00002916 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002917 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002918 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002919 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002920}
2921
2922
Chris Lattnere168f762006-11-10 05:29:30 +00002923
John McCalldadc5752010-08-24 06:29:42 +00002924ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002925Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002926 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002927 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002928 switch (Kind) {
2929 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002930 case tok::plusplus: Opc = UO_PostInc; break;
2931 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002932 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002933
John McCallb268a282010-08-23 23:25:46 +00002934 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002935}
2936
John McCalldadc5752010-08-24 06:29:42 +00002937ExprResult
John McCallb268a282010-08-23 23:25:46 +00002938Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2939 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002940 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002941 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002942 if (Result.isInvalid()) return ExprError();
2943 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002944
John McCallb268a282010-08-23 23:25:46 +00002945 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor40412ac2008-11-19 17:17:41 +00002947 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002948 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002949 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002950 Context.DependentTy,
2951 VK_LValue, OK_Ordinary,
2952 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002953 }
2954
Mike Stump11289f42009-09-09 15:08:12 +00002955 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002956 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002957 LHSExp->getType()->isEnumeralType() ||
2958 RHSExp->getType()->isRecordType() ||
2959 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002960 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002961 }
2962
John McCallb268a282010-08-23 23:25:46 +00002963 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002964}
2965
2966
John McCalldadc5752010-08-24 06:29:42 +00002967ExprResult
John McCallb268a282010-08-23 23:25:46 +00002968Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2969 Expr *Idx, SourceLocation RLoc) {
2970 Expr *LHSExp = Base;
2971 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002972
Chris Lattner36d572b2007-07-16 00:14:47 +00002973 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00002974 if (!LHSExp->getType()->getAs<VectorType>()) {
2975 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2976 if (Result.isInvalid())
2977 return ExprError();
2978 LHSExp = Result.take();
2979 }
2980 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
2981 if (Result.isInvalid())
2982 return ExprError();
2983 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002984
Chris Lattner36d572b2007-07-16 00:14:47 +00002985 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002986 ExprValueKind VK = VK_LValue;
2987 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002988
Steve Naroffc1aadb12007-03-28 21:49:40 +00002989 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002990 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002991 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002992 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002993 Expr *BaseExpr, *IndexExpr;
2994 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002995 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2996 BaseExpr = LHSExp;
2997 IndexExpr = RHSExp;
2998 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002999 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003000 BaseExpr = LHSExp;
3001 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003002 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003003 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003004 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003005 BaseExpr = RHSExp;
3006 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003007 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003008 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003009 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003010 BaseExpr = LHSExp;
3011 IndexExpr = RHSExp;
3012 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003013 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003014 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003015 // Handle the uncommon case of "123[Ptr]".
3016 BaseExpr = RHSExp;
3017 IndexExpr = LHSExp;
3018 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003019 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003020 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003021 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003022 VK = LHSExp->getValueKind();
3023 if (VK != VK_RValue)
3024 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003025
Chris Lattner36d572b2007-07-16 00:14:47 +00003026 // FIXME: need to deal with const...
3027 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003028 } else if (LHSTy->isArrayType()) {
3029 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003030 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003031 // wasn't promoted because of the C90 rule that doesn't
3032 // allow promoting non-lvalue arrays. Warn, then
3033 // force the promotion here.
3034 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3035 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003036 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3037 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003038 LHSTy = LHSExp->getType();
3039
3040 BaseExpr = LHSExp;
3041 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003042 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003043 } else if (RHSTy->isArrayType()) {
3044 // Same as previous, except for 123[f().a] case
3045 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3046 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003047 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3048 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003049 RHSTy = RHSExp->getType();
3050
3051 BaseExpr = RHSExp;
3052 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003053 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003054 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003055 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3056 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003057 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003058 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003059 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003060 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3061 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003062
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003063 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003064 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3065 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003066 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3067
Douglas Gregorac1fb652009-03-24 19:52:54 +00003068 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003069 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3070 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003071 // incomplete types are not object types.
3072 if (ResultType->isFunctionType()) {
3073 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3074 << ResultType << BaseExpr->getSourceRange();
3075 return ExprError();
3076 }
Mike Stump11289f42009-09-09 15:08:12 +00003077
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003078 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3079 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003080 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3081 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003082
3083 // C forbids expressions of unqualified void type from being l-values.
3084 // See IsCForbiddenLValueType.
3085 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003086 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003087 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003088 PDiag(diag::err_subscript_incomplete_type)
3089 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003090 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003091
Chris Lattner62975a72009-04-24 00:30:45 +00003092 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003093 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003094 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3095 << ResultType << BaseExpr->getSourceRange();
3096 return ExprError();
3097 }
Mike Stump11289f42009-09-09 15:08:12 +00003098
John McCall4bc41ae2010-11-18 19:01:18 +00003099 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003100 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003101
Mike Stump4e1f26a2009-02-19 03:04:26 +00003102 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003103 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003104}
3105
John McCalldadc5752010-08-24 06:29:42 +00003106ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003107 FunctionDecl *FD,
3108 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003109 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003110 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003111 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003112 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003113 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003114 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003115 return ExprError();
3116 }
3117
3118 if (Param->hasUninstantiatedDefaultArg()) {
3119 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003120
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003121 // Instantiate the expression.
3122 MultiLevelTemplateArgumentList ArgList
3123 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003124
Nico Weber44887f62010-11-29 18:19:25 +00003125 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003126 = ArgList.getInnermost();
3127 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3128 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003129
Nico Weber44887f62010-11-29 18:19:25 +00003130 ExprResult Result;
3131 {
3132 // C++ [dcl.fct.default]p5:
3133 // The names in the [default argument] expression are bound, and
3134 // the semantic constraints are checked, at the point where the
3135 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003136 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003137 Result = SubstExpr(UninstExpr, ArgList);
3138 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003139 if (Result.isInvalid())
3140 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003142 // Check the expression as an initializer for the parameter.
3143 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003144 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003145 InitializationKind Kind
3146 = InitializationKind::CreateCopy(Param->getLocation(),
3147 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3148 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003149
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003150 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3151 Result = InitSeq.Perform(*this, Entity, Kind,
3152 MultiExprArg(*this, &ResultE, 1));
3153 if (Result.isInvalid())
3154 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003155
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003156 // Build the default argument expression.
3157 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3158 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003159 }
3160
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003161 // If the default expression creates temporaries, we need to
3162 // push them to the current stack of expression temporaries so they'll
3163 // be properly destroyed.
3164 // FIXME: We should really be rebuilding the default argument with new
3165 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003166 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3167 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3168 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3169 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3170 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003171 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003172 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003173
3174 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003175 // Just mark all of the declarations in this potentially-evaluated expression
3176 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003177 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003178 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003179}
3180
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003181/// ConvertArgumentsForCall - Converts the arguments specified in
3182/// Args/NumArgs to the parameter types of the function FDecl with
3183/// function prototype Proto. Call is the call expression itself, and
3184/// Fn is the function expression. For a C++ member function, this
3185/// routine does not attempt to convert the object argument. Returns
3186/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003187bool
3188Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003189 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003190 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003191 Expr **Args, unsigned NumArgs,
3192 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003193 // Bail out early if calling a builtin with custom typechecking.
3194 // We don't need to do this in the
3195 if (FDecl)
3196 if (unsigned ID = FDecl->getBuiltinID())
3197 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3198 return false;
3199
Mike Stump4e1f26a2009-02-19 03:04:26 +00003200 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003201 // assignment, to the types of the corresponding parameter, ...
3202 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003203 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003204
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003205 // If too few arguments are available (and we don't have default
3206 // arguments for the remaining parameters), don't make the call.
3207 if (NumArgs < NumArgsInProto) {
3208 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3209 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003210 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003211 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003212 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003213 }
3214
3215 // If too many are passed and not variadic, error on the extras and drop
3216 // them.
3217 if (NumArgs > NumArgsInProto) {
3218 if (!Proto->isVariadic()) {
3219 Diag(Args[NumArgsInProto]->getLocStart(),
3220 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003221 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003222 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003223 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3224 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003225
3226 // Emit the location of the prototype.
3227 if (FDecl && !FDecl->getBuiltinID())
3228 Diag(FDecl->getLocStart(),
3229 diag::note_typecheck_call_too_many_args)
3230 << FDecl;
3231
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003232 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003233 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003234 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003235 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003236 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003237 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003238 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003239 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3240 if (Fn->getType()->isBlockPointerType())
3241 CallType = VariadicBlock; // Block
3242 else if (isa<MemberExpr>(Fn))
3243 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003244 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003245 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003246 if (Invalid)
3247 return true;
3248 unsigned TotalNumArgs = AllArgs.size();
3249 for (unsigned i = 0; i < TotalNumArgs; ++i)
3250 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003251
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003252 return false;
3253}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003254
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003255bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3256 FunctionDecl *FDecl,
3257 const FunctionProtoType *Proto,
3258 unsigned FirstProtoArg,
3259 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003260 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003261 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003262 unsigned NumArgsInProto = Proto->getNumArgs();
3263 unsigned NumArgsToCheck = NumArgs;
3264 bool Invalid = false;
3265 if (NumArgs != NumArgsInProto)
3266 // Use default arguments for missing arguments
3267 NumArgsToCheck = NumArgsInProto;
3268 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003269 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003270 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003271 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003272
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003273 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003274 if (ArgIx < NumArgs) {
3275 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003276
Eli Friedman3164fb12009-03-22 22:00:50 +00003277 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3278 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003279 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003280 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003281 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003282
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003283 // Pass the argument
3284 ParmVarDecl *Param = 0;
3285 if (FDecl && i < FDecl->getNumParams())
3286 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003287
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003288 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003289 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003290 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3291 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003292 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003293 SourceLocation(),
3294 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003295 if (ArgE.isInvalid())
3296 return true;
3297
3298 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003299 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003300 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003301
John McCalldadc5752010-08-24 06:29:42 +00003302 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003303 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003304 if (ArgExpr.isInvalid())
3305 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003306
Anders Carlsson355933d2009-08-25 03:49:14 +00003307 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003308 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003309 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003310 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003311
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003312 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003313 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003314
3315 // Assume that extern "C" functions with variadic arguments that
3316 // return __unknown_anytype aren't *really* variadic.
3317 if (Proto->getResultType() == Context.UnknownAnyTy &&
3318 FDecl && FDecl->isExternC()) {
3319 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3320 ExprResult arg;
3321 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3322 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3323 else
3324 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3325 Invalid |= arg.isInvalid();
3326 AllArgs.push_back(arg.take());
3327 }
3328
3329 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3330 } else {
3331 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3332 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3333 Invalid |= Arg.isInvalid();
3334 AllArgs.push_back(Arg.take());
3335 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003336 }
3337 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003338 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003339}
3340
John McCall2979fe02011-04-12 00:42:48 +00003341/// Given a function expression of unknown-any type, try to rebuild it
3342/// to have a function type.
3343static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3344
Steve Naroff83895f72007-09-16 03:34:24 +00003345/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003346/// This provides the location of the left/right parens and a list of comma
3347/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003348ExprResult
John McCallb268a282010-08-23 23:25:46 +00003349Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003350 MultiExprArg args, SourceLocation RParenLoc,
3351 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003352 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003353
3354 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003355 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003356 if (Result.isInvalid()) return ExprError();
3357 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003358
John McCallb268a282010-08-23 23:25:46 +00003359 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003360
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003361 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003362 // If this is a pseudo-destructor expression, build the call immediately.
3363 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3364 if (NumArgs > 0) {
3365 // Pseudo-destructor calls should not have any arguments.
3366 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003367 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003368 SourceRange(Args[0]->getLocStart(),
3369 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003370
Douglas Gregorad8a3362009-09-04 17:36:40 +00003371 NumArgs = 0;
3372 }
Mike Stump11289f42009-09-09 15:08:12 +00003373
Douglas Gregorad8a3362009-09-04 17:36:40 +00003374 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003375 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003376 }
Mike Stump11289f42009-09-09 15:08:12 +00003377
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003378 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003379 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003380 // FIXME: Will need to cache the results of name lookup (including ADL) in
3381 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003382 bool Dependent = false;
3383 if (Fn->isTypeDependent())
3384 Dependent = true;
3385 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3386 Dependent = true;
3387
Peter Collingbourne41f85462011-02-09 21:07:24 +00003388 if (Dependent) {
3389 if (ExecConfig) {
3390 return Owned(new (Context) CUDAKernelCallExpr(
3391 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3392 Context.DependentTy, VK_RValue, RParenLoc));
3393 } else {
3394 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3395 Context.DependentTy, VK_RValue,
3396 RParenLoc));
3397 }
3398 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003399
3400 // Determine whether this is a call to an object (C++ [over.call.object]).
3401 if (Fn->getType()->isRecordType())
3402 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003403 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003404
John McCall2979fe02011-04-12 00:42:48 +00003405 if (Fn->getType() == Context.UnknownAnyTy) {
3406 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3407 if (result.isInvalid()) return ExprError();
3408 Fn = result.take();
3409 }
3410
John McCall0009fcc2011-04-26 20:42:42 +00003411 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003412 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003413 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003414 }
John McCall0009fcc2011-04-26 20:42:42 +00003415 }
John McCall10eae182009-11-30 22:42:35 +00003416
John McCall0009fcc2011-04-26 20:42:42 +00003417 // Check for overloaded calls. This can happen even in C due to extensions.
3418 if (Fn->getType() == Context.OverloadTy) {
3419 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3420
3421 // We aren't supposed to apply this logic if there's an '&' involved.
3422 if (!find.IsAddressOfOperand) {
3423 OverloadExpr *ovl = find.Expression;
3424 if (isa<UnresolvedLookupExpr>(ovl)) {
3425 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3426 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3427 RParenLoc, ExecConfig);
3428 } else {
John McCall2d74de92009-12-01 22:10:20 +00003429 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003430 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003431 }
3432 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003433 }
3434
Douglas Gregore254f902009-02-04 00:32:51 +00003435 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003436
Eli Friedmane14b1992009-12-26 03:35:45 +00003437 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003438
John McCall57500772009-12-16 12:17:52 +00003439 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003440 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3441 if (UnOp->getOpcode() == UO_AddrOf)
3442 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3443
John McCall57500772009-12-16 12:17:52 +00003444 if (isa<DeclRefExpr>(NakedFn))
3445 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003446 else if (isa<MemberExpr>(NakedFn))
3447 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003448
Peter Collingbourne41f85462011-02-09 21:07:24 +00003449 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3450 ExecConfig);
3451}
3452
3453ExprResult
3454Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3455 MultiExprArg execConfig, SourceLocation GGGLoc) {
3456 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3457 if (!ConfigDecl)
3458 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3459 << "cudaConfigureCall");
3460 QualType ConfigQTy = ConfigDecl->getType();
3461
3462 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3463 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3464
3465 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003466}
3467
Tanya Lattner55808c12011-06-04 00:47:47 +00003468/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3469///
3470/// __builtin_astype( value, dst type )
3471///
3472ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3473 SourceLocation BuiltinLoc,
3474 SourceLocation RParenLoc) {
3475 ExprValueKind VK = VK_RValue;
3476 ExprObjectKind OK = OK_Ordinary;
3477 QualType DstTy = GetTypeFromParser(destty);
3478 QualType SrcTy = expr->getType();
3479 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3480 return ExprError(Diag(BuiltinLoc,
3481 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003482 << DstTy
3483 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003484 << expr->getSourceRange());
3485 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3486}
3487
John McCall57500772009-12-16 12:17:52 +00003488/// BuildResolvedCallExpr - Build a call to a resolved expression,
3489/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003490/// unary-convert to an expression of function-pointer or
3491/// block-pointer type.
3492///
3493/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003494ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003495Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3496 SourceLocation LParenLoc,
3497 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003498 SourceLocation RParenLoc,
3499 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003500 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3501
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003502 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003503 ExprResult Result = UsualUnaryConversions(Fn);
3504 if (Result.isInvalid())
3505 return ExprError();
3506 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003507
Chris Lattner08464942007-12-28 05:29:59 +00003508 // Make the call expr early, before semantic checks. This guarantees cleanup
3509 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003510 CallExpr *TheCall;
3511 if (Config) {
3512 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3513 cast<CallExpr>(Config),
3514 Args, NumArgs,
3515 Context.BoolTy,
3516 VK_RValue,
3517 RParenLoc);
3518 } else {
3519 TheCall = new (Context) CallExpr(Context, Fn,
3520 Args, NumArgs,
3521 Context.BoolTy,
3522 VK_RValue,
3523 RParenLoc);
3524 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003525
John McCallbebede42011-02-26 05:39:39 +00003526 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3527
3528 // Bail out early if calling a builtin with custom typechecking.
3529 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3530 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3531
John McCall31996342011-04-07 08:22:57 +00003532 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003533 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003534 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003535 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3536 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003537 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003538 if (FuncT == 0)
3539 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3540 << Fn->getType() << Fn->getSourceRange());
3541 } else if (const BlockPointerType *BPT =
3542 Fn->getType()->getAs<BlockPointerType>()) {
3543 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3544 } else {
John McCall31996342011-04-07 08:22:57 +00003545 // Handle calls to expressions of unknown-any type.
3546 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003547 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003548 if (rewrite.isInvalid()) return ExprError();
3549 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003550 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003551 goto retry;
3552 }
3553
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003554 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3555 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003556 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003557
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003558 if (getLangOptions().CUDA) {
3559 if (Config) {
3560 // CUDA: Kernel calls must be to global functions
3561 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3562 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3563 << FDecl->getName() << Fn->getSourceRange());
3564
3565 // CUDA: Kernel function must have 'void' return type
3566 if (!FuncT->getResultType()->isVoidType())
3567 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3568 << Fn->getType() << Fn->getSourceRange());
3569 }
3570 }
3571
Eli Friedman3164fb12009-03-22 22:00:50 +00003572 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003573 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003574 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003575 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003576 return ExprError();
3577
Chris Lattner08464942007-12-28 05:29:59 +00003578 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003579 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003580 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003581
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003582 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003583 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003584 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003585 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003586 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003587 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003588
Douglas Gregord8e97de2009-04-02 15:37:10 +00003589 if (FDecl) {
3590 // Check if we have too few/too many template arguments, based
3591 // on our knowledge of the function definition.
3592 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003593 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003594 const FunctionProtoType *Proto
3595 = Def->getType()->getAs<FunctionProtoType>();
3596 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003597 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3598 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003599 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003600
3601 // If the function we're calling isn't a function prototype, but we have
3602 // a function prototype from a prior declaratiom, use that prototype.
3603 if (!FDecl->hasPrototype())
3604 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003605 }
3606
Steve Naroff0b661582007-08-28 23:30:39 +00003607 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003608 for (unsigned i = 0; i != NumArgs; i++) {
3609 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003610
3611 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003612 InitializedEntity Entity
3613 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003614 Proto->getArgType(i),
3615 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003616 ExprResult ArgE = PerformCopyInitialization(Entity,
3617 SourceLocation(),
3618 Owned(Arg));
3619 if (ArgE.isInvalid())
3620 return true;
3621
3622 Arg = ArgE.takeAs<Expr>();
3623
3624 } else {
John Wiegley01296292011-04-08 18:41:53 +00003625 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3626
3627 if (ArgE.isInvalid())
3628 return true;
3629
3630 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003631 }
3632
Douglas Gregor83025412010-10-26 05:45:40 +00003633 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3634 Arg->getType(),
3635 PDiag(diag::err_call_incomplete_argument)
3636 << Arg->getSourceRange()))
3637 return ExprError();
3638
Chris Lattner08464942007-12-28 05:29:59 +00003639 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003640 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003641 }
Chris Lattner08464942007-12-28 05:29:59 +00003642
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003643 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3644 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003645 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3646 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003647
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003648 // Check for sentinels
3649 if (NDecl)
3650 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003651
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003652 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003653 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003654 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003655 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003656
John McCallbebede42011-02-26 05:39:39 +00003657 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003658 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003659 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003660 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003661 return ExprError();
3662 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003663
John McCallb268a282010-08-23 23:25:46 +00003664 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003665}
3666
John McCalldadc5752010-08-24 06:29:42 +00003667ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003668Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003669 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003670 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003671 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003672 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003673
3674 TypeSourceInfo *TInfo;
3675 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3676 if (!TInfo)
3677 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3678
John McCallb268a282010-08-23 23:25:46 +00003679 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003680}
3681
John McCalldadc5752010-08-24 06:29:42 +00003682ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003683Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003684 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003685 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003686
Eli Friedman37a186d2008-05-20 05:22:08 +00003687 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003688 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3689 PDiag(diag::err_illegal_decl_array_incomplete_type)
3690 << SourceRange(LParenLoc,
3691 literalExpr->getSourceRange().getEnd())))
3692 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003693 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003694 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3695 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003696 } else if (!literalType->isDependentType() &&
3697 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003698 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003699 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003700 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003701 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003702
Douglas Gregor85dabae2009-12-16 01:38:02 +00003703 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003704 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003705 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003706 = InitializationKind::CreateCStyleCast(LParenLoc,
3707 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003708 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003709 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003710 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003711 &literalType);
3712 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003713 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003714 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003715
Chris Lattner79413952008-12-04 23:50:19 +00003716 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003717 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003718 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003719 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003720 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003721
John McCall7decc9e2010-11-18 06:31:45 +00003722 // In C, compound literals are l-values for some reason.
3723 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3724
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003725 return MaybeBindToTemporary(
3726 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3727 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003728}
3729
John McCalldadc5752010-08-24 06:29:42 +00003730ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003731Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003732 SourceLocation RBraceLoc) {
3733 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003734 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003735
Steve Naroff30d242c2007-09-15 18:49:24 +00003736 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003737 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003738
Ted Kremenekac034612010-04-13 23:39:13 +00003739 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3740 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003741 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003742 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003743}
3744
John McCalld7646252010-11-14 08:17:51 +00003745/// Prepares for a scalar cast, performing all the necessary stages
3746/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003747static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003748 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3749 // Also, callers should have filtered out the invalid cases with
3750 // pointers. Everything else should be possible.
3751
John Wiegley01296292011-04-08 18:41:53 +00003752 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003753 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003754 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003755
John McCall8cb679e2010-11-15 09:13:47 +00003756 switch (SrcTy->getScalarTypeKind()) {
3757 case Type::STK_MemberPointer:
3758 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003759
John McCall8cb679e2010-11-15 09:13:47 +00003760 case Type::STK_Pointer:
3761 switch (DestTy->getScalarTypeKind()) {
3762 case Type::STK_Pointer:
3763 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003764 CK_AnyPointerToObjCPointerCast :
3765 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003766 case Type::STK_Bool:
3767 return CK_PointerToBoolean;
3768 case Type::STK_Integral:
3769 return CK_PointerToIntegral;
3770 case Type::STK_Floating:
3771 case Type::STK_FloatingComplex:
3772 case Type::STK_IntegralComplex:
3773 case Type::STK_MemberPointer:
3774 llvm_unreachable("illegal cast from pointer");
3775 }
3776 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003777
John McCall8cb679e2010-11-15 09:13:47 +00003778 case Type::STK_Bool: // casting from bool is like casting from an integer
3779 case Type::STK_Integral:
3780 switch (DestTy->getScalarTypeKind()) {
3781 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00003782 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003783 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003784 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003785 case Type::STK_Bool:
3786 return CK_IntegralToBoolean;
3787 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003788 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003789 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003790 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003791 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003792 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3793 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003794 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003795 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003796 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3797 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003798 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003799 case Type::STK_MemberPointer:
3800 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003801 }
3802 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003803
John McCall8cb679e2010-11-15 09:13:47 +00003804 case Type::STK_Floating:
3805 switch (DestTy->getScalarTypeKind()) {
3806 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003807 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003808 case Type::STK_Bool:
3809 return CK_FloatingToBoolean;
3810 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003811 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003812 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00003813 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3814 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003815 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003816 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00003817 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3818 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003819 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003820 case Type::STK_Pointer:
3821 llvm_unreachable("valid float->pointer cast?");
3822 case Type::STK_MemberPointer:
3823 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003824 }
3825 break;
3826
John McCall8cb679e2010-11-15 09:13:47 +00003827 case Type::STK_FloatingComplex:
3828 switch (DestTy->getScalarTypeKind()) {
3829 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003830 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003831 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003832 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003833 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003834 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003835 if (S.Context.hasSameType(ET, DestTy))
3836 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003837 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003838 return CK_FloatingCast;
3839 }
John McCall8cb679e2010-11-15 09:13:47 +00003840 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003841 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003842 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00003843 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3844 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003845 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003846 case Type::STK_Pointer:
3847 llvm_unreachable("valid complex float->pointer cast?");
3848 case Type::STK_MemberPointer:
3849 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003850 }
3851 break;
3852
John McCall8cb679e2010-11-15 09:13:47 +00003853 case Type::STK_IntegralComplex:
3854 switch (DestTy->getScalarTypeKind()) {
3855 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003856 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003857 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003858 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003859 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003860 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003861 if (S.Context.hasSameType(ET, DestTy))
3862 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003863 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003864 return CK_IntegralCast;
3865 }
John McCall8cb679e2010-11-15 09:13:47 +00003866 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003867 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003868 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00003869 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3870 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003871 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003872 case Type::STK_Pointer:
3873 llvm_unreachable("valid complex int->pointer cast?");
3874 case Type::STK_MemberPointer:
3875 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003876 }
3877 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003878 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003879
John McCalld7646252010-11-14 08:17:51 +00003880 llvm_unreachable("Unhandled scalar cast");
3881 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003882}
3883
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003884/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003885ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3886 QualType castType, Expr *castExpr,
3887 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003888 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003889 if (castExpr->getType() == Context.UnknownAnyTy)
3890 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3891
Sebastian Redl9f831db2009-07-25 15:41:38 +00003892 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003893 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003894 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003895 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003896 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003897
John McCall3aef3d82011-04-10 19:13:55 +00003898 assert(!castExpr->getType()->isPlaceholderType());
3899
John McCall7decc9e2010-11-18 06:31:45 +00003900 // We only support r-value casts in C.
3901 VK = VK_RValue;
3902
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003903 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3904 // type needs to be scalar.
3905 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00003906 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00003907 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3908 if (castExprRes.isInvalid())
3909 return ExprError();
3910 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003911
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003912 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00003913 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00003914 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00003915 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003916
John Wiegley01296292011-04-08 18:41:53 +00003917 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3918 if (castExprRes.isInvalid())
3919 return ExprError();
3920 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00003921
Eli Friedmane98194d2010-07-17 20:43:49 +00003922 if (RequireCompleteType(TyR.getBegin(), castType,
3923 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00003924 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00003925
Anders Carlssonef918ac2009-10-16 02:35:04 +00003926 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003927 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003928 (castType->isStructureType() || castType->isUnionType())) {
3929 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003930 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003931 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3932 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003933 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00003934 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00003935 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003936
Anders Carlsson525b76b2009-10-16 02:48:28 +00003937 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003938 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003939 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003940 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003941 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003942 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003943 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00003944 castExpr->getType()) &&
3945 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3947 << castExpr->getSourceRange();
3948 break;
3949 }
3950 }
John Wiegley01296292011-04-08 18:41:53 +00003951 if (Field == FieldEnd) {
3952 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003953 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003954 return ExprError();
3955 }
John McCalle3027922010-08-25 11:45:40 +00003956 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00003957 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003958 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003959
Anders Carlsson525b76b2009-10-16 02:48:28 +00003960 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00003961 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00003962 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003963 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003964 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003965
John McCalld7646252010-11-14 08:17:51 +00003966 // The type we're casting to is known to be a scalar or vector.
3967
3968 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003969 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003970 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00003971 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003972 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003973 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003974 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003975 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003976
3977 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00003978 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
Anton Yartsev28ccef72011-03-27 09:32:40 +00003980 if (castType->isVectorType()) {
3981 if (castType->getAs<VectorType>()->getVectorKind() ==
3982 VectorType::AltiVecVector &&
3983 (castExpr->getType()->isIntegerType() ||
3984 castExpr->getType()->isFloatingType())) {
3985 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00003986 return Owned(castExpr);
3987 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
3988 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00003989 } else
John Wiegley01296292011-04-08 18:41:53 +00003990 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00003991 }
John Wiegley01296292011-04-08 18:41:53 +00003992 if (castExpr->getType()->isVectorType()) {
3993 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
3994 return ExprError();
3995 else
3996 return Owned(castExpr);
3997 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003998
John McCalld7646252010-11-14 08:17:51 +00003999 // The source and target types are both scalars, i.e.
4000 // - arithmetic types (fundamental, enum, and complex)
4001 // - all kinds of pointers
4002 // Note that member pointers were filtered out with C++, above.
4003
John Wiegley01296292011-04-08 18:41:53 +00004004 if (isa<ObjCSelectorExpr>(castExpr)) {
4005 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4006 return ExprError();
4007 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004008
John McCalld7646252010-11-14 08:17:51 +00004009 // If either type is a pointer, the other type has to be either an
4010 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004011 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004012 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004013 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004014 castExprType->isArithmeticType()) {
4015 Diag(castExpr->getLocStart(),
4016 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004017 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004018 return ExprError();
4019 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004020 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004021 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4022 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004023 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004024 return ExprError();
4025 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004026 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004027
John McCall31168b02011-06-15 23:02:42 +00004028 if (getLangOptions().ObjCAutoRefCount) {
4029 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4030 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4031 castType, castExpr, CCK_CStyleCast);
4032
4033 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4034 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4035 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4036 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4037 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4038 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4039 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4040 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004041 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004042 << castExprType << castType << AA_Casting
4043 << castExpr->getSourceRange();
4044
4045 return ExprError();
4046 }
4047 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004048 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004049 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4050 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004051 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004052 << castExprType << castType
4053 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004054 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004055 }
4056 }
4057
John Wiegley01296292011-04-08 18:41:53 +00004058 castExprRes = Owned(castExpr);
4059 Kind = PrepareScalarCast(*this, castExprRes, castType);
4060 if (castExprRes.isInvalid())
4061 return ExprError();
4062 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004063
John McCalld7646252010-11-14 08:17:51 +00004064 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004065 CheckCastAlign(castExpr, castType, TyR);
4066
John Wiegley01296292011-04-08 18:41:53 +00004067 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004068}
4069
Anders Carlsson525b76b2009-10-16 02:48:28 +00004070bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004071 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004072 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004073
Anders Carlssonde71adf2007-11-27 05:51:55 +00004074 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004075 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004076 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004077 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004078 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004079 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004080 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004081 } else
4082 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004083 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004084 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004085
John McCalle3027922010-08-25 11:45:40 +00004086 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004087 return false;
4088}
4089
John Wiegley01296292011-04-08 18:41:53 +00004090ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4091 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004092 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004093
Anders Carlsson43d70f82009-10-16 05:23:41 +00004094 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004095
Nate Begemanc8961a42009-06-27 22:05:55 +00004096 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4097 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004098 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004099 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4100 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004101 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004102 return ExprError();
4103 }
John McCalle3027922010-08-25 11:45:40 +00004104 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004105 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004106 }
4107
Nate Begemanbd956c42009-06-28 02:36:38 +00004108 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004109 // conversion will take place first from scalar to elt type, and then
4110 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004111 if (SrcTy->isPointerType())
4112 return Diag(R.getBegin(),
4113 diag::err_invalid_conversion_between_vector_and_scalar)
4114 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004115
4116 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004117 ExprResult CastExprRes = Owned(CastExpr);
4118 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4119 if (CastExprRes.isInvalid())
4120 return ExprError();
4121 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004122
John McCalle3027922010-08-25 11:45:40 +00004123 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004124 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004125}
4126
John McCalldadc5752010-08-24 06:29:42 +00004127ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004128Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4129 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004130 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004131 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004132 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004133
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004134 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4135 if (D.isInvalidType())
4136 return ExprError();
4137
4138 if (getLangOptions().CPlusPlus) {
4139 // Check that there are no default arguments (C++ only).
4140 CheckExtraCXXDefaultArguments(D);
4141 }
4142
4143 QualType castType = castTInfo->getType();
4144 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004145
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004146 bool isVectorLiteral = false;
4147
4148 // Check for an altivec or OpenCL literal,
4149 // i.e. all the elements are integer constants.
4150 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4151 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4152 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4153 if (PLE && PLE->getNumExprs() == 0) {
4154 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4155 return ExprError();
4156 }
4157 if (PE || PLE->getNumExprs() == 1) {
4158 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4159 if (!E->getType()->isVectorType())
4160 isVectorLiteral = true;
4161 }
4162 else
4163 isVectorLiteral = true;
4164 }
4165
4166 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4167 // then handle it as such.
4168 if (isVectorLiteral)
4169 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4170
Nate Begeman5ec4b312009-08-10 23:49:36 +00004171 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004172 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4173 // sequence of BinOp comma operators.
4174 if (isa<ParenListExpr>(castExpr)) {
4175 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4176 if (Result.isInvalid()) return ExprError();
4177 castExpr = Result.take();
4178 }
John McCallebe54742010-01-15 18:56:44 +00004179
John McCallb268a282010-08-23 23:25:46 +00004180 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004181}
4182
John McCalldadc5752010-08-24 06:29:42 +00004183ExprResult
John McCallebe54742010-01-15 18:56:44 +00004184Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004185 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004186 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004187 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004188 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004189 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004190 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4191 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004192 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004193 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004194 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004195
John McCallcf142162010-08-07 06:22:56 +00004196 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00004197 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004198 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004199 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004200}
4201
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004202ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4203 SourceLocation RParenLoc, Expr *E,
4204 TypeSourceInfo *TInfo) {
4205 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4206 "Expected paren or paren list expression");
4207
4208 Expr **exprs;
4209 unsigned numExprs;
4210 Expr *subExpr;
4211 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4212 exprs = PE->getExprs();
4213 numExprs = PE->getNumExprs();
4214 } else {
4215 subExpr = cast<ParenExpr>(E)->getSubExpr();
4216 exprs = &subExpr;
4217 numExprs = 1;
4218 }
4219
4220 QualType Ty = TInfo->getType();
4221 assert(Ty->isVectorType() && "Expected vector type");
4222
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004223 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004224 const VectorType *VTy = Ty->getAs<VectorType>();
4225 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4226
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004227 // '(...)' form of vector initialization in AltiVec: the number of
4228 // initializers must be one or must match the size of the vector.
4229 // If a single value is specified in the initializer then it will be
4230 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004231 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004232 // The number of initializers must be one or must match the size of the
4233 // vector. If a single value is specified in the initializer then it will
4234 // be replicated to all the components of the vector
4235 if (numExprs == 1) {
4236 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4237 ExprResult Literal = Owned(exprs[0]);
4238 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4239 PrepareScalarCast(*this, Literal, ElemTy));
4240 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4241 }
4242 else if (numExprs < numElems) {
4243 Diag(E->getExprLoc(),
4244 diag::err_incorrect_number_of_vector_initializers);
4245 return ExprError();
4246 }
4247 else
4248 for (unsigned i = 0, e = numExprs; i != e; ++i)
4249 initExprs.push_back(exprs[i]);
4250 }
Tanya Lattner83559382011-07-15 23:07:01 +00004251 else {
4252 // For OpenCL, when the number of initializers is a single value,
4253 // it will be replicated to all components of the vector.
4254 if (getLangOptions().OpenCL &&
4255 VTy->getVectorKind() == VectorType::GenericVector &&
4256 numExprs == 1) {
4257 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4258 ExprResult Literal = Owned(exprs[0]);
4259 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4260 PrepareScalarCast(*this, Literal, ElemTy));
4261 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4262 }
4263
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004264 for (unsigned i = 0, e = numExprs; i != e; ++i)
4265 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004266 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004267 // FIXME: This means that pretty-printing the final AST will produce curly
4268 // braces instead of the original commas.
4269 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4270 &initExprs[0],
4271 initExprs.size(), RParenLoc);
4272 initE->setType(Ty);
4273 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4274}
4275
Nate Begeman5ec4b312009-08-10 23:49:36 +00004276/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4277/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004278ExprResult
John McCallb268a282010-08-23 23:25:46 +00004279Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004280 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4281 if (!E)
4282 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004283
John McCalldadc5752010-08-24 06:29:42 +00004284 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004285
Nate Begeman5ec4b312009-08-10 23:49:36 +00004286 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004287 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4288 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004289
John McCallb268a282010-08-23 23:25:46 +00004290 if (Result.isInvalid()) return ExprError();
4291
4292 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004293}
4294
John McCalldadc5752010-08-24 06:29:42 +00004295ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004296 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004297 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004298 unsigned nexprs = Val.size();
4299 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004300 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4301 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004302 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004303 expr = new (Context) ParenExpr(L, R, exprs[0]);
4304 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004305 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4306 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004307 return Owned(expr);
4308}
4309
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004310/// \brief Emit a specialized diagnostic when one expression is a null pointer
4311/// constant and the other is not a pointer.
4312bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4313 SourceLocation QuestionLoc) {
4314 Expr *NullExpr = LHS;
4315 Expr *NonPointerExpr = RHS;
4316 Expr::NullPointerConstantKind NullKind =
4317 NullExpr->isNullPointerConstant(Context,
4318 Expr::NPC_ValueDependentIsNotNull);
4319
4320 if (NullKind == Expr::NPCK_NotNull) {
4321 NullExpr = RHS;
4322 NonPointerExpr = LHS;
4323 NullKind =
4324 NullExpr->isNullPointerConstant(Context,
4325 Expr::NPC_ValueDependentIsNotNull);
4326 }
4327
4328 if (NullKind == Expr::NPCK_NotNull)
4329 return false;
4330
4331 if (NullKind == Expr::NPCK_ZeroInteger) {
4332 // In this case, check to make sure that we got here from a "NULL"
4333 // string in the source code.
4334 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004335 SourceLocation loc = NullExpr->getExprLoc();
4336 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004337 return false;
4338 }
4339
4340 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4341 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4342 << NonPointerExpr->getType() << DiagType
4343 << NonPointerExpr->getSourceRange();
4344 return true;
4345}
4346
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004347/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4348/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004349/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00004350QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004351 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004352 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004353
John McCall3aef3d82011-04-10 19:13:55 +00004354 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004355 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004356 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004357
John McCall3aef3d82011-04-10 19:13:55 +00004358 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004359 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004360 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004361
Sebastian Redl1a99f442009-04-16 17:51:27 +00004362 // C++ is sufficiently different to merit its own checker.
4363 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004364 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004365
4366 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004367 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004368
John Wiegley01296292011-04-08 18:41:53 +00004369 Cond = UsualUnaryConversions(Cond.take());
4370 if (Cond.isInvalid())
4371 return QualType();
4372 LHS = UsualUnaryConversions(LHS.take());
4373 if (LHS.isInvalid())
4374 return QualType();
4375 RHS = UsualUnaryConversions(RHS.take());
4376 if (RHS.isInvalid())
4377 return QualType();
4378
4379 QualType CondTy = Cond.get()->getType();
4380 QualType LHSTy = LHS.get()->getType();
4381 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004382
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004383 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004384 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004385 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4386 // Throw an error if its not either.
4387 if (getLangOptions().OpenCL) {
4388 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004389 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004390 diag::err_typecheck_cond_expect_scalar_or_vector)
4391 << CondTy;
4392 return QualType();
4393 }
4394 }
4395 else {
John Wiegley01296292011-04-08 18:41:53 +00004396 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004397 << CondTy;
4398 return QualType();
4399 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004400 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004401
Chris Lattnere2949f42008-01-06 22:42:25 +00004402 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004403 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004404 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004405
Nate Begemanabb5a732010-09-20 22:41:17 +00004406 // OpenCL: If the condition is a vector, and both operands are scalar,
4407 // attempt to implicity convert them to the vector type to act like the
4408 // built in select.
4409 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4410 // Both operands should be of scalar type.
4411 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004412 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004413 << CondTy;
4414 return QualType();
4415 }
4416 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004417 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004418 << CondTy;
4419 return QualType();
4420 }
4421 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004422 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4423 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004424 }
4425
Chris Lattnere2949f42008-01-06 22:42:25 +00004426 // If both operands have arithmetic type, do the usual arithmetic conversions
4427 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004428 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4429 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004430 if (LHS.isInvalid() || RHS.isInvalid())
4431 return QualType();
4432 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004433 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004434
Chris Lattnere2949f42008-01-06 22:42:25 +00004435 // If both operands are the same structure or union type, the result is that
4436 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004437 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4438 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004439 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004440 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004441 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004442 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004443 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004444 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004445
Chris Lattnere2949f42008-01-06 22:42:25 +00004446 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004447 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004448 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4449 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004450 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4451 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004452 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004453 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4454 << LHS.get()->getSourceRange();
4455 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4456 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004457 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004458 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004459 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4460 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004461 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004462 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004463 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004464 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004465 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004466 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004467 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00004468 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4469 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004470 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004471 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004472
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004473 // All objective-c pointer type analysis is done here.
4474 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4475 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004476 if (LHS.isInvalid() || RHS.isInvalid())
4477 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004478 if (!compositeType.isNull())
4479 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004480
4481
Steve Naroff05efa972009-07-01 14:36:47 +00004482 // Handle block pointer types.
4483 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4484 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4485 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4486 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004487 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4488 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004489 return destType;
4490 }
4491 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004492 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004493 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004494 }
Steve Naroff05efa972009-07-01 14:36:47 +00004495 // We have 2 block pointer types.
4496 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4497 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004498 return LHSTy;
4499 }
Steve Naroff05efa972009-07-01 14:36:47 +00004500 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004501 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4502 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004503
Steve Naroff05efa972009-07-01 14:36:47 +00004504 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4505 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004506 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004507 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004508 // In this situation, we assume void* type. No especially good
4509 // reason, but this is what gcc does, and we do have to pick
4510 // to get a consistent AST.
4511 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004512 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4513 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004514 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004515 }
Steve Naroff05efa972009-07-01 14:36:47 +00004516 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004517 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4518 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004519 return LHSTy;
4520 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004521
Steve Naroff05efa972009-07-01 14:36:47 +00004522 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4523 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4524 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004525 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4526 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004527
4528 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4529 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4530 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004531 QualType destPointee
4532 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004533 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004534 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004535 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004536 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004537 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004538 return destType;
4539 }
4540 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004541 QualType destPointee
4542 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004543 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004544 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004545 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004546 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004547 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004548 return destType;
4549 }
4550
4551 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4552 // Two identical pointer types are always compatible.
4553 return LHSTy;
4554 }
4555 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4556 rhptee.getUnqualifiedType())) {
4557 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00004558 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004559 // In this situation, we assume void* type. No especially good
4560 // reason, but this is what gcc does, and we do have to pick
4561 // to get a consistent AST.
4562 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004563 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4564 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004565 return incompatTy;
4566 }
4567 // The pointer types are compatible.
4568 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4569 // differently qualified versions of compatible types, the result type is
4570 // a pointer to an appropriately qualified version of the *composite*
4571 // type.
4572 // FIXME: Need to calculate the composite type.
4573 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004574 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4575 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004576 return LHSTy;
4577 }
Mike Stump11289f42009-09-09 15:08:12 +00004578
John McCalle84af4e2010-11-13 01:35:44 +00004579 // GCC compatibility: soften pointer/integer mismatch. Note that
4580 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004581 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4582 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004583 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4584 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004585 return RHSTy;
4586 }
4587 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4588 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00004589 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4590 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004591 return LHSTy;
4592 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004593
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004594 // Emit a better diagnostic if one of the expressions is a null pointer
4595 // constant and the other is not a pointer type. In this case, the user most
4596 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004597 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004598 return QualType();
4599
Chris Lattnere2949f42008-01-06 22:42:25 +00004600 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004601 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004602 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004603 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004604}
4605
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004606/// FindCompositeObjCPointerType - Helper method to find composite type of
4607/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004608QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004609 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004610 QualType LHSTy = LHS.get()->getType();
4611 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004612
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004613 // Handle things like Class and struct objc_class*. Here we case the result
4614 // to the pseudo-builtin, because that will be implicitly cast back to the
4615 // redefinition type if an attempt is made to access its fields.
4616 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004617 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004618 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004619 return LHSTy;
4620 }
4621 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004622 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004623 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004624 return RHSTy;
4625 }
4626 // And the same for struct objc_object* / id
4627 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004628 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004629 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004630 return LHSTy;
4631 }
4632 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004633 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004634 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004635 return RHSTy;
4636 }
4637 // And the same for struct objc_selector* / SEL
4638 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004639 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004640 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004641 return LHSTy;
4642 }
4643 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004644 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004645 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004646 return RHSTy;
4647 }
4648 // Check constraints for Objective-C object pointers types.
4649 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004650
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004651 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4652 // Two identical object pointer types are always compatible.
4653 return LHSTy;
4654 }
4655 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4656 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4657 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004658
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004659 // If both operands are interfaces and either operand can be
4660 // assigned to the other, use that type as the composite
4661 // type. This allows
4662 // xxx ? (A*) a : (B*) b
4663 // where B is a subclass of A.
4664 //
4665 // Additionally, as for assignment, if either type is 'id'
4666 // allow silent coercion. Finally, if the types are
4667 // incompatible then make sure to use 'id' as the composite
4668 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004669
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004670 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4671 // It could return the composite type.
4672 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4673 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4674 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4675 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4676 } else if ((LHSTy->isObjCQualifiedIdType() ||
4677 RHSTy->isObjCQualifiedIdType()) &&
4678 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4679 // Need to handle "id<xx>" explicitly.
4680 // GCC allows qualified id and any Objective-C type to devolve to
4681 // id. Currently localizing to here until clear this should be
4682 // part of ObjCQualifiedIdTypesAreCompatible.
4683 compositeType = Context.getObjCIdType();
4684 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4685 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004686 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004687 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4688 ;
4689 else {
4690 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4691 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004692 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004693 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004694 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4695 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004696 return incompatTy;
4697 }
4698 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004699 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4700 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004701 return compositeType;
4702 }
4703 // Check Objective-C object pointer types and 'void *'
4704 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4705 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4706 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4707 QualType destPointee
4708 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4709 QualType destType = Context.getPointerType(destPointee);
4710 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004711 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004712 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004713 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004714 return destType;
4715 }
4716 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4717 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4718 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4719 QualType destPointee
4720 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4721 QualType destType = Context.getPointerType(destPointee);
4722 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004723 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004724 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004725 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004726 return destType;
4727 }
4728 return QualType();
4729}
4730
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004731/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004732/// ParenRange in parentheses.
4733static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004734 const PartialDiagnostic &Note,
4735 SourceRange ParenRange) {
4736 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4737 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4738 EndLoc.isValid()) {
4739 Self.Diag(Loc, Note)
4740 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4741 << FixItHint::CreateInsertion(EndLoc, ")");
4742 } else {
4743 // We can't display the parentheses, so just show the bare note.
4744 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004745 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004746}
4747
4748static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4749 return Opc >= BO_Mul && Opc <= BO_Shr;
4750}
4751
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004752/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4753/// expression, either using a built-in or overloaded operator,
4754/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4755static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4756 Expr **RHS) {
4757 E = E->IgnoreParenImpCasts();
4758 E = E->IgnoreConversionOperator();
4759 E = E->IgnoreParenImpCasts();
4760
4761 // Built-in binary operator.
4762 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4763 if (IsArithmeticOp(OP->getOpcode())) {
4764 *Opcode = OP->getOpcode();
4765 *RHS = OP->getRHS();
4766 return true;
4767 }
4768 }
4769
4770 // Overloaded operator.
4771 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4772 if (Call->getNumArgs() != 2)
4773 return false;
4774
4775 // Make sure this is really a binary operator that is safe to pass into
4776 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4777 OverloadedOperatorKind OO = Call->getOperator();
4778 if (OO < OO_Plus || OO > OO_Arrow)
4779 return false;
4780
4781 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4782 if (IsArithmeticOp(OpKind)) {
4783 *Opcode = OpKind;
4784 *RHS = Call->getArg(1);
4785 return true;
4786 }
4787 }
4788
4789 return false;
4790}
4791
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004792static bool IsLogicOp(BinaryOperatorKind Opc) {
4793 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4794}
4795
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004796/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4797/// or is a logical expression such as (x==y) which has int type, but is
4798/// commonly interpreted as boolean.
4799static bool ExprLooksBoolean(Expr *E) {
4800 E = E->IgnoreParenImpCasts();
4801
4802 if (E->getType()->isBooleanType())
4803 return true;
4804 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4805 return IsLogicOp(OP->getOpcode());
4806 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4807 return OP->getOpcode() == UO_LNot;
4808
4809 return false;
4810}
4811
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004812/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4813/// and binary operator are mixed in a way that suggests the programmer assumed
4814/// the conditional operator has higher precedence, for example:
4815/// "int x = a + someBinaryCondition ? 1 : 2".
4816static void DiagnoseConditionalPrecedence(Sema &Self,
4817 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004818 Expr *Condition,
4819 Expr *LHS,
4820 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004821 BinaryOperatorKind CondOpcode;
4822 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004823
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004824 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004825 return;
4826 if (!ExprLooksBoolean(CondRHS))
4827 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004828
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004829 // The condition is an arithmetic binary expression, with a right-
4830 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004831
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004832 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004833 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004834 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004835
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004836 SuggestParentheses(Self, OpLoc,
4837 Self.PDiag(diag::note_precedence_conditional_silence)
4838 << BinaryOperator::getOpcodeStr(CondOpcode),
4839 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004840
4841 SuggestParentheses(Self, OpLoc,
4842 Self.PDiag(diag::note_precedence_conditional_first),
4843 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004844}
4845
Steve Naroff83895f72007-09-16 03:34:24 +00004846/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004847/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004848ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004849 SourceLocation ColonLoc,
4850 Expr *CondExpr, Expr *LHSExpr,
4851 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004852 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4853 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004854 OpaqueValueExpr *opaqueValue = 0;
4855 Expr *commonExpr = 0;
4856 if (LHSExpr == 0) {
4857 commonExpr = CondExpr;
4858
4859 // We usually want to apply unary conversions *before* saving, except
4860 // in the special case of a C++ l-value conditional.
4861 if (!(getLangOptions().CPlusPlus
4862 && !commonExpr->isTypeDependent()
4863 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4864 && commonExpr->isGLValue()
4865 && commonExpr->isOrdinaryOrBitFieldObject()
4866 && RHSExpr->isOrdinaryOrBitFieldObject()
4867 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004868 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4869 if (commonRes.isInvalid())
4870 return ExprError();
4871 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004872 }
4873
4874 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4875 commonExpr->getType(),
4876 commonExpr->getValueKind(),
4877 commonExpr->getObjectKind());
4878 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004879 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004880
John McCall7decc9e2010-11-18 06:31:45 +00004881 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004882 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004883 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4884 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004885 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004886 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4887 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004888 return ExprError();
4889
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004890 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4891 RHS.get());
4892
John McCallc07a0c72011-02-17 10:25:35 +00004893 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004894 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4895 LHS.take(), ColonLoc,
4896 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004897
4898 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004899 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4900 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00004901}
4902
John McCallaba90822011-01-31 23:13:11 +00004903// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004904// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004905// routine is it effectively iqnores the qualifiers on the top level pointee.
4906// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4907// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00004908static Sema::AssignConvertType
4909checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4910 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4911 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004912
Steve Naroff1f4d7272007-05-11 04:00:31 +00004913 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00004914 const Type *lhptee, *rhptee;
4915 Qualifiers lhq, rhq;
4916 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4917 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004918
John McCallaba90822011-01-31 23:13:11 +00004919 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004920
4921 // C99 6.5.16.1p1: This following citation is common to constraints
4922 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4923 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00004924 Qualifiers lq;
4925
John McCall31168b02011-06-15 23:02:42 +00004926 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4927 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4928 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4929 // Ignore lifetime for further calculation.
4930 lhq.removeObjCLifetime();
4931 rhq.removeObjCLifetime();
4932 }
4933
John McCall4fff8f62011-02-01 00:10:29 +00004934 if (!lhq.compatiblyIncludes(rhq)) {
4935 // Treat address-space mismatches as fatal. TODO: address subspaces
4936 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4937 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4938
John McCall31168b02011-06-15 23:02:42 +00004939 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00004940 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00004941 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4942 .compatiblyIncludes(
4943 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00004944 && (lhptee->isVoidType() || rhptee->isVoidType()))
4945 ; // keep old
4946
John McCall31168b02011-06-15 23:02:42 +00004947 // Treat lifetime mismatches as fatal.
4948 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4949 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4950
John McCall4fff8f62011-02-01 00:10:29 +00004951 // For GCC compatibility, other qualifier mismatches are treated
4952 // as still compatible in C.
4953 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4954 }
Steve Naroff3f597292007-05-11 22:18:03 +00004955
Mike Stump4e1f26a2009-02-19 03:04:26 +00004956 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4957 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004958 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004959 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004960 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004961 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004962
Chris Lattner0a788432008-01-03 22:56:36 +00004963 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004964 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004965 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004966 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004967
Chris Lattner0a788432008-01-03 22:56:36 +00004968 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004969 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004970 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004971
4972 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004973 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00004974 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004975 }
John McCall4fff8f62011-02-01 00:10:29 +00004976
Mike Stump4e1f26a2009-02-19 03:04:26 +00004977 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004978 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00004979 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
4980 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004981 // Check if the pointee types are compatible ignoring the sign.
4982 // We explicitly check for char so that we catch "char" vs
4983 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004984 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004985 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004986 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004987 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004988
Chris Lattnerec3a1562009-10-17 20:33:28 +00004989 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00004990 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004991 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00004992 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004993
John McCall4fff8f62011-02-01 00:10:29 +00004994 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00004995 // Types are compatible ignoring the sign. Qualifier incompatibility
4996 // takes priority over sign incompatibility because the sign
4997 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00004998 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00004999 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005000
John McCallaba90822011-01-31 23:13:11 +00005001 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005002 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005003
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005004 // If we are a multi-level pointer, it's possible that our issue is simply
5005 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5006 // the eventual target type is the same and the pointers have the same
5007 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005008 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005009 do {
John McCall4fff8f62011-02-01 00:10:29 +00005010 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5011 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005012 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005013
John McCall4fff8f62011-02-01 00:10:29 +00005014 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005015 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005016 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005017
Eli Friedman80160bd2009-03-22 23:59:44 +00005018 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005019 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005020 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005021 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005022}
5023
John McCallaba90822011-01-31 23:13:11 +00005024/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005025/// block pointer types are compatible or whether a block and normal pointer
5026/// are compatible. It is more restrict than comparing two function pointer
5027// types.
John McCallaba90822011-01-31 23:13:11 +00005028static Sema::AssignConvertType
5029checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5030 QualType rhsType) {
5031 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5032 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5033
Steve Naroff081c7422008-09-04 15:10:53 +00005034 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005035
Steve Naroff081c7422008-09-04 15:10:53 +00005036 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005037 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5038 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005039
John McCallaba90822011-01-31 23:13:11 +00005040 // In C++, the types have to match exactly.
5041 if (S.getLangOptions().CPlusPlus)
5042 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005043
John McCallaba90822011-01-31 23:13:11 +00005044 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005045
Steve Naroff081c7422008-09-04 15:10:53 +00005046 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005047 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5048 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005049
John McCallaba90822011-01-31 23:13:11 +00005050 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5051 return Sema::IncompatibleBlockPointer;
5052
Steve Naroff081c7422008-09-04 15:10:53 +00005053 return ConvTy;
5054}
5055
John McCallaba90822011-01-31 23:13:11 +00005056/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005057/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005058static Sema::AssignConvertType
5059checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5060 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5061 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5062
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005063 if (lhsType->isObjCBuiltinType()) {
5064 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005065 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5066 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005067 return Sema::IncompatiblePointer;
5068 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005069 }
5070 if (rhsType->isObjCBuiltinType()) {
5071 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005072 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5073 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005074 return Sema::IncompatiblePointer;
5075 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005076 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005077 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005078 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005079 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005080 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005081
John McCallaba90822011-01-31 23:13:11 +00005082 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5083 return Sema::CompatiblePointerDiscardsQualifiers;
5084
5085 if (S.Context.typesAreCompatible(lhsType, rhsType))
5086 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005087 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005088 return Sema::IncompatibleObjCQualifiedId;
5089 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005090}
5091
John McCall29600e12010-11-16 02:32:08 +00005092Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005093Sema::CheckAssignmentConstraints(SourceLocation Loc,
5094 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005095 // Fake up an opaque expression. We don't actually care about what
5096 // cast operations are required, so if CheckAssignmentConstraints
5097 // adds casts to this they'll be wasted, but fortunately that doesn't
5098 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005099 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005100 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005101 CastKind K = CK_Invalid;
5102
5103 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5104}
5105
Mike Stump4e1f26a2009-02-19 03:04:26 +00005106/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5107/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005108/// pointers. Here are some objectionable examples that GCC considers warnings:
5109///
5110/// int a, *pint;
5111/// short *pshort;
5112/// struct foo *pfoo;
5113///
5114/// pint = pshort; // warning: assignment from incompatible pointer type
5115/// a = pint; // warning: assignment makes integer from pointer without a cast
5116/// pint = a; // warning: assignment makes pointer from integer without a cast
5117/// pint = pfoo; // warning: assignment from incompatible pointer type
5118///
5119/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005120/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005121///
John McCall8cb679e2010-11-15 09:13:47 +00005122/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005123Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005124Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005125 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005126 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005127 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005128
Chris Lattnera52c2f22008-01-04 23:18:45 +00005129 // Get canonical types. We're not formatting these types, just comparing
5130 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005131 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5132 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005133
John McCalle5255932011-01-31 22:28:28 +00005134 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005135 if (lhsType == rhsType) {
5136 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005137 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005138 }
5139
Douglas Gregor6b754842008-10-28 00:22:11 +00005140 // If the left-hand side is a reference type, then we are in a
5141 // (rare!) case where we've allowed the use of references in C,
5142 // e.g., as a parameter type in a built-in function. In this case,
5143 // just make sure that the type referenced is compatible with the
5144 // right-hand side type. The caller is responsible for adjusting
5145 // lhsType so that the resulting expression does not have reference
5146 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005147 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005148 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5149 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005150 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005151 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005152 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005153 }
John McCalle5255932011-01-31 22:28:28 +00005154
Nate Begemanbd956c42009-06-28 02:36:38 +00005155 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5156 // to the same ExtVector type.
5157 if (lhsType->isExtVectorType()) {
5158 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005159 return Incompatible;
5160 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005161 // CK_VectorSplat does T -> vector T, so first cast to the
5162 // element type.
5163 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5164 if (elType != rhsType) {
5165 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005166 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005167 }
5168 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005169 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005170 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
John McCalle5255932011-01-31 22:28:28 +00005173 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005174 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005175 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005176 // Allow assignments of an AltiVec vector type to an equivalent GCC
5177 // vector type and vice versa
5178 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5179 Kind = CK_BitCast;
5180 return Compatible;
5181 }
5182
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005183 // If we are allowing lax vector conversions, and LHS and RHS are both
5184 // vectors, the total size only needs to be the same. This is a bitcast;
5185 // no bits are changed but the result type is different.
5186 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005187 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005188 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005189 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005190 }
Chris Lattner881a2122008-01-04 23:32:24 +00005191 }
5192 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005193 }
Eli Friedman3360d892008-05-30 18:07:22 +00005194
John McCalle5255932011-01-31 22:28:28 +00005195 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005196 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005197 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005198 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005199 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005200 }
Eli Friedman3360d892008-05-30 18:07:22 +00005201
John McCalle5255932011-01-31 22:28:28 +00005202 // Conversions to normal pointers.
5203 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5204 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005205 if (isa<PointerType>(rhsType)) {
5206 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005207 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005208 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005209
John McCalle5255932011-01-31 22:28:28 +00005210 // int -> T*
5211 if (rhsType->isIntegerType()) {
5212 Kind = CK_IntegralToPointer; // FIXME: null?
5213 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005214 }
John McCalle5255932011-01-31 22:28:28 +00005215
5216 // C pointers are not compatible with ObjC object pointers,
5217 // with two exceptions:
5218 if (isa<ObjCObjectPointerType>(rhsType)) {
5219 // - conversions to void*
5220 if (lhsPointer->getPointeeType()->isVoidType()) {
5221 Kind = CK_AnyPointerToObjCPointerCast;
5222 return Compatible;
5223 }
5224
5225 // - conversions from 'Class' to the redefinition type
5226 if (rhsType->isObjCClassType() &&
5227 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005228 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005229 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005230 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005231
John McCalle5255932011-01-31 22:28:28 +00005232 Kind = CK_BitCast;
5233 return IncompatiblePointer;
5234 }
5235
5236 // U^ -> void*
5237 if (rhsType->getAs<BlockPointerType>()) {
5238 if (lhsPointer->getPointeeType()->isVoidType()) {
5239 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005240 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005241 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005242 }
John McCalle5255932011-01-31 22:28:28 +00005243
Steve Naroff081c7422008-09-04 15:10:53 +00005244 return Incompatible;
5245 }
5246
John McCalle5255932011-01-31 22:28:28 +00005247 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005248 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005249 // U^ -> T^
5250 if (rhsType->isBlockPointerType()) {
5251 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005252 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005253 }
5254
5255 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005256 if (rhsType->isIntegerType()) {
5257 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005258 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005259 }
5260
John McCalle5255932011-01-31 22:28:28 +00005261 // id -> T^
5262 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5263 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005264 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005265 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005266
John McCalle5255932011-01-31 22:28:28 +00005267 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005268 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005269 if (RHSPT->getPointeeType()->isVoidType()) {
5270 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005271 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005272 }
John McCall8cb679e2010-11-15 09:13:47 +00005273
Chris Lattnera52c2f22008-01-04 23:18:45 +00005274 return Incompatible;
5275 }
5276
John McCalle5255932011-01-31 22:28:28 +00005277 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005278 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005279 // A* -> B*
5280 if (rhsType->isObjCObjectPointerType()) {
5281 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005282 Sema::AssignConvertType result =
5283 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5284 if (getLangOptions().ObjCAutoRefCount &&
5285 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005286 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5287 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005288 return result;
John McCalle5255932011-01-31 22:28:28 +00005289 }
5290
5291 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005292 if (rhsType->isIntegerType()) {
5293 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005294 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005295 }
5296
John McCalle5255932011-01-31 22:28:28 +00005297 // In general, C pointers are not compatible with ObjC object pointers,
5298 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005299 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005300 // - conversions from 'void*'
5301 if (rhsType->isVoidPointerType()) {
5302 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005303 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005304 }
5305
5306 // - conversions to 'Class' from its redefinition type
5307 if (lhsType->isObjCClassType() &&
5308 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5309 Kind = CK_BitCast;
5310 return Compatible;
5311 }
5312
5313 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005314 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005315 }
John McCalle5255932011-01-31 22:28:28 +00005316
5317 // T^ -> A*
5318 if (rhsType->isBlockPointerType()) {
5319 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005320 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005321 }
5322
Steve Naroff7cae42b2009-07-10 23:34:53 +00005323 return Incompatible;
5324 }
John McCalle5255932011-01-31 22:28:28 +00005325
5326 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005327 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005328 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005329 if (lhsType == Context.BoolTy) {
5330 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005331 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005332 }
Eli Friedman3360d892008-05-30 18:07:22 +00005333
John McCalle5255932011-01-31 22:28:28 +00005334 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005335 if (lhsType->isIntegerType()) {
5336 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005337 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005338 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005339
Chris Lattnera52c2f22008-01-04 23:18:45 +00005340 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005341 }
John McCalle5255932011-01-31 22:28:28 +00005342
5343 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005344 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005345 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005346 if (lhsType == Context.BoolTy) {
5347 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005348 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005349 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005350
John McCalle5255932011-01-31 22:28:28 +00005351 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005352 if (lhsType->isIntegerType()) {
5353 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005354 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005355 }
5356
Steve Naroff7cae42b2009-07-10 23:34:53 +00005357 return Incompatible;
5358 }
Eli Friedman3360d892008-05-30 18:07:22 +00005359
John McCalle5255932011-01-31 22:28:28 +00005360 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005361 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005362 if (Context.typesAreCompatible(lhsType, rhsType)) {
5363 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005364 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005365 }
Bill Wendling216423b2007-05-30 06:30:29 +00005366 }
John McCalle5255932011-01-31 22:28:28 +00005367
Steve Naroff98cf3e92007-06-06 18:38:38 +00005368 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005369}
5370
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005371/// \brief Constructs a transparent union from an expression that is
5372/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005373static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005374 QualType UnionType, FieldDecl *Field) {
5375 // Build an initializer list that designates the appropriate member
5376 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005377 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005378 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005379 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005380 SourceLocation());
5381 Initializer->setType(UnionType);
5382 Initializer->setInitializedFieldInUnion(Field);
5383
5384 // Build a compound literal constructing a value of the transparent
5385 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005386 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005387 EResult = S.Owned(
5388 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5389 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005390}
5391
5392Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005393Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5394 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005395
Mike Stump11289f42009-09-09 15:08:12 +00005396 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005397 // transparent_union GCC extension.
5398 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005399 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005400 return Incompatible;
5401
5402 // The field to initialize within the transparent union.
5403 RecordDecl *UD = UT->getDecl();
5404 FieldDecl *InitField = 0;
5405 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005406 for (RecordDecl::field_iterator it = UD->field_begin(),
5407 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005408 it != itend; ++it) {
5409 if (it->getType()->isPointerType()) {
5410 // If the transparent union contains a pointer type, we allow:
5411 // 1) void pointer
5412 // 2) null pointer constant
5413 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005414 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005415 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005416 InitField = *it;
5417 break;
5418 }
Mike Stump11289f42009-09-09 15:08:12 +00005419
John Wiegley01296292011-04-08 18:41:53 +00005420 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005421 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005422 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005423 InitField = *it;
5424 break;
5425 }
5426 }
5427
John McCall8cb679e2010-11-15 09:13:47 +00005428 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005429 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005430 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005431 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005432 InitField = *it;
5433 break;
5434 }
5435 }
5436
5437 if (!InitField)
5438 return Incompatible;
5439
John Wiegley01296292011-04-08 18:41:53 +00005440 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005441 return Compatible;
5442}
5443
Chris Lattner9bad62c2008-01-04 18:04:52 +00005444Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005445Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005446 if (getLangOptions().CPlusPlus) {
5447 if (!lhsType->isRecordType()) {
5448 // C++ 5.17p3: If the left operand is not of class type, the
5449 // expression is implicitly converted (C++ 4) to the
5450 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005451 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5452 lhsType.getUnqualifiedType(),
5453 AA_Assigning);
5454 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005455 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005456 Sema::AssignConvertType result = Compatible;
5457 if (getLangOptions().ObjCAutoRefCount &&
5458 !CheckObjCARCUnavailableWeakConversion(lhsType, rExpr.get()->getType()))
5459 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005460 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005461 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005462 }
5463
5464 // FIXME: Currently, we fall through and treat C++ classes like C
5465 // structures.
John McCall34376a62010-12-04 03:47:34 +00005466 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005467
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005468 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5469 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005470 if ((lhsType->isPointerType() ||
5471 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005472 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005473 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005474 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005475 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005476 return Compatible;
5477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478
Chris Lattnere6dcd502007-10-16 02:55:40 +00005479 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005480 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005481 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005482 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005483 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005484 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005485 if (!lhsType->isReferenceType()) {
5486 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5487 if (rExpr.isInvalid())
5488 return Incompatible;
5489 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005490
John McCall8cb679e2010-11-15 09:13:47 +00005491 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005492 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005493 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005494
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005495 // C99 6.5.16.1p2: The value of the right operand is converted to the
5496 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005497 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5498 // so that we can use references in built-in functions even in C.
5499 // The getNonReferenceType() call makes sure that the resulting expression
5500 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005501 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5502 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005503 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005504}
5505
John Wiegley01296292011-04-08 18:41:53 +00005506QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005507 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005508 << lex.get()->getType() << rex.get()->getType()
5509 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005510 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005511}
5512
Eli Friedman1408bc92011-06-23 18:10:35 +00005513QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5514 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005515 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005516 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005517 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005518 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005519 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005520 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005521
Nate Begeman191a6b12008-07-14 18:02:46 +00005522 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005523 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005524 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005525
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005526 // Handle the case of equivalent AltiVec and GCC vector types
5527 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5528 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005529 if (lhsType->isExtVectorType()) {
5530 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5531 return lhsType;
5532 }
5533
5534 if (!isCompAssign)
5535 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005536 return rhsType;
5537 }
5538
Eli Friedman1408bc92011-06-23 18:10:35 +00005539 if (getLangOptions().LaxVectorConversions &&
5540 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5541 // If we are allowing lax vector conversions, and LHS and RHS are both
5542 // vectors, the total size only needs to be the same. This is a
5543 // bitcast; no bits are changed but the result type is different.
5544 // FIXME: Should we really be allowing this?
5545 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5546 return lhsType;
5547 }
5548
Nate Begemanbd956c42009-06-28 02:36:38 +00005549 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5550 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5551 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005552 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005553 swapped = true;
5554 std::swap(rex, lex);
5555 std::swap(rhsType, lhsType);
5556 }
Mike Stump11289f42009-09-09 15:08:12 +00005557
Nate Begeman886448d2009-06-28 19:12:57 +00005558 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005559 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005560 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005561 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005562 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5563 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005564 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005565 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005566 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005567 if (swapped) std::swap(rex, lex);
5568 return lhsType;
5569 }
5570 }
5571 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5572 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005573 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5574 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005575 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005576 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005577 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005578 if (swapped) std::swap(rex, lex);
5579 return lhsType;
5580 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005581 }
5582 }
Mike Stump11289f42009-09-09 15:08:12 +00005583
Nate Begeman886448d2009-06-28 19:12:57 +00005584 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005585 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005586 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005587 << lex.get()->getType() << rex.get()->getType()
5588 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005589 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005590}
5591
Chris Lattnerfaa54172010-01-12 21:23:57 +00005592QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00005593 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5594 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005595 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005596
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005597 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005598 if (lex.isInvalid() || rex.isInvalid())
5599 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005600
John Wiegley01296292011-04-08 18:41:53 +00005601 if (!lex.get()->getType()->isArithmeticType() ||
5602 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005603 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005604
Chris Lattnerfaa54172010-01-12 21:23:57 +00005605 // Check for division by zero.
5606 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00005607 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5608 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5609 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005610
Chris Lattnerfaa54172010-01-12 21:23:57 +00005611 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005612}
5613
Chris Lattnerfaa54172010-01-12 21:23:57 +00005614QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005615 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5616 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5617 if (lex.get()->getType()->hasIntegerRepresentation() &&
5618 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005619 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005620 return InvalidOperands(Loc, lex, rex);
5621 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005622
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005623 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005624 if (lex.isInvalid() || rex.isInvalid())
5625 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005626
John Wiegley01296292011-04-08 18:41:53 +00005627 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005628 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005629
Chris Lattnerfaa54172010-01-12 21:23:57 +00005630 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00005631 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5632 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5633 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005634
Chris Lattnerfaa54172010-01-12 21:23:57 +00005635 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005636}
5637
Chandler Carruthc9332212011-06-27 08:02:19 +00005638/// \brief Diagnose invalid arithmetic on two void pointers.
5639static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5640 Expr *LHS, Expr *RHS) {
5641 S.Diag(Loc, S.getLangOptions().CPlusPlus
5642 ? diag::err_typecheck_pointer_arith_void_type
5643 : diag::ext_gnu_void_ptr)
5644 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5645}
5646
5647/// \brief Diagnose invalid arithmetic on a void pointer.
5648static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5649 Expr *Pointer) {
5650 S.Diag(Loc, S.getLangOptions().CPlusPlus
5651 ? diag::err_typecheck_pointer_arith_void_type
5652 : diag::ext_gnu_void_ptr)
5653 << 0 /* one pointer */ << Pointer->getSourceRange();
5654}
5655
5656/// \brief Diagnose invalid arithmetic on two function pointers.
5657static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5658 Expr *LHS, Expr *RHS) {
5659 assert(LHS->getType()->isAnyPointerType());
5660 assert(RHS->getType()->isAnyPointerType());
5661 S.Diag(Loc, S.getLangOptions().CPlusPlus
5662 ? diag::err_typecheck_pointer_arith_function_type
5663 : diag::ext_gnu_ptr_func_arith)
5664 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5665 // We only show the second type if it differs from the first.
5666 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5667 RHS->getType())
5668 << RHS->getType()->getPointeeType()
5669 << LHS->getSourceRange() << RHS->getSourceRange();
5670}
5671
5672/// \brief Diagnose invalid arithmetic on a function pointer.
5673static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5674 Expr *Pointer) {
5675 assert(Pointer->getType()->isAnyPointerType());
5676 S.Diag(Loc, S.getLangOptions().CPlusPlus
5677 ? diag::err_typecheck_pointer_arith_function_type
5678 : diag::ext_gnu_ptr_func_arith)
5679 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5680 << 0 /* one pointer, so only one type */
5681 << Pointer->getSourceRange();
5682}
5683
5684/// \brief Check the validity of an arithmetic pointer operand.
5685///
5686/// If the operand has pointer type, this code will check for pointer types
5687/// which are invalid in arithmetic operations. These will be diagnosed
5688/// appropriately, including whether or not the use is supported as an
5689/// extension.
5690///
5691/// \returns True when the operand is valid to use (even if as an extension).
5692static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5693 Expr *Operand) {
5694 if (!Operand->getType()->isAnyPointerType()) return true;
5695
5696 QualType PointeeTy = Operand->getType()->getPointeeType();
5697 if (PointeeTy->isVoidType()) {
5698 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5699 return !S.getLangOptions().CPlusPlus;
5700 }
5701 if (PointeeTy->isFunctionType()) {
5702 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5703 return !S.getLangOptions().CPlusPlus;
5704 }
5705
5706 if ((Operand->getType()->isPointerType() &&
5707 !Operand->getType()->isDependentType()) ||
5708 Operand->getType()->isObjCObjectPointerType()) {
5709 QualType PointeeTy = Operand->getType()->getPointeeType();
5710 if (S.RequireCompleteType(
5711 Loc, PointeeTy,
5712 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5713 << PointeeTy << Operand->getSourceRange()))
5714 return false;
5715 }
5716
5717 return true;
5718}
5719
5720/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5721/// operands.
5722///
5723/// This routine will diagnose any invalid arithmetic on pointer operands much
5724/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5725/// for emitting a single diagnostic even for operations where both LHS and RHS
5726/// are (potentially problematic) pointers.
5727///
5728/// \returns True when the operand is valid to use (even if as an extension).
5729static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5730 Expr *LHS, Expr *RHS) {
5731 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5732 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5733 if (!isLHSPointer && !isRHSPointer) return true;
5734
5735 QualType LHSPointeeTy, RHSPointeeTy;
5736 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5737 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5738
5739 // Check for arithmetic on pointers to incomplete types.
5740 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5741 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5742 if (isLHSVoidPtr || isRHSVoidPtr) {
5743 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5744 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5745 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5746
5747 return !S.getLangOptions().CPlusPlus;
5748 }
5749
5750 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5751 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5752 if (isLHSFuncPtr || isRHSFuncPtr) {
5753 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5754 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5755 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5756
5757 return !S.getLangOptions().CPlusPlus;
5758 }
5759
5760 Expr *Operands[] = { LHS, RHS };
5761 for (unsigned i = 0; i < 2; ++i) {
5762 Expr *Operand = Operands[i];
5763 if ((Operand->getType()->isPointerType() &&
5764 !Operand->getType()->isDependentType()) ||
5765 Operand->getType()->isObjCObjectPointerType()) {
5766 QualType PointeeTy = Operand->getType()->getPointeeType();
5767 if (S.RequireCompleteType(
5768 Loc, PointeeTy,
5769 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5770 << PointeeTy << Operand->getSourceRange()))
5771 return false;
5772 }
5773 }
5774 return true;
5775}
5776
Chris Lattnerfaa54172010-01-12 21:23:57 +00005777QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005778 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5779 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005780 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005781 if (CompLHSTy) *CompLHSTy = compType;
5782 return compType;
5783 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005784
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005785 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005786 if (lex.isInvalid() || rex.isInvalid())
5787 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005788
Steve Naroffe4718892007-04-27 18:30:00 +00005789 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005790 if (lex.get()->getType()->isArithmeticType() &&
5791 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005792 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005793 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005794 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005795
Eli Friedman8e122982008-05-18 18:08:51 +00005796 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005797 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005798 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005799 std::swap(PExp, IExp);
5800
Steve Naroff6b712a72009-07-14 18:25:06 +00005801 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005802 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005803 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5804 return QualType();
5805
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005806 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005807
Chris Lattner12bdebb2009-04-24 23:50:08 +00005808 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005809 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005810 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5811 << PointeeTy << PExp->getSourceRange();
5812 return QualType();
5813 }
Mike Stump11289f42009-09-09 15:08:12 +00005814
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005815 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005816 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005817 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005818 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005819 if (LHSTy->isPromotableIntegerType())
5820 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005821 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005822 *CompLHSTy = LHSTy;
5823 }
Eli Friedman8e122982008-05-18 18:08:51 +00005824 return PExp->getType();
5825 }
5826 }
5827
Chris Lattner326f7572008-11-18 01:30:42 +00005828 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005829}
5830
Chris Lattner2a3569b2008-04-07 05:30:13 +00005831// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005832QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005833 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005834 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005835 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005836 if (CompLHSTy) *CompLHSTy = compType;
5837 return compType;
5838 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005839
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005840 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005841 if (lex.isInvalid() || rex.isInvalid())
5842 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005843
Chris Lattner4d62f422007-12-09 21:53:25 +00005844 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005845
Chris Lattner4d62f422007-12-09 21:53:25 +00005846 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005847 if (lex.get()->getType()->isArithmeticType() &&
5848 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005849 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005850 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005851 }
Mike Stump11289f42009-09-09 15:08:12 +00005852
Chris Lattner4d62f422007-12-09 21:53:25 +00005853 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005854 if (lex.get()->getType()->isAnyPointerType()) {
5855 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005856
Chris Lattner12bdebb2009-04-24 23:50:08 +00005857 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005858 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005859 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005860 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005861 return QualType();
5862 }
Mike Stump11289f42009-09-09 15:08:12 +00005863
Chris Lattner4d62f422007-12-09 21:53:25 +00005864 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005865 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005866 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5867 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005868
John Wiegley01296292011-04-08 18:41:53 +00005869 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5870 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005871 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005872
Chris Lattner4d62f422007-12-09 21:53:25 +00005873 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00005874 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005875 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005876
Eli Friedman168fe152009-05-16 13:54:38 +00005877 if (getLangOptions().CPlusPlus) {
5878 // Pointee types must be the same: C++ [expr.add]
5879 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5880 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005881 << lex.get()->getType() << rex.get()->getType()
5882 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005883 return QualType();
5884 }
5885 } else {
5886 // Pointee types must be compatible C99 6.5.6p3
5887 if (!Context.typesAreCompatible(
5888 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5889 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5890 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00005891 << lex.get()->getType() << rex.get()->getType()
5892 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00005893 return QualType();
5894 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005895 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005896
Chandler Carruthc9332212011-06-27 08:02:19 +00005897 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
5898 lex.get(), rex.get()))
5899 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005900
John Wiegley01296292011-04-08 18:41:53 +00005901 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005902 return Context.getPointerDiffType();
5903 }
5904 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005905
Chris Lattner326f7572008-11-18 01:30:42 +00005906 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005907}
5908
Douglas Gregor0bf31402010-10-08 23:50:27 +00005909static bool isScopedEnumerationType(QualType T) {
5910 if (const EnumType *ET = dyn_cast<EnumType>(T))
5911 return ET->getDecl()->isScoped();
5912 return false;
5913}
5914
John Wiegley01296292011-04-08 18:41:53 +00005915static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005916 SourceLocation Loc, unsigned Opc,
5917 QualType LHSTy) {
5918 llvm::APSInt Right;
5919 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00005920 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005921 return;
5922
5923 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00005924 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00005925 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00005926 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005927 return;
5928 }
5929 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00005930 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005931 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00005932 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00005933 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00005934 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005935 return;
5936 }
5937 if (Opc != BO_Shl)
5938 return;
5939
5940 // When left shifting an ICE which is signed, we can check for overflow which
5941 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5942 // integers have defined behavior modulo one more than the maximum value
5943 // representable in the result type, so never warn for those.
5944 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00005945 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005946 LHSTy->hasUnsignedIntegerRepresentation())
5947 return;
5948 llvm::APInt ResultBits =
5949 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5950 if (LeftBits.uge(ResultBits))
5951 return;
5952 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5953 Result = Result.shl(Right);
5954
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005955 // Print the bit representation of the signed integer as an unsigned
5956 // hexadecimal number.
5957 llvm::SmallString<40> HexResult;
5958 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5959
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005960 // If we are only missing a sign bit, this is less likely to result in actual
5961 // bugs -- if the result is cast back to an unsigned type, it will have the
5962 // expected value. Thus we place this behind a different warning that can be
5963 // turned off separately if needed.
5964 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005965 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5966 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005967 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005968 return;
5969 }
5970
5971 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00005972 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00005973 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005974}
5975
Chris Lattner2a3569b2008-04-07 05:30:13 +00005976// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00005977QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00005978 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005979 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00005980 if (!lex.get()->getType()->hasIntegerRepresentation() ||
5981 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005982 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005983
Douglas Gregor0bf31402010-10-08 23:50:27 +00005984 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5985 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00005986 if (isScopedEnumerationType(lex.get()->getType()) ||
5987 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00005988 return InvalidOperands(Loc, lex, rex);
5989 }
5990
Nate Begemane46ee9a2009-10-25 02:26:48 +00005991 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00005992 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005993 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00005994
Chris Lattner5c11c412007-12-12 05:47:28 +00005995 // Shifts don't perform usual arithmetic conversions, they just do integer
5996 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005997
John McCall57cdd882010-12-16 19:28:59 +00005998 // For the LHS, do usual unary conversions, but then reset them away
5999 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006000 ExprResult old_lex = lex;
6001 lex = UsualUnaryConversions(lex.take());
6002 if (lex.isInvalid())
6003 return QualType();
6004 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006005 if (isCompAssign) lex = old_lex;
6006
6007 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006008 rex = UsualUnaryConversions(rex.take());
6009 if (rex.isInvalid())
6010 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006011
Ryan Flynnf53fab82009-08-07 16:20:20 +00006012 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006013 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006014
Chris Lattner5c11c412007-12-12 05:47:28 +00006015 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006016 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006017}
6018
Chandler Carruth17773fc2010-07-10 12:30:03 +00006019static bool IsWithinTemplateSpecialization(Decl *D) {
6020 if (DeclContext *DC = D->getDeclContext()) {
6021 if (isa<ClassTemplateSpecializationDecl>(DC))
6022 return true;
6023 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6024 return FD->isFunctionTemplateSpecialization();
6025 }
6026 return false;
6027}
6028
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006029// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00006030QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006031 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006032 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006033
Chris Lattner9a152e22009-12-05 05:40:13 +00006034 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00006035 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006036 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006037
John Wiegley01296292011-04-08 18:41:53 +00006038 QualType lType = lex.get()->getType();
6039 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006040
John Wiegley01296292011-04-08 18:41:53 +00006041 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6042 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006043 QualType LHSStrippedType = LHSStripped->getType();
6044 QualType RHSStrippedType = RHSStripped->getType();
6045
Douglas Gregor1beec452011-03-12 01:48:56 +00006046
6047
Chandler Carruth712563b2011-02-17 08:37:06 +00006048 // Two different enums will raise a warning when compared.
6049 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6050 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6051 if (LHSEnumType->getDecl()->getIdentifier() &&
6052 RHSEnumType->getDecl()->getIdentifier() &&
6053 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6054 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6055 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006056 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006057 }
6058 }
6059 }
6060
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006061 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006062 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006063 !lex.get()->getLocStart().isMacroID() &&
6064 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006065 // For non-floating point types, check for self-comparisons of the form
6066 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6067 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006068 //
6069 // NOTE: Don't warn about comparison expressions resulting from macro
6070 // expansion. Also don't warn about comparisons which are only self
6071 // comparisons within a template specialization. The warnings should catch
6072 // obvious cases in the definition of the template anyways. The idea is to
6073 // warn when the typed comparison operator will always evaluate to the same
6074 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006075 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006076 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006077 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006078 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006079 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006080 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006081 << (Opc == BO_EQ
6082 || Opc == BO_LE
6083 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006084 } else if (lType->isArrayType() && rType->isArrayType() &&
6085 !DRL->getDecl()->getType()->isReferenceType() &&
6086 !DRR->getDecl()->getType()->isReferenceType()) {
6087 // what is it always going to eval to?
6088 char always_evals_to;
6089 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006090 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006091 always_evals_to = 0; // false
6092 break;
John McCalle3027922010-08-25 11:45:40 +00006093 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006094 always_evals_to = 1; // true
6095 break;
6096 default:
6097 // best we can say is 'a constant'
6098 always_evals_to = 2; // e.g. array1 <= array2
6099 break;
6100 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006101 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006102 << 1 // array
6103 << always_evals_to);
6104 }
6105 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006106 }
Mike Stump11289f42009-09-09 15:08:12 +00006107
Chris Lattner222b8bd2009-03-08 19:39:53 +00006108 if (isa<CastExpr>(LHSStripped))
6109 LHSStripped = LHSStripped->IgnoreParenCasts();
6110 if (isa<CastExpr>(RHSStripped))
6111 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006112
Chris Lattner222b8bd2009-03-08 19:39:53 +00006113 // Warn about comparisons against a string constant (unless the other
6114 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006115 Expr *literalString = 0;
6116 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006117 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006118 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006119 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006120 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006121 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006122 } else if ((isa<StringLiteral>(RHSStripped) ||
6123 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006124 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006125 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006126 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006127 literalStringStripped = RHSStripped;
6128 }
6129
6130 if (literalString) {
6131 std::string resultComparison;
6132 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006133 case BO_LT: resultComparison = ") < 0"; break;
6134 case BO_GT: resultComparison = ") > 0"; break;
6135 case BO_LE: resultComparison = ") <= 0"; break;
6136 case BO_GE: resultComparison = ") >= 0"; break;
6137 case BO_EQ: resultComparison = ") == 0"; break;
6138 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006139 default: assert(false && "Invalid comparison operator");
6140 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006141
Ted Kremenek3427fac2011-02-23 01:52:04 +00006142 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006143 PDiag(diag::warn_stringcompare)
6144 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006145 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006146 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006147 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006148
Douglas Gregorec170db2010-06-08 19:50:34 +00006149 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00006150 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006151 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006152 if (lex.isInvalid() || rex.isInvalid())
6153 return QualType();
6154 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006155 else {
John Wiegley01296292011-04-08 18:41:53 +00006156 lex = UsualUnaryConversions(lex.take());
6157 if (lex.isInvalid())
6158 return QualType();
6159
6160 rex = UsualUnaryConversions(rex.take());
6161 if (rex.isInvalid())
6162 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006163 }
6164
John Wiegley01296292011-04-08 18:41:53 +00006165 lType = lex.get()->getType();
6166 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006167
Douglas Gregorca63811b2008-11-19 03:25:36 +00006168 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006169 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006170
Chris Lattnerb620c342007-08-26 01:18:55 +00006171 if (isRelational) {
6172 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006173 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006174 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006175 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006176 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006177 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006178
Chris Lattnerb620c342007-08-26 01:18:55 +00006179 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006180 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006181 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006182
John Wiegley01296292011-04-08 18:41:53 +00006183 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006184 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006185 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006186 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006187
Douglas Gregorf267edd2010-06-15 21:38:40 +00006188 // All of the following pointer-related warnings are GCC extensions, except
6189 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006190 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006191 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006192 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006193 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006194 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006195
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006196 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006197 if (LCanPointeeTy == RCanPointeeTy)
6198 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006199 if (!isRelational &&
6200 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6201 // Valid unless comparison between non-null pointer and function pointer
6202 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006203 // In a SFINAE context, we treat this as a hard error to maintain
6204 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006205 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6206 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006207 Diag(Loc,
6208 isSFINAEContext()?
6209 diag::err_typecheck_comparison_of_fptr_to_void
6210 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006211 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006212
6213 if (isSFINAEContext())
6214 return QualType();
6215
John Wiegley01296292011-04-08 18:41:53 +00006216 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006217 return ResultTy;
6218 }
6219 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006220
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006221 // C++ [expr.rel]p2:
6222 // [...] Pointer conversions (4.10) and qualification
6223 // conversions (4.4) are performed on pointer operands (or on
6224 // a pointer operand and a null pointer constant) to bring
6225 // them to their composite pointer type. [...]
6226 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006227 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006228 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006229 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006230 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006231 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006232 if (T.isNull()) {
6233 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006234 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006235 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006236 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006237 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006238 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006239 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006240 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006241 }
6242
John Wiegley01296292011-04-08 18:41:53 +00006243 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6244 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006245 return ResultTy;
6246 }
Eli Friedman16c209612009-08-23 00:27:47 +00006247 // C99 6.5.9p2 and C99 6.5.8p2
6248 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6249 RCanPointeeTy.getUnqualifiedType())) {
6250 // Valid unless a relational comparison of function pointers
6251 if (isRelational && LCanPointeeTy->isFunctionType()) {
6252 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006253 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006254 }
6255 } else if (!isRelational &&
6256 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6257 // Valid unless comparison between non-null pointer and function pointer
6258 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6259 && !LHSIsNull && !RHSIsNull) {
6260 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00006261 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006262 }
6263 } else {
6264 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006265 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006266 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006267 }
John McCall7684dde2011-03-11 04:25:25 +00006268 if (LCanPointeeTy != RCanPointeeTy) {
6269 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006270 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006271 else
John Wiegley01296292011-04-08 18:41:53 +00006272 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006273 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006274 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006275 }
Mike Stump11289f42009-09-09 15:08:12 +00006276
Sebastian Redl576fd422009-05-10 18:38:11 +00006277 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006278 // Comparison of nullptr_t with itself.
6279 if (lType->isNullPtrType() && rType->isNullPtrType())
6280 return ResultTy;
6281
Mike Stump11289f42009-09-09 15:08:12 +00006282 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006283 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006284 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006285 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006286 (!isRelational &&
6287 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006288 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006289 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006290 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006291 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006292 return ResultTy;
6293 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006294 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006295 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006296 (!isRelational &&
6297 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006298 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006299 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006300 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006301 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006302 return ResultTy;
6303 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006304
6305 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006306 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006307 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6308 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006309 // In addition, pointers to members can be compared, or a pointer to
6310 // member and a null pointer constant. Pointer to member conversions
6311 // (4.11) and qualification conversions (4.4) are performed to bring
6312 // them to a common type. If one operand is a null pointer constant,
6313 // the common type is the type of the other operand. Otherwise, the
6314 // common type is a pointer to member type similar (4.4) to the type
6315 // of one of the operands, with a cv-qualification signature (4.4)
6316 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006317 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006318 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006319 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006320 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006321 if (T.isNull()) {
6322 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006323 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006324 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006325 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006326 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006327 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006328 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006329 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006330 }
Mike Stump11289f42009-09-09 15:08:12 +00006331
John Wiegley01296292011-04-08 18:41:53 +00006332 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6333 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006334 return ResultTy;
6335 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006336
6337 // Handle scoped enumeration types specifically, since they don't promote
6338 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006339 if (lex.get()->getType()->isEnumeralType() &&
6340 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006341 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006342 }
Mike Stump11289f42009-09-09 15:08:12 +00006343
Steve Naroff081c7422008-09-04 15:10:53 +00006344 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006345 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006346 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6347 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Steve Naroff081c7422008-09-04 15:10:53 +00006349 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006350 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006351 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006352 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006353 }
John Wiegley01296292011-04-08 18:41:53 +00006354 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006355 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006356 }
John Wiegley01296292011-04-08 18:41:53 +00006357
Steve Naroffe18f94c2008-09-28 01:11:11 +00006358 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006359 if (!isRelational
6360 && ((lType->isBlockPointerType() && rType->isPointerType())
6361 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006362 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006363 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006364 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006365 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006366 ->getPointeeType()->isVoidType())))
6367 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00006368 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006369 }
John McCall7684dde2011-03-11 04:25:25 +00006370 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006371 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006372 else
John Wiegley01296292011-04-08 18:41:53 +00006373 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006374 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006375 }
Steve Naroff081c7422008-09-04 15:10:53 +00006376
John McCall7684dde2011-03-11 04:25:25 +00006377 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6378 const PointerType *LPT = lType->getAs<PointerType>();
6379 const PointerType *RPT = rType->getAs<PointerType>();
6380 if (LPT || RPT) {
6381 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6382 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006383
Steve Naroff753567f2008-11-17 19:49:16 +00006384 if (!LPtrToVoid && !RPtrToVoid &&
6385 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006386 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006387 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006388 }
John McCall7684dde2011-03-11 04:25:25 +00006389 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006390 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006391 else
John Wiegley01296292011-04-08 18:41:53 +00006392 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006393 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006394 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006395 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006396 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006397 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006398 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006399 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006400 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006401 else
John Wiegley01296292011-04-08 18:41:53 +00006402 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006403 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006404 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006405 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006406 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6407 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006408 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006409 bool isError = false;
6410 if ((LHSIsNull && lType->isIntegerType()) ||
6411 (RHSIsNull && rType->isIntegerType())) {
6412 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006413 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006414 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006415 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006416 else if (getLangOptions().CPlusPlus) {
6417 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6418 isError = true;
6419 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006420 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006421
Chris Lattnerd99bd522009-08-23 00:03:44 +00006422 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006423 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00006424 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006425 if (isError)
6426 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006427 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006428
6429 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006430 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006431 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006432 else
John Wiegley01296292011-04-08 18:41:53 +00006433 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006434 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006435 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006436 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006437
Steve Naroff4b191572008-09-04 16:56:14 +00006438 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006439 if (!isRelational && RHSIsNull
6440 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006441 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006442 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006443 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006444 if (!isRelational && LHSIsNull
6445 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006446 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006447 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006448 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006449
Chris Lattner326f7572008-11-18 01:30:42 +00006450 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006451}
6452
Nate Begeman191a6b12008-07-14 18:02:46 +00006453/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006454/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006455/// like a scalar comparison, a vector comparison produces a vector of integer
6456/// types.
John Wiegley01296292011-04-08 18:41:53 +00006457QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006458 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006459 bool isRelational) {
6460 // Check to make sure we're operating on vectors of the same type and width,
6461 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006462 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006463 if (vType.isNull())
6464 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
John Wiegley01296292011-04-08 18:41:53 +00006466 QualType lType = lex.get()->getType();
6467 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006468
Anton Yartsev530deb92011-03-27 15:36:07 +00006469 // If AltiVec, the comparison results in a numeric type, i.e.
6470 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006471 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006472 return Context.getLogicalOperationType();
6473
Nate Begeman191a6b12008-07-14 18:02:46 +00006474 // For non-floating point types, check for self-comparisons of the form
6475 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6476 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006477 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006478 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6479 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006480 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006481 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006482 PDiag(diag::warn_comparison_always)
6483 << 0 // self-
6484 << 2 // "a constant"
6485 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006486 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006487
Nate Begeman191a6b12008-07-14 18:02:46 +00006488 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006489 if (!isRelational && lType->hasFloatingRepresentation()) {
6490 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006491 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006492 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
Nate Begeman191a6b12008-07-14 18:02:46 +00006494 // Return the type for the comparison, which is the same as vector type for
6495 // integer vectors, or an integer type of identical size and number of
6496 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006497 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006498 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006499
John McCall9dd450b2009-09-21 23:43:11 +00006500 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006501 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006502 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006503 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006504 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006505 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6506
Mike Stump4e1f26a2009-02-19 03:04:26 +00006507 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006508 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006509 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6510}
6511
Steve Naroff218bc2b2007-05-04 21:54:46 +00006512inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006513 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6514 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6515 if (lex.get()->getType()->hasIntegerRepresentation() &&
6516 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006517 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006518
6519 return InvalidOperands(Loc, lex, rex);
6520 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006521
John Wiegley01296292011-04-08 18:41:53 +00006522 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6523 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6524 if (lexResult.isInvalid() || rexResult.isInvalid())
6525 return QualType();
6526 lex = lexResult.take();
6527 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006528
John Wiegley01296292011-04-08 18:41:53 +00006529 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6530 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006531 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006532 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006533}
6534
Steve Naroff218bc2b2007-05-04 21:54:46 +00006535inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006536 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006537
6538 // Diagnose cases where the user write a logical and/or but probably meant a
6539 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6540 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00006541 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6542 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006543 // Don't warn in macros or template instantiations.
6544 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006545 // If the RHS can be constant folded, and if it constant folds to something
6546 // that isn't 0 or 1 (which indicate a potential logical operation that
6547 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006548 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006549 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006550 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6551 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6552 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6553 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6554 << rex.get()->getSourceRange()
6555 << (Opc == BO_LAnd ? "&&" : "||")
6556 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006557 }
6558 }
Chris Lattner8406c512010-07-13 19:41:32 +00006559
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006560 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006561 lex = UsualUnaryConversions(lex.take());
6562 if (lex.isInvalid())
6563 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006564
John Wiegley01296292011-04-08 18:41:53 +00006565 rex = UsualUnaryConversions(rex.take());
6566 if (rex.isInvalid())
6567 return QualType();
6568
6569 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006570 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006571
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006572 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006573 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006574
John McCall4a2429a2010-06-04 00:29:51 +00006575 // The following is safe because we only use this method for
6576 // non-overloadable operands.
6577
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006578 // C++ [expr.log.and]p1
6579 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006580 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006581 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6582 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006583 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006584 lex = move(lexRes);
6585
6586 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6587 if (rexRes.isInvalid())
6588 return InvalidOperands(Loc, lex, rex);
6589 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006590
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006591 // C++ [expr.log.and]p2
6592 // C++ [expr.log.or]p2
6593 // The result is a bool.
6594 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006595}
6596
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006597/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6598/// is a read-only property; return true if so. A readonly property expression
6599/// depends on various declarations and thus must be treated specially.
6600///
Mike Stump11289f42009-09-09 15:08:12 +00006601static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006602 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6603 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006604 if (PropExpr->isImplicitProperty()) return false;
6605
6606 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6607 QualType BaseType = PropExpr->isSuperReceiver() ?
6608 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006609 PropExpr->getBase()->getType();
6610
John McCallb7bd14f2010-12-02 01:19:52 +00006611 if (const ObjCObjectPointerType *OPT =
6612 BaseType->getAsObjCInterfacePointerType())
6613 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6614 if (S.isPropertyReadonly(PDecl, IFace))
6615 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006616 }
6617 return false;
6618}
6619
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006620static bool IsConstProperty(Expr *E, Sema &S) {
6621 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6622 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6623 if (PropExpr->isImplicitProperty()) return false;
6624
6625 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6626 QualType T = PDecl->getType();
6627 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006628 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006629 CanQualType CT = S.Context.getCanonicalType(T);
6630 return CT.isConstQualified();
6631 }
6632 return false;
6633}
6634
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006635static bool IsReadonlyMessage(Expr *E, Sema &S) {
6636 if (E->getStmtClass() != Expr::MemberExprClass)
6637 return false;
6638 const MemberExpr *ME = cast<MemberExpr>(E);
6639 NamedDecl *Member = ME->getMemberDecl();
6640 if (isa<FieldDecl>(Member)) {
6641 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6642 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6643 return false;
6644 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6645 }
6646 return false;
6647}
6648
Chris Lattner30bd3272008-11-18 01:22:49 +00006649/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6650/// emit an error and return true. If so, return false.
6651static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006652 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006653 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006654 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006655 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6656 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006657 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6658 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006659 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6660 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006661 if (IsLV == Expr::MLV_Valid)
6662 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006663
Chris Lattner30bd3272008-11-18 01:22:49 +00006664 unsigned Diag = 0;
6665 bool NeedType = false;
6666 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006667 case Expr::MLV_ConstQualified:
6668 Diag = diag::err_typecheck_assign_const;
6669
John McCalld4631322011-06-17 06:42:21 +00006670 // In ARC, use some specialized diagnostics for occasions where we
6671 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006672 if (S.getLangOptions().ObjCAutoRefCount) {
6673 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6674 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6675 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6676
John McCalld4631322011-06-17 06:42:21 +00006677 // Use the normal diagnostic if it's pseudo-__strong but the
6678 // user actually wrote 'const'.
6679 if (var->isARCPseudoStrong() &&
6680 (!var->getTypeSourceInfo() ||
6681 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6682 // There are two pseudo-strong cases:
6683 // - self
John McCall31168b02011-06-15 23:02:42 +00006684 ObjCMethodDecl *method = S.getCurMethodDecl();
6685 if (method && var == method->getSelfDecl())
6686 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006687
6688 // - fast enumeration variables
6689 else
John McCall31168b02011-06-15 23:02:42 +00006690 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006691
John McCall31168b02011-06-15 23:02:42 +00006692 SourceRange Assign;
6693 if (Loc != OrigLoc)
6694 Assign = SourceRange(OrigLoc, OrigLoc);
6695 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6696 // We need to preserve the AST regardless, so migration tool
6697 // can do its job.
6698 return false;
6699 }
6700 }
6701 }
6702
6703 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006704 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006705 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6706 NeedType = true;
6707 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006708 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006709 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6710 NeedType = true;
6711 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006712 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006713 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6714 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006715 case Expr::MLV_Valid:
6716 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006717 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006718 case Expr::MLV_MemberFunction:
6719 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006720 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6721 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006722 case Expr::MLV_IncompleteType:
6723 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006724 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006725 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006726 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006727 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006728 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6729 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006730 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006731 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6732 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006733 case Expr::MLV_ReadonlyProperty:
6734 Diag = diag::error_readonly_property_assignment;
6735 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006736 case Expr::MLV_NoSetterProperty:
6737 Diag = diag::error_nosetter_property_assignment;
6738 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006739 case Expr::MLV_InvalidMessageExpression:
6740 Diag = diag::error_readonly_message_assignment;
6741 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006742 case Expr::MLV_SubObjCPropertySetting:
6743 Diag = diag::error_no_subobject_property_setting;
6744 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006745 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006746
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006747 SourceRange Assign;
6748 if (Loc != OrigLoc)
6749 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006750 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006751 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006752 else
Mike Stump11289f42009-09-09 15:08:12 +00006753 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006754 return true;
6755}
6756
6757
6758
6759// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006760QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006761 SourceLocation Loc,
6762 QualType CompoundType) {
6763 // Verify that LHS is a modifiable lvalue, and emit error if not.
6764 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006765 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006766
6767 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00006768 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006769 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006770 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006771 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006772 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006773 if (LHS->getObjectKind() == OK_ObjCProperty) {
6774 ExprResult LHSResult = Owned(LHS);
6775 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6776 if (LHSResult.isInvalid())
6777 return QualType();
6778 LHS = LHSResult.take();
6779 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006780 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006781 if (RHS.isInvalid())
6782 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006783 // Special case of NSObject attributes on c-style pointer types.
6784 if (ConvTy == IncompatiblePointer &&
6785 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006786 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006787 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006788 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006789 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006790
John McCall7decc9e2010-11-18 06:31:45 +00006791 if (ConvTy == Compatible &&
6792 getLangOptions().ObjCNonFragileABI &&
6793 LHSType->isObjCObjectType())
6794 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6795 << LHSType;
6796
Chris Lattnerea714382008-08-21 18:04:13 +00006797 // If the RHS is a unary plus or minus, check to see if they = and + are
6798 // right next to each other. If so, the user may have typo'd "x =+ 4"
6799 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006800 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006801 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6802 RHSCheck = ICE->getSubExpr();
6803 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006804 if ((UO->getOpcode() == UO_Plus ||
6805 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006806 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006807 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006808 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6809 // And there is a space or other character before the subexpr of the
6810 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006811 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6812 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006813 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006814 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006815 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006816 }
Chris Lattnerea714382008-08-21 18:04:13 +00006817 }
John McCall31168b02011-06-15 23:02:42 +00006818
6819 if (ConvTy == Compatible) {
6820 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6821 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006822 else if (getLangOptions().ObjCAutoRefCount)
6823 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006824 }
Chris Lattnerea714382008-08-21 18:04:13 +00006825 } else {
6826 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006827 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006828 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006829
Chris Lattner326f7572008-11-18 01:30:42 +00006830 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006831 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006832 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006833
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006834 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006835 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006836 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006837
Steve Naroff98cf3e92007-06-06 18:38:38 +00006838 // C99 6.5.16p3: The type of an assignment expression is the type of the
6839 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006840 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006841 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6842 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006843 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006844 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006845 return (getLangOptions().CPlusPlus
6846 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006847}
6848
Chris Lattner326f7572008-11-18 01:30:42 +00006849// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00006850static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006851 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00006852 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006853
John McCall3aef3d82011-04-10 19:13:55 +00006854 LHS = S.CheckPlaceholderExpr(LHS.take());
6855 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00006856 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006857 return QualType();
6858
John McCall73d36182010-10-12 07:14:40 +00006859 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6860 // operands, but not unary promotions.
6861 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00006862
John McCall34376a62010-12-04 03:47:34 +00006863 // So we treat the LHS as a ignored value, and in C++ we allow the
6864 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00006865 LHS = S.IgnoredValueConversions(LHS.take());
6866 if (LHS.isInvalid())
6867 return QualType();
John McCall34376a62010-12-04 03:47:34 +00006868
6869 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006870 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6871 if (RHS.isInvalid())
6872 return QualType();
6873 if (!RHS.get()->getType()->isVoidType())
6874 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00006875 }
Eli Friedmanba961a92009-03-23 00:24:07 +00006876
John Wiegley01296292011-04-08 18:41:53 +00006877 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006878}
6879
Steve Naroff7a5af782007-07-13 16:58:59 +00006880/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6881/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00006882static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6883 ExprValueKind &VK,
6884 SourceLocation OpLoc,
6885 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006886 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00006887 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006888
Chris Lattner6b0cf142008-11-21 07:05:48 +00006889 QualType ResType = Op->getType();
6890 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006891
John McCall4bc41ae2010-11-18 19:01:18 +00006892 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00006893 // Decrement of bool is not allowed.
6894 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00006895 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006896 return QualType();
6897 }
6898 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00006899 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00006900 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006901 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006902 } else if (ResType->isAnyPointerType()) {
6903 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006904
Chris Lattner6b0cf142008-11-21 07:05:48 +00006905 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00006906 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00006907 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006908
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006909 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00006910 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6911 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006912 << PointeeTy << Op->getSourceRange();
6913 return QualType();
6914 }
Eli Friedman090addd2010-01-03 00:20:48 +00006915 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006916 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00006917 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006918 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00006919 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00006920 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00006921 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00006922 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6923 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00006924 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6925 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00006926 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00006927 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006928 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006929 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006930 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006931 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006932 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00006933 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00006934 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006935 // In C++, a prefix increment is the same type as the operand. Otherwise
6936 // (in C or with postfix), the increment is the unqualified type of the
6937 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00006938 if (isPrefix && S.getLangOptions().CPlusPlus) {
6939 VK = VK_LValue;
6940 return ResType;
6941 } else {
6942 VK = VK_RValue;
6943 return ResType.getUnqualifiedType();
6944 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00006945}
6946
John Wiegley01296292011-04-08 18:41:53 +00006947ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00006948 assert(E->getValueKind() == VK_LValue &&
6949 E->getObjectKind() == OK_ObjCProperty);
6950 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6951
Douglas Gregor33823722011-06-11 01:09:30 +00006952 QualType T = E->getType();
6953 QualType ReceiverType;
6954 if (PRE->isObjectReceiver())
6955 ReceiverType = PRE->getBase()->getType();
6956 else if (PRE->isSuperReceiver())
6957 ReceiverType = PRE->getSuperReceiverType();
6958 else
6959 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6960
John McCall34376a62010-12-04 03:47:34 +00006961 ExprValueKind VK = VK_RValue;
6962 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006963 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006964 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00006965 T = getMessageSendResultType(ReceiverType, GetterMethod,
6966 PRE->isClassReceiver(),
6967 PRE->isSuperReceiver());
6968 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00006969 }
6970 else {
6971 Diag(PRE->getLocation(), diag::err_getter_not_found)
6972 << PRE->getBase()->getType();
6973 }
John McCall34376a62010-12-04 03:47:34 +00006974 }
Douglas Gregor33823722011-06-11 01:09:30 +00006975
6976 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00006977 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00006978
6979 ExprResult Result = MaybeBindToTemporary(E);
6980 if (!Result.isInvalid())
6981 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00006982
6983 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00006984}
6985
John Wiegley01296292011-04-08 18:41:53 +00006986void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
6987 assert(LHS.get()->getValueKind() == VK_LValue &&
6988 LHS.get()->getObjectKind() == OK_ObjCProperty);
6989 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00006990
John McCall31168b02011-06-15 23:02:42 +00006991 bool Consumed = false;
6992
John Wiegley01296292011-04-08 18:41:53 +00006993 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00006994 // If using property-dot syntax notation for assignment, and there is a
6995 // setter, RHS expression is being passed to the setter argument. So,
6996 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00006997 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00006998 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6999 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007000 Consumed = (getLangOptions().ObjCAutoRefCount &&
7001 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007002
7003 // Otherwise, if the getter returns an l-value, just call that.
7004 } else {
John Wiegley01296292011-04-08 18:41:53 +00007005 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007006 ExprValueKind VK = Expr::getValueKindForType(Result);
7007 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007008 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7009 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007010 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007011 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007012 }
John McCall31168b02011-06-15 23:02:42 +00007013 } else if (getLangOptions().ObjCAutoRefCount) {
7014 const ObjCMethodDecl *setter
7015 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7016 if (setter) {
7017 ObjCMethodDecl::param_iterator P = setter->param_begin();
7018 LHSTy = (*P)->getType();
7019 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7020 }
John McCall34376a62010-12-04 03:47:34 +00007021 }
7022
John McCall31168b02011-06-15 23:02:42 +00007023 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7024 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007025 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007026 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007027 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007028 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007029 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007030 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7031 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7032 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007033 }
7034}
7035
7036
Anders Carlsson806700f2008-02-01 07:15:58 +00007037/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007038/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007039/// where the declaration is needed for type checking. We only need to
7040/// handle cases when the expression references a function designator
7041/// or is an lvalue. Here are some examples:
7042/// - &(x) => x
7043/// - &*****f => f for f a function designator.
7044/// - &s.xx => s
7045/// - &s.zz[1].yy -> s, if zz is an array
7046/// - *(x + 1) -> x, if x is an array
7047/// - &"123"[2] -> 0
7048/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007049static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007050 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007051 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007052 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007053 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007054 // If this is an arrow operator, the address is an offset from
7055 // the base's value, so the object the base refers to is
7056 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007057 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007058 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007059 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007060 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007061 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007062 // FIXME: This code shouldn't be necessary! We should catch the implicit
7063 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007064 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7065 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7066 if (ICE->getSubExpr()->getType()->isArrayType())
7067 return getPrimaryDecl(ICE->getSubExpr());
7068 }
7069 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007070 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007071 case Stmt::UnaryOperatorClass: {
7072 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007073
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007074 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007075 case UO_Real:
7076 case UO_Imag:
7077 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007078 return getPrimaryDecl(UO->getSubExpr());
7079 default:
7080 return 0;
7081 }
7082 }
Steve Naroff47500512007-04-19 23:00:49 +00007083 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007084 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007085 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007086 // If the result of an implicit cast is an l-value, we care about
7087 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007088 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007089 default:
7090 return 0;
7091 }
7092}
7093
7094/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007095/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007096/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007097/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007098/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007099/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007100/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007101static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7102 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007103 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007104 return S.Context.DependentTy;
7105 if (OrigOp->getType() == S.Context.OverloadTy)
7106 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007107 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7108 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007109 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7110 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7111 << OrigOp->getSourceRange();
7112 return QualType();
7113 }
John McCall8d08b9b2010-08-27 09:08:28 +00007114
John McCall2979fe02011-04-12 00:42:48 +00007115 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007116
John McCall8d08b9b2010-08-27 09:08:28 +00007117 // Make sure to ignore parentheses in subsequent checks
7118 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007119
John McCall4bc41ae2010-11-18 19:01:18 +00007120 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007121 // Implement C99-only parts of addressof rules.
7122 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007123 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007124 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7125 // (assuming the deref expression is valid).
7126 return uOp->getSubExpr()->getType();
7127 }
7128 // Technically, there should be a check for array subscript
7129 // expressions here, but the result of one is always an lvalue anyway.
7130 }
John McCallf3a88602011-02-03 08:15:49 +00007131 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007132 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007133
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007134 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007135 bool sfinae = S.isSFINAEContext();
7136 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7137 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007138 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007139 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007140 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007141 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007142 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007143 } else if (lval == Expr::LV_MemberFunction) {
7144 // If it's an instance method, make a member pointer.
7145 // The expression must have exactly the form &A::foo.
7146
7147 // If the underlying expression isn't a decl ref, give up.
7148 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007149 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007150 << OrigOp->getSourceRange();
7151 return QualType();
7152 }
7153 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7154 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7155
7156 // The id-expression was parenthesized.
7157 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007158 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007159 << OrigOp->getSourceRange();
7160
7161 // The method was named without a qualifier.
7162 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007163 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007164 << op->getSourceRange();
7165 }
7166
John McCall4bc41ae2010-11-18 19:01:18 +00007167 return S.Context.getMemberPointerType(op->getType(),
7168 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007169 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007170 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007171 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007172 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007173 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007174 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007175 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007176 return QualType();
7177 }
John McCall086a4642010-11-24 05:12:34 +00007178 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007179 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007180 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007181 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007182 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007183 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007184 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007185 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007186 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007187 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007188 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007189 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007190 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007191 << "property expression" << op->getSourceRange();
7192 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007193 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007194 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007195 // with the register storage-class specifier.
7196 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007197 // in C++ it is not error to take address of a register
7198 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007199 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007200 !S.getLangOptions().CPlusPlus) {
7201 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007202 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007203 return QualType();
7204 }
John McCalld14a8642009-11-21 08:51:07 +00007205 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007206 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007207 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007208 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007209 // Could be a pointer to member, though, if there is an explicit
7210 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007211 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007212 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007213 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007214 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007215 S.Diag(OpLoc,
7216 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007217 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007218 return QualType();
7219 }
Mike Stump11289f42009-09-09 15:08:12 +00007220
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007221 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7222 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007223 return S.Context.getMemberPointerType(op->getType(),
7224 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007225 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007226 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007227 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007228 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007229 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007230
Eli Friedmance7f9002009-05-16 23:27:50 +00007231 if (lval == Expr::LV_IncompleteVoidType) {
7232 // Taking the address of a void variable is technically illegal, but we
7233 // allow it in cases which are otherwise valid.
7234 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007235 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007236 }
7237
Steve Naroff47500512007-04-19 23:00:49 +00007238 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007239 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007240 return S.Context.getObjCObjectPointerType(op->getType());
7241 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007242}
7243
Chris Lattner9156f1b2010-07-05 19:17:26 +00007244/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007245static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7246 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007247 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007248 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007249
John Wiegley01296292011-04-08 18:41:53 +00007250 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7251 if (ConvResult.isInvalid())
7252 return QualType();
7253 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007254 QualType OpTy = Op->getType();
7255 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007256
7257 if (isa<CXXReinterpretCastExpr>(Op)) {
7258 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7259 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7260 Op->getSourceRange());
7261 }
7262
Chris Lattner9156f1b2010-07-05 19:17:26 +00007263 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7264 // is an incomplete type or void. It would be possible to warn about
7265 // dereferencing a void pointer, but it's completely well-defined, and such a
7266 // warning is unlikely to catch any mistakes.
7267 if (const PointerType *PT = OpTy->getAs<PointerType>())
7268 Result = PT->getPointeeType();
7269 else if (const ObjCObjectPointerType *OPT =
7270 OpTy->getAs<ObjCObjectPointerType>())
7271 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007272 else {
John McCall3aef3d82011-04-10 19:13:55 +00007273 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007274 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007275 if (PR.take() != Op)
7276 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007277 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007278
Chris Lattner9156f1b2010-07-05 19:17:26 +00007279 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007280 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007281 << OpTy << Op->getSourceRange();
7282 return QualType();
7283 }
John McCall4bc41ae2010-11-18 19:01:18 +00007284
7285 // Dereferences are usually l-values...
7286 VK = VK_LValue;
7287
7288 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007289 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007290 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007291
7292 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007293}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007294
John McCalle3027922010-08-25 11:45:40 +00007295static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007296 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007297 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007298 switch (Kind) {
7299 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007300 case tok::periodstar: Opc = BO_PtrMemD; break;
7301 case tok::arrowstar: Opc = BO_PtrMemI; break;
7302 case tok::star: Opc = BO_Mul; break;
7303 case tok::slash: Opc = BO_Div; break;
7304 case tok::percent: Opc = BO_Rem; break;
7305 case tok::plus: Opc = BO_Add; break;
7306 case tok::minus: Opc = BO_Sub; break;
7307 case tok::lessless: Opc = BO_Shl; break;
7308 case tok::greatergreater: Opc = BO_Shr; break;
7309 case tok::lessequal: Opc = BO_LE; break;
7310 case tok::less: Opc = BO_LT; break;
7311 case tok::greaterequal: Opc = BO_GE; break;
7312 case tok::greater: Opc = BO_GT; break;
7313 case tok::exclaimequal: Opc = BO_NE; break;
7314 case tok::equalequal: Opc = BO_EQ; break;
7315 case tok::amp: Opc = BO_And; break;
7316 case tok::caret: Opc = BO_Xor; break;
7317 case tok::pipe: Opc = BO_Or; break;
7318 case tok::ampamp: Opc = BO_LAnd; break;
7319 case tok::pipepipe: Opc = BO_LOr; break;
7320 case tok::equal: Opc = BO_Assign; break;
7321 case tok::starequal: Opc = BO_MulAssign; break;
7322 case tok::slashequal: Opc = BO_DivAssign; break;
7323 case tok::percentequal: Opc = BO_RemAssign; break;
7324 case tok::plusequal: Opc = BO_AddAssign; break;
7325 case tok::minusequal: Opc = BO_SubAssign; break;
7326 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7327 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7328 case tok::ampequal: Opc = BO_AndAssign; break;
7329 case tok::caretequal: Opc = BO_XorAssign; break;
7330 case tok::pipeequal: Opc = BO_OrAssign; break;
7331 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007332 }
7333 return Opc;
7334}
7335
John McCalle3027922010-08-25 11:45:40 +00007336static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007337 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007338 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007339 switch (Kind) {
7340 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007341 case tok::plusplus: Opc = UO_PreInc; break;
7342 case tok::minusminus: Opc = UO_PreDec; break;
7343 case tok::amp: Opc = UO_AddrOf; break;
7344 case tok::star: Opc = UO_Deref; break;
7345 case tok::plus: Opc = UO_Plus; break;
7346 case tok::minus: Opc = UO_Minus; break;
7347 case tok::tilde: Opc = UO_Not; break;
7348 case tok::exclaim: Opc = UO_LNot; break;
7349 case tok::kw___real: Opc = UO_Real; break;
7350 case tok::kw___imag: Opc = UO_Imag; break;
7351 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007352 }
7353 return Opc;
7354}
7355
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007356/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7357/// This warning is only emitted for builtin assignment operations. It is also
7358/// suppressed in the event of macro expansions.
7359static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7360 SourceLocation OpLoc) {
7361 if (!S.ActiveTemplateInstantiations.empty())
7362 return;
7363 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7364 return;
7365 lhs = lhs->IgnoreParenImpCasts();
7366 rhs = rhs->IgnoreParenImpCasts();
7367 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7368 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7369 if (!LeftDeclRef || !RightDeclRef ||
7370 LeftDeclRef->getLocation().isMacroID() ||
7371 RightDeclRef->getLocation().isMacroID())
7372 return;
7373 const ValueDecl *LeftDecl =
7374 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7375 const ValueDecl *RightDecl =
7376 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7377 if (LeftDecl != RightDecl)
7378 return;
7379 if (LeftDecl->getType().isVolatileQualified())
7380 return;
7381 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7382 if (RefTy->getPointeeType().isVolatileQualified())
7383 return;
7384
7385 S.Diag(OpLoc, diag::warn_self_assignment)
7386 << LeftDeclRef->getType()
7387 << lhs->getSourceRange() << rhs->getSourceRange();
7388}
7389
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007390/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7391/// operator @p Opc at location @c TokLoc. This routine only supports
7392/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007393ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007394 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007395 Expr *lhsExpr, Expr *rhsExpr) {
7396 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007397 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007398 // The following two variables are used for compound assignment operators
7399 QualType CompLHSTy; // Type of LHS after promotions for computation
7400 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007401 ExprValueKind VK = VK_RValue;
7402 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007403
Douglas Gregor1beec452011-03-12 01:48:56 +00007404 // Check if a 'foo<int>' involved in a binary op, identifies a single
7405 // function unambiguously (i.e. an lvalue ala 13.4)
7406 // But since an assignment can trigger target based overload, exclude it in
7407 // our blind search. i.e:
7408 // template<class T> void f(); template<class T, class U> void f(U);
7409 // f<int> == 0; // resolve f<int> blindly
7410 // void (*p)(int); p = f<int>; // resolve f<int> using target
7411 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007412 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007413 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007414 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007415
John McCall3aef3d82011-04-10 19:13:55 +00007416 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007417 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007418 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007419 }
7420
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007421 // The canonical way to check for a GNU null is with isNullPointerConstant,
7422 // but we use a bit of a hack here for speed; this is a relatively
7423 // hot path, and isNullPointerConstant is slow.
7424 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7425 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007426
7427 // Detect when a NULL constant is used improperly in an expression. These
7428 // are mainly cases where the null pointer is used as an integer instead
7429 // of a pointer.
7430 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007431 // Avoid analyzing cases where the result will either be invalid (and
7432 // diagnosed as such) or entirely valid and not something to warn about.
7433 QualType LeftType = lhs.get()->getType();
7434 QualType RightType = rhs.get()->getType();
7435 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7436 !LeftType->isFunctionType() &&
7437 !RightType->isBlockPointerType() &&
7438 !RightType->isMemberPointerType() &&
7439 !RightType->isFunctionType()) {
7440 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7441 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7442 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7443 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7444 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7445 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7446 // These are the operations that would not make sense with a null pointer
7447 // no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007448 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007449 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7450 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7451 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7452 Opc == BO_EQ || Opc == BO_NE) {
7453 // These are the operations that would not make sense with a null pointer
7454 // if the other expression the other expression is not a pointer.
7455 if (LeftNull != RightNull &&
7456 !LeftType->isAnyPointerType() &&
7457 !LeftType->canDecayToPointerType() &&
7458 !RightType->isAnyPointerType() &&
7459 !RightType->canDecayToPointerType()) {
7460 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7461 << (LeftNull ? lhs.get()->getSourceRange()
7462 : rhs.get()->getSourceRange());
7463 }
Richard Trieu701fb362011-06-16 21:36:56 +00007464 }
7465 }
7466 }
7467
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007468 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007469 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007470 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007471 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007472 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7473 VK = lhs.get()->getValueKind();
7474 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007475 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007476 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007477 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007478 break;
John McCalle3027922010-08-25 11:45:40 +00007479 case BO_PtrMemD:
7480 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007481 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007482 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007483 break;
John McCalle3027922010-08-25 11:45:40 +00007484 case BO_Mul:
7485 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007486 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007487 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007488 break;
John McCalle3027922010-08-25 11:45:40 +00007489 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007490 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7491 break;
John McCalle3027922010-08-25 11:45:40 +00007492 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007493 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7494 break;
John McCalle3027922010-08-25 11:45:40 +00007495 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007496 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7497 break;
John McCalle3027922010-08-25 11:45:40 +00007498 case BO_Shl:
7499 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007500 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007501 break;
John McCalle3027922010-08-25 11:45:40 +00007502 case BO_LE:
7503 case BO_LT:
7504 case BO_GE:
7505 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007506 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007507 break;
John McCalle3027922010-08-25 11:45:40 +00007508 case BO_EQ:
7509 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007510 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007511 break;
John McCalle3027922010-08-25 11:45:40 +00007512 case BO_And:
7513 case BO_Xor:
7514 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007515 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7516 break;
John McCalle3027922010-08-25 11:45:40 +00007517 case BO_LAnd:
7518 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007519 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007520 break;
John McCalle3027922010-08-25 11:45:40 +00007521 case BO_MulAssign:
7522 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007523 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007524 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007525 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007526 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7527 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007528 break;
John McCalle3027922010-08-25 11:45:40 +00007529 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007530 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7531 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007532 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7533 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007534 break;
John McCalle3027922010-08-25 11:45:40 +00007535 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007536 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007537 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7538 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007539 break;
John McCalle3027922010-08-25 11:45:40 +00007540 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007541 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007542 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7543 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007544 break;
John McCalle3027922010-08-25 11:45:40 +00007545 case BO_ShlAssign:
7546 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007547 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007548 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007549 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7550 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007551 break;
John McCalle3027922010-08-25 11:45:40 +00007552 case BO_AndAssign:
7553 case BO_XorAssign:
7554 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007555 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7556 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007557 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7558 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007559 break;
John McCalle3027922010-08-25 11:45:40 +00007560 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007561 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007562 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7563 VK = rhs.get()->getValueKind();
7564 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007565 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007566 break;
7567 }
John Wiegley01296292011-04-08 18:41:53 +00007568 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007569 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007570 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007571 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7572 ResultTy, VK, OK, OpLoc));
7573 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007574 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007575 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007576 }
John Wiegley01296292011-04-08 18:41:53 +00007577 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7578 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007579 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007580}
7581
Sebastian Redl44615072009-10-27 12:10:02 +00007582/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7583/// operators are mixed in a way that suggests that the programmer forgot that
7584/// comparison operators have higher precedence. The most typical example of
7585/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007586static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007587 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007588 typedef BinaryOperator BinOp;
7589 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7590 rhsopc = static_cast<BinOp::Opcode>(-1);
7591 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007592 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007593 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007594 rhsopc = BO->getOpcode();
7595
7596 // Subs are not binary operators.
7597 if (lhsopc == -1 && rhsopc == -1)
7598 return;
7599
7600 // Bitwise operations are sometimes used as eager logical ops.
7601 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007602 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7603 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007604 return;
7605
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007606 if (BinOp::isComparisonOp(lhsopc)) {
7607 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7608 << SourceRange(lhs->getLocStart(), OpLoc)
7609 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007610 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007611 Self.PDiag(diag::note_precedence_bitwise_silence)
7612 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007613 lhs->getSourceRange());
7614 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007615 Self.PDiag(diag::note_precedence_bitwise_first)
7616 << BinOp::getOpcodeStr(Opc),
7617 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007618 } else if (BinOp::isComparisonOp(rhsopc)) {
7619 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7620 << SourceRange(OpLoc, rhs->getLocEnd())
7621 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007622 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007623 Self.PDiag(diag::note_precedence_bitwise_silence)
7624 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007625 rhs->getSourceRange());
7626 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007627 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007628 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007629 SourceRange(lhs->getLocStart(),
7630 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007631 }
Sebastian Redl43028242009-10-26 15:24:15 +00007632}
7633
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007634/// \brief It accepts a '&' expr that is inside a '|' one.
7635/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7636/// in parentheses.
7637static void
7638EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7639 BinaryOperator *Bop) {
7640 assert(Bop->getOpcode() == BO_And);
7641 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7642 << Bop->getSourceRange() << OpLoc;
7643 SuggestParentheses(Self, Bop->getOperatorLoc(),
7644 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7645 Bop->getSourceRange());
7646}
7647
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007648/// \brief It accepts a '&&' expr that is inside a '||' one.
7649/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7650/// in parentheses.
7651static void
7652EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007653 BinaryOperator *Bop) {
7654 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007655 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7656 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007657 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007658 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007659 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007660}
7661
7662/// \brief Returns true if the given expression can be evaluated as a constant
7663/// 'true'.
7664static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7665 bool Res;
7666 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7667}
7668
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007669/// \brief Returns true if the given expression can be evaluated as a constant
7670/// 'false'.
7671static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7672 bool Res;
7673 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7674}
7675
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007676/// \brief Look for '&&' in the left hand of a '||' expr.
7677static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007678 Expr *OrLHS, Expr *OrRHS) {
7679 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007680 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007681 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7682 if (EvaluatesAsFalse(S, OrRHS))
7683 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007684 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7685 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7686 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7687 } else if (Bop->getOpcode() == BO_LOr) {
7688 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7689 // If it's "a || b && 1 || c" we didn't warn earlier for
7690 // "a || b && 1", but warn now.
7691 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7692 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7693 }
7694 }
7695 }
7696}
7697
7698/// \brief Look for '&&' in the right hand of a '||' expr.
7699static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007700 Expr *OrLHS, Expr *OrRHS) {
7701 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007702 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007703 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7704 if (EvaluatesAsFalse(S, OrLHS))
7705 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007706 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7707 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7708 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007709 }
7710 }
7711}
7712
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007713/// \brief Look for '&' in the left or right hand of a '|' expr.
7714static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7715 Expr *OrArg) {
7716 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7717 if (Bop->getOpcode() == BO_And)
7718 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7719 }
7720}
7721
Sebastian Redl43028242009-10-26 15:24:15 +00007722/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007723/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007724static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007725 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007726 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007727 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007728 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7729
7730 // Diagnose "arg1 & arg2 | arg3"
7731 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7732 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7733 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7734 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007735
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007736 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7737 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007738 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007739 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7740 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007741 }
Sebastian Redl43028242009-10-26 15:24:15 +00007742}
7743
Steve Naroff218bc2b2007-05-04 21:54:46 +00007744// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007745ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007746 tok::TokenKind Kind,
7747 Expr *lhs, Expr *rhs) {
7748 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007749 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7750 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007751
Sebastian Redl43028242009-10-26 15:24:15 +00007752 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7753 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7754
Douglas Gregor5287f092009-11-05 00:51:44 +00007755 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7756}
7757
John McCalldadc5752010-08-24 06:29:42 +00007758ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007759 BinaryOperatorKind Opc,
7760 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007761 if (getLangOptions().CPlusPlus) {
7762 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007763
John McCall622114c2010-12-06 05:26:58 +00007764 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7765 UseBuiltinOperator = false;
7766 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7767 UseBuiltinOperator = true;
7768 } else {
7769 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7770 !rhs->getType()->isOverloadableType();
7771 }
7772
7773 if (!UseBuiltinOperator) {
7774 // Find all of the overloaded operators visible from this
7775 // point. We perform both an operator-name lookup from the local
7776 // scope and an argument-dependent lookup based on the types of
7777 // the arguments.
7778 UnresolvedSet<16> Functions;
7779 OverloadedOperatorKind OverOp
7780 = BinaryOperator::getOverloadedOperator(Opc);
7781 if (S && OverOp != OO_None)
7782 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7783 Functions);
7784
7785 // Build the (potentially-overloaded, potentially-dependent)
7786 // binary operation.
7787 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7788 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007789 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007790
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007791 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007792 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007793}
7794
John McCalldadc5752010-08-24 06:29:42 +00007795ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007796 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007797 Expr *InputExpr) {
7798 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007799 ExprValueKind VK = VK_RValue;
7800 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007801 QualType resultType;
7802 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007803 case UO_PreInc:
7804 case UO_PreDec:
7805 case UO_PostInc:
7806 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007807 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007808 Opc == UO_PreInc ||
7809 Opc == UO_PostInc,
7810 Opc == UO_PreInc ||
7811 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007812 break;
John McCalle3027922010-08-25 11:45:40 +00007813 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007814 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007815 break;
John McCall31996342011-04-07 08:22:57 +00007816 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007817 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007818 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007819 Input = move(resolved);
7820 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7821 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007822 break;
John McCall31996342011-04-07 08:22:57 +00007823 }
John McCalle3027922010-08-25 11:45:40 +00007824 case UO_Plus:
7825 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007826 Input = UsualUnaryConversions(Input.take());
7827 if (Input.isInvalid()) return ExprError();
7828 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007829 if (resultType->isDependentType())
7830 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007831 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7832 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007833 break;
7834 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7835 resultType->isEnumeralType())
7836 break;
7837 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007838 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007839 resultType->isPointerType())
7840 break;
John McCall36226622010-10-12 02:09:17 +00007841 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007842 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007843 if (Input.isInvalid()) return ExprError();
7844 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007845 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007846
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007847 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007848 << resultType << Input.get()->getSourceRange());
7849
John McCalle3027922010-08-25 11:45:40 +00007850 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00007851 Input = UsualUnaryConversions(Input.take());
7852 if (Input.isInvalid()) return ExprError();
7853 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007854 if (resultType->isDependentType())
7855 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007856 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7857 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7858 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007859 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00007860 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007861 else if (resultType->hasIntegerRepresentation())
7862 break;
7863 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007864 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007865 if (Input.isInvalid()) return ExprError();
7866 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007867 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007869 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007870 }
Steve Naroff35d85152007-05-07 00:24:15 +00007871 break;
John Wiegley01296292011-04-08 18:41:53 +00007872
John McCalle3027922010-08-25 11:45:40 +00007873 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007874 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00007875 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7876 if (Input.isInvalid()) return ExprError();
7877 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007878 if (resultType->isDependentType())
7879 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007880 if (resultType->isScalarType()) {
7881 // C99 6.5.3.3p1: ok, fallthrough;
7882 if (Context.getLangOptions().CPlusPlus) {
7883 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7884 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00007885 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7886 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00007887 }
John McCall36226622010-10-12 02:09:17 +00007888 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007889 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007890 if (Input.isInvalid()) return ExprError();
7891 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00007892 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007893 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00007894 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007895 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007896
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007897 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007898 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007899 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00007900 break;
John McCalle3027922010-08-25 11:45:40 +00007901 case UO_Real:
7902 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007903 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007904 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00007905 if (Input.isInvalid()) return ExprError();
7906 if (Input.get()->getValueKind() != VK_RValue &&
7907 Input.get()->getObjectKind() == OK_Ordinary)
7908 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007909 break;
John McCalle3027922010-08-25 11:45:40 +00007910 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00007911 resultType = Input.get()->getType();
7912 VK = Input.get()->getValueKind();
7913 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007914 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007915 }
John Wiegley01296292011-04-08 18:41:53 +00007916 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007917 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007918
John Wiegley01296292011-04-08 18:41:53 +00007919 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00007920 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007921}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007922
John McCalldadc5752010-08-24 06:29:42 +00007923ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007924 UnaryOperatorKind Opc,
7925 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007926 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007927 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007928 // Find all of the overloaded operators visible from this
7929 // point. We perform both an operator-name lookup from the local
7930 // scope and an argument-dependent lookup based on the types of
7931 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007932 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007933 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007934 if (S && OverOp != OO_None)
7935 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7936 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007937
John McCallb268a282010-08-23 23:25:46 +00007938 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007939 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007940
John McCallb268a282010-08-23 23:25:46 +00007941 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007942}
7943
Douglas Gregor5287f092009-11-05 00:51:44 +00007944// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007945ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007946 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007947 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007948}
7949
Steve Naroff66356bd2007-09-16 14:56:35 +00007950/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007951ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00007952 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007953 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00007954 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00007955 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007956 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00007957}
7958
John McCall31168b02011-06-15 23:02:42 +00007959/// Given the last statement in a statement-expression, check whether
7960/// the result is a producing expression (like a call to an
7961/// ns_returns_retained function) and, if so, rebuild it to hoist the
7962/// release out of the full-expression. Otherwise, return null.
7963/// Cannot fail.
7964static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7965 // Should always be wrapped with one of these.
7966 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7967 if (!cleanups) return 0;
7968
7969 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7970 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7971 return 0;
7972
7973 // Splice out the cast. This shouldn't modify any interesting
7974 // features of the statement.
7975 Expr *producer = cast->getSubExpr();
7976 assert(producer->getType() == cast->getType());
7977 assert(producer->getValueKind() == cast->getValueKind());
7978 cleanups->setSubExpr(producer);
7979 return cleanups;
7980}
7981
John McCalldadc5752010-08-24 06:29:42 +00007982ExprResult
John McCallb268a282010-08-23 23:25:46 +00007983Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007984 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00007985 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7986 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7987
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00007988 bool isFileScope
7989 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00007990 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007991 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00007992
Chris Lattner366727f2007-07-24 16:58:17 +00007993 // FIXME: there are a variety of strange constraints to enforce here, for
7994 // example, it is not possible to goto into a stmt expression apparently.
7995 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007996
Chris Lattner366727f2007-07-24 16:58:17 +00007997 // If there are sub stmts in the compound stmt, take the type of the last one
7998 // as the type of the stmtexpr.
7999 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008000 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008001 if (!Compound->body_empty()) {
8002 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008003 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008004 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008005 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8006 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008007 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008008 }
John McCall31168b02011-06-15 23:02:42 +00008009
John Wiegley01296292011-04-08 18:41:53 +00008010 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008011 // Do function/array conversion on the last expression, but not
8012 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008013 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8014 if (LastExpr.isInvalid())
8015 return ExprError();
8016 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008017
John Wiegley01296292011-04-08 18:41:53 +00008018 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008019 // In ARC, if the final expression ends in a consume, splice
8020 // the consume out and bind it later. In the alternate case
8021 // (when dealing with a retainable type), the result
8022 // initialization will create a produce. In both cases the
8023 // result will be +1, and we'll need to balance that out with
8024 // a bind.
8025 if (Expr *rebuiltLastStmt
8026 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8027 LastExpr = rebuiltLastStmt;
8028 } else {
8029 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008030 InitializedEntity::InitializeResult(LPLoc,
8031 Ty,
8032 false),
8033 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008034 LastExpr);
8035 }
8036
John Wiegley01296292011-04-08 18:41:53 +00008037 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008038 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008039 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008040 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008041 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008042 else
John Wiegley01296292011-04-08 18:41:53 +00008043 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008044 StmtExprMayBindToTemp = true;
8045 }
8046 }
8047 }
Chris Lattner944d3062008-07-26 19:51:01 +00008048 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008049
Eli Friedmanba961a92009-03-23 00:24:07 +00008050 // FIXME: Check that expression type is complete/non-abstract; statement
8051 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008052 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8053 if (StmtExprMayBindToTemp)
8054 return MaybeBindToTemporary(ResStmtExpr);
8055 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008056}
Steve Naroff78864672007-08-01 22:05:33 +00008057
John McCalldadc5752010-08-24 06:29:42 +00008058ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008059 TypeSourceInfo *TInfo,
8060 OffsetOfComponent *CompPtr,
8061 unsigned NumComponents,
8062 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008063 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008064 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008065 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008066
Chris Lattnerf17bd422007-08-30 17:45:32 +00008067 // We must have at least one component that refers to the type, and the first
8068 // one is known to be a field designator. Verify that the ArgTy represents
8069 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008070 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008071 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8072 << ArgTy << TypeRange);
8073
8074 // Type must be complete per C99 7.17p3 because a declaring a variable
8075 // with an incomplete type would be ill-formed.
8076 if (!Dependent
8077 && RequireCompleteType(BuiltinLoc, ArgTy,
8078 PDiag(diag::err_offsetof_incomplete_type)
8079 << TypeRange))
8080 return ExprError();
8081
Chris Lattner78502cf2007-08-31 21:49:13 +00008082 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8083 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008084 // FIXME: This diagnostic isn't actually visible because the location is in
8085 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008086 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008087 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8088 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008089
8090 bool DidWarnAboutNonPOD = false;
8091 QualType CurrentType = ArgTy;
8092 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008093 SmallVector<OffsetOfNode, 4> Comps;
8094 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008095 for (unsigned i = 0; i != NumComponents; ++i) {
8096 const OffsetOfComponent &OC = CompPtr[i];
8097 if (OC.isBrackets) {
8098 // Offset of an array sub-field. TODO: Should we allow vector elements?
8099 if (!CurrentType->isDependentType()) {
8100 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8101 if(!AT)
8102 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8103 << CurrentType);
8104 CurrentType = AT->getElementType();
8105 } else
8106 CurrentType = Context.DependentTy;
8107
8108 // The expression must be an integral expression.
8109 // FIXME: An integral constant expression?
8110 Expr *Idx = static_cast<Expr*>(OC.U.E);
8111 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8112 !Idx->getType()->isIntegerType())
8113 return ExprError(Diag(Idx->getLocStart(),
8114 diag::err_typecheck_subscript_not_integer)
8115 << Idx->getSourceRange());
8116
8117 // Record this array index.
8118 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8119 Exprs.push_back(Idx);
8120 continue;
8121 }
8122
8123 // Offset of a field.
8124 if (CurrentType->isDependentType()) {
8125 // We have the offset of a field, but we can't look into the dependent
8126 // type. Just record the identifier of the field.
8127 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8128 CurrentType = Context.DependentTy;
8129 continue;
8130 }
8131
8132 // We need to have a complete type to look into.
8133 if (RequireCompleteType(OC.LocStart, CurrentType,
8134 diag::err_offsetof_incomplete_type))
8135 return ExprError();
8136
8137 // Look for the designated field.
8138 const RecordType *RC = CurrentType->getAs<RecordType>();
8139 if (!RC)
8140 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8141 << CurrentType);
8142 RecordDecl *RD = RC->getDecl();
8143
8144 // C++ [lib.support.types]p5:
8145 // The macro offsetof accepts a restricted set of type arguments in this
8146 // International Standard. type shall be a POD structure or a POD union
8147 // (clause 9).
8148 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8149 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008150 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008151 PDiag(diag::warn_offsetof_non_pod_type)
8152 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8153 << CurrentType))
8154 DidWarnAboutNonPOD = true;
8155 }
8156
8157 // Look for the field.
8158 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8159 LookupQualifiedName(R, RD);
8160 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008161 IndirectFieldDecl *IndirectMemberDecl = 0;
8162 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008163 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008164 MemberDecl = IndirectMemberDecl->getAnonField();
8165 }
8166
Douglas Gregor882211c2010-04-28 22:16:22 +00008167 if (!MemberDecl)
8168 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8169 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8170 OC.LocEnd));
8171
Douglas Gregor10982ea2010-04-28 22:36:06 +00008172 // C99 7.17p3:
8173 // (If the specified member is a bit-field, the behavior is undefined.)
8174 //
8175 // We diagnose this as an error.
8176 if (MemberDecl->getBitWidth()) {
8177 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8178 << MemberDecl->getDeclName()
8179 << SourceRange(BuiltinLoc, RParenLoc);
8180 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8181 return ExprError();
8182 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008183
8184 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008185 if (IndirectMemberDecl)
8186 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008187
Douglas Gregord1702062010-04-29 00:18:15 +00008188 // If the member was found in a base class, introduce OffsetOfNodes for
8189 // the base class indirections.
8190 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8191 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008192 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008193 CXXBasePath &Path = Paths.front();
8194 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8195 B != BEnd; ++B)
8196 Comps.push_back(OffsetOfNode(B->Base));
8197 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008198
Francois Pichet783dd6e2010-11-21 06:08:52 +00008199 if (IndirectMemberDecl) {
8200 for (IndirectFieldDecl::chain_iterator FI =
8201 IndirectMemberDecl->chain_begin(),
8202 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8203 assert(isa<FieldDecl>(*FI));
8204 Comps.push_back(OffsetOfNode(OC.LocStart,
8205 cast<FieldDecl>(*FI), OC.LocEnd));
8206 }
8207 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008208 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008209
Douglas Gregor882211c2010-04-28 22:16:22 +00008210 CurrentType = MemberDecl->getType().getNonReferenceType();
8211 }
8212
8213 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8214 TInfo, Comps.data(), Comps.size(),
8215 Exprs.data(), Exprs.size(), RParenLoc));
8216}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008217
John McCalldadc5752010-08-24 06:29:42 +00008218ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008219 SourceLocation BuiltinLoc,
8220 SourceLocation TypeLoc,
8221 ParsedType argty,
8222 OffsetOfComponent *CompPtr,
8223 unsigned NumComponents,
8224 SourceLocation RPLoc) {
8225
Douglas Gregor882211c2010-04-28 22:16:22 +00008226 TypeSourceInfo *ArgTInfo;
8227 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8228 if (ArgTy.isNull())
8229 return ExprError();
8230
Eli Friedman06dcfd92010-08-05 10:15:45 +00008231 if (!ArgTInfo)
8232 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8233
8234 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8235 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008236}
8237
8238
John McCalldadc5752010-08-24 06:29:42 +00008239ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008240 Expr *CondExpr,
8241 Expr *LHSExpr, Expr *RHSExpr,
8242 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008243 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8244
John McCall7decc9e2010-11-18 06:31:45 +00008245 ExprValueKind VK = VK_RValue;
8246 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008247 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008248 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008249 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008250 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008251 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008252 } else {
8253 // The conditional expression is required to be a constant expression.
8254 llvm::APSInt condEval(32);
8255 SourceLocation ExpLoc;
8256 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008257 return ExprError(Diag(ExpLoc,
8258 diag::err_typecheck_choose_expr_requires_constant)
8259 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008260
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008261 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008262 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8263
8264 resType = ActiveExpr->getType();
8265 ValueDependent = ActiveExpr->isValueDependent();
8266 VK = ActiveExpr->getValueKind();
8267 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008268 }
8269
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008270 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008271 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008272 resType->isDependentType(),
8273 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008274}
8275
Steve Naroffc540d662008-09-03 18:15:37 +00008276//===----------------------------------------------------------------------===//
8277// Clang Extensions.
8278//===----------------------------------------------------------------------===//
8279
8280/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008281void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008282 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8283 PushBlockScope(BlockScope, Block);
8284 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008285 if (BlockScope)
8286 PushDeclContext(BlockScope, Block);
8287 else
8288 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008289}
8290
Mike Stump82f071f2009-02-04 22:31:32 +00008291void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008292 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008293 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008294 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008295
John McCall8cb7bdf2010-06-04 23:28:52 +00008296 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008297 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008298
John McCall3882ace2011-01-05 12:14:39 +00008299 // GetTypeForDeclarator always produces a function type for a block
8300 // literal signature. Furthermore, it is always a FunctionProtoType
8301 // unless the function was written with a typedef.
8302 assert(T->isFunctionType() &&
8303 "GetTypeForDeclarator made a non-function block signature");
8304
8305 // Look for an explicit signature in that function type.
8306 FunctionProtoTypeLoc ExplicitSignature;
8307
8308 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8309 if (isa<FunctionProtoTypeLoc>(tmp)) {
8310 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8311
8312 // Check whether that explicit signature was synthesized by
8313 // GetTypeForDeclarator. If so, don't save that as part of the
8314 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008315 if (ExplicitSignature.getLocalRangeBegin() ==
8316 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008317 // This would be much cheaper if we stored TypeLocs instead of
8318 // TypeSourceInfos.
8319 TypeLoc Result = ExplicitSignature.getResultLoc();
8320 unsigned Size = Result.getFullDataSize();
8321 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8322 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8323
8324 ExplicitSignature = FunctionProtoTypeLoc();
8325 }
John McCalla3ccba02010-06-04 11:21:44 +00008326 }
Mike Stump11289f42009-09-09 15:08:12 +00008327
John McCall3882ace2011-01-05 12:14:39 +00008328 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8329 CurBlock->FunctionType = T;
8330
8331 const FunctionType *Fn = T->getAs<FunctionType>();
8332 QualType RetTy = Fn->getResultType();
8333 bool isVariadic =
8334 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8335
John McCall8e346702010-06-04 19:02:56 +00008336 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008337
John McCalla3ccba02010-06-04 11:21:44 +00008338 // Don't allow returning a objc interface by value.
8339 if (RetTy->isObjCObjectType()) {
8340 Diag(ParamInfo.getSourceRange().getBegin(),
8341 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8342 return;
8343 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008344
John McCalla3ccba02010-06-04 11:21:44 +00008345 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008346 // return type. TODO: what should we do with declarators like:
8347 // ^ * { ... }
8348 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008349 if (RetTy != Context.DependentTy)
8350 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008351
John McCalla3ccba02010-06-04 11:21:44 +00008352 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008353 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008354 if (ExplicitSignature) {
8355 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8356 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008357 if (Param->getIdentifier() == 0 &&
8358 !Param->isImplicit() &&
8359 !Param->isInvalidDecl() &&
8360 !getLangOptions().CPlusPlus)
8361 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008362 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008363 }
John McCalla3ccba02010-06-04 11:21:44 +00008364
8365 // Fake up parameter variables if we have a typedef, like
8366 // ^ fntype { ... }
8367 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8368 for (FunctionProtoType::arg_type_iterator
8369 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8370 ParmVarDecl *Param =
8371 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8372 ParamInfo.getSourceRange().getBegin(),
8373 *I);
John McCall8e346702010-06-04 19:02:56 +00008374 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008375 }
Steve Naroffc540d662008-09-03 18:15:37 +00008376 }
John McCalla3ccba02010-06-04 11:21:44 +00008377
John McCall8e346702010-06-04 19:02:56 +00008378 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008379 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008380 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008381 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8382 CurBlock->TheDecl->param_end(),
8383 /*CheckParameterNames=*/false);
8384 }
8385
John McCalla3ccba02010-06-04 11:21:44 +00008386 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008387 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008388
John McCall8e346702010-06-04 19:02:56 +00008389 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008390 Diag(ParamInfo.getAttributes()->getLoc(),
8391 diag::warn_attribute_sentinel_not_variadic) << 1;
8392 // FIXME: remove the attribute.
8393 }
8394
8395 // Put the parameter variables in scope. We can bail out immediately
8396 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008397 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008398 return;
8399
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008400 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008401 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8402 (*AI)->setOwningFunction(CurBlock->TheDecl);
8403
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008404 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008405 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008406 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008407
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008408 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008409 }
John McCallf7b2fb52010-01-22 00:28:27 +00008410 }
Steve Naroffc540d662008-09-03 18:15:37 +00008411}
8412
8413/// ActOnBlockError - If there is an error parsing a block, this callback
8414/// is invoked to pop the information about the block from the action impl.
8415void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008416 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008417 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008418 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008419}
8420
8421/// ActOnBlockStmtExpr - This is called when the body of a block statement
8422/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008423ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008424 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008425 // If blocks are disabled, emit an error.
8426 if (!LangOpts.Blocks)
8427 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008428
Douglas Gregor9a28e842010-03-01 23:15:13 +00008429 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008430
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008431 PopDeclContext();
8432
Steve Naroffc540d662008-09-03 18:15:37 +00008433 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008434 if (!BSI->ReturnType.isNull())
8435 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008436
Mike Stump3bf1ab42009-07-28 22:04:01 +00008437 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008438 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008439
John McCallc63de662011-02-02 13:00:07 +00008440 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008441 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8442 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008443
John McCall8e346702010-06-04 19:02:56 +00008444 // If the user wrote a function type in some form, try to use that.
8445 if (!BSI->FunctionType.isNull()) {
8446 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8447
8448 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8449 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8450
8451 // Turn protoless block types into nullary block types.
8452 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008453 FunctionProtoType::ExtProtoInfo EPI;
8454 EPI.ExtInfo = Ext;
8455 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008456
8457 // Otherwise, if we don't need to change anything about the function type,
8458 // preserve its sugar structure.
8459 } else if (FTy->getResultType() == RetTy &&
8460 (!NoReturn || FTy->getNoReturnAttr())) {
8461 BlockTy = BSI->FunctionType;
8462
8463 // Otherwise, make the minimal modifications to the function type.
8464 } else {
8465 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008466 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8467 EPI.TypeQuals = 0; // FIXME: silently?
8468 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008469 BlockTy = Context.getFunctionType(RetTy,
8470 FPT->arg_type_begin(),
8471 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008472 EPI);
John McCall8e346702010-06-04 19:02:56 +00008473 }
8474
8475 // If we don't have a function type, just build one from nothing.
8476 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008477 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008478 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008479 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008480 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008481
John McCall8e346702010-06-04 19:02:56 +00008482 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8483 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008484 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008485
Chris Lattner45542ea2009-04-19 05:28:12 +00008486 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008487 if (getCurFunction()->NeedsScopeChecking() &&
8488 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008489 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008490
Chris Lattner60f84492011-02-17 23:58:47 +00008491 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008492
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008493 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8494 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8495 const VarDecl *variable = ci->getVariable();
8496 QualType T = variable->getType();
8497 QualType::DestructionKind destructKind = T.isDestructedType();
8498 if (destructKind != QualType::DK_none)
8499 getCurFunction()->setHasBranchProtectedScope();
8500 }
8501
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008502 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8503 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8504 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8505
Douglas Gregor9a28e842010-03-01 23:15:13 +00008506 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008507}
8508
John McCalldadc5752010-08-24 06:29:42 +00008509ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008510 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008511 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008512 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008513 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008514 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008515}
8516
John McCalldadc5752010-08-24 06:29:42 +00008517ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008518 Expr *E, TypeSourceInfo *TInfo,
8519 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008520 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008521
Eli Friedman121ba0c2008-08-09 23:32:40 +00008522 // Get the va_list type
8523 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008524 if (VaListType->isArrayType()) {
8525 // Deal with implicit array decay; for example, on x86-64,
8526 // va_list is an array, but it's supposed to decay to
8527 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008528 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008529 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008530 ExprResult Result = UsualUnaryConversions(E);
8531 if (Result.isInvalid())
8532 return ExprError();
8533 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008534 } else {
8535 // Otherwise, the va_list argument must be an l-value because
8536 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008537 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008538 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008539 return ExprError();
8540 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008541
Douglas Gregorad3150c2009-05-19 23:10:31 +00008542 if (!E->isTypeDependent() &&
8543 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008544 return ExprError(Diag(E->getLocStart(),
8545 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008546 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008547 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008548
David Majnemerc75d1a12011-06-14 05:17:32 +00008549 if (!TInfo->getType()->isDependentType()) {
8550 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8551 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8552 << TInfo->getTypeLoc().getSourceRange()))
8553 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008554
David Majnemerc75d1a12011-06-14 05:17:32 +00008555 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8556 TInfo->getType(),
8557 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8558 << TInfo->getTypeLoc().getSourceRange()))
8559 return ExprError();
8560
John McCall31168b02011-06-15 23:02:42 +00008561 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00008562 Diag(TInfo->getTypeLoc().getBeginLoc(),
8563 diag::warn_second_parameter_to_va_arg_not_pod)
8564 << TInfo->getType()
8565 << TInfo->getTypeLoc().getSourceRange();
Eli Friedman6290ae42011-07-11 21:45:59 +00008566
8567 // Check for va_arg where arguments of the given type will be promoted
8568 // (i.e. this va_arg is guaranteed to have undefined behavior).
8569 QualType PromoteType;
8570 if (TInfo->getType()->isPromotableIntegerType()) {
8571 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8572 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8573 PromoteType = QualType();
8574 }
8575 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8576 PromoteType = Context.DoubleTy;
8577 if (!PromoteType.isNull())
8578 Diag(TInfo->getTypeLoc().getBeginLoc(),
8579 diag::warn_second_parameter_to_va_arg_never_compatible)
8580 << TInfo->getType()
8581 << PromoteType
8582 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008583 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008584
Abramo Bagnara27db2392010-08-10 10:06:15 +00008585 QualType T = TInfo->getType().getNonLValueExprType(Context);
8586 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008587}
8588
John McCalldadc5752010-08-24 06:29:42 +00008589ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008590 // The type of __null will be int or long, depending on the size of
8591 // pointers on the target.
8592 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008593 unsigned pw = Context.Target.getPointerWidth(0);
8594 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008595 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008596 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008597 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008598 else if (pw == Context.Target.getLongLongWidth())
8599 Ty = Context.LongLongTy;
8600 else {
8601 assert(!"I don't know size of pointer!");
8602 Ty = Context.IntTy;
8603 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008604
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008605 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008606}
8607
Alexis Huntc46382e2010-04-28 23:02:27 +00008608static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008609 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008610 if (!SemaRef.getLangOptions().ObjC1)
8611 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008612
Anders Carlssonace5d072009-11-10 04:46:30 +00008613 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8614 if (!PT)
8615 return;
8616
8617 // Check if the destination is of type 'id'.
8618 if (!PT->isObjCIdType()) {
8619 // Check if the destination is the 'NSString' interface.
8620 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8621 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8622 return;
8623 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008624
Anders Carlssonace5d072009-11-10 04:46:30 +00008625 // Strip off any parens and casts.
8626 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8627 if (!SL || SL->isWide())
8628 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008629
Douglas Gregora771f462010-03-31 17:46:05 +00008630 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008631}
8632
Chris Lattner9bad62c2008-01-04 18:04:52 +00008633bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8634 SourceLocation Loc,
8635 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008636 Expr *SrcExpr, AssignmentAction Action,
8637 bool *Complained) {
8638 if (Complained)
8639 *Complained = false;
8640
Chris Lattner9bad62c2008-01-04 18:04:52 +00008641 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008642 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008643 bool isInvalid = false;
8644 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008645 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008646
Chris Lattner9bad62c2008-01-04 18:04:52 +00008647 switch (ConvTy) {
8648 default: assert(0 && "Unknown conversion type");
8649 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008650 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008651 DiagKind = diag::ext_typecheck_convert_pointer_int;
8652 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008653 case IntToPointer:
8654 DiagKind = diag::ext_typecheck_convert_int_pointer;
8655 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008656 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008657 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008658 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008659 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8660 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +00008661 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008662 case IncompatiblePointerSign:
8663 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8664 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008665 case FunctionVoidPointer:
8666 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8667 break;
John McCall4fff8f62011-02-01 00:10:29 +00008668 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008669 // Perform array-to-pointer decay if necessary.
8670 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8671
John McCall4fff8f62011-02-01 00:10:29 +00008672 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8673 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8674 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8675 DiagKind = diag::err_typecheck_incompatible_address_space;
8676 break;
John McCall31168b02011-06-15 23:02:42 +00008677
8678
8679 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008680 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008681 break;
John McCall4fff8f62011-02-01 00:10:29 +00008682 }
8683
8684 llvm_unreachable("unknown error case for discarding qualifiers!");
8685 // fallthrough
8686 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008687 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008688 // If the qualifiers lost were because we were applying the
8689 // (deprecated) C++ conversion from a string literal to a char*
8690 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8691 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008692 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008693 // bit of refactoring (so that the second argument is an
8694 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008695 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008696 // C++ semantics.
8697 if (getLangOptions().CPlusPlus &&
8698 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8699 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008700 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8701 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008702 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008703 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008704 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008705 case IntToBlockPointer:
8706 DiagKind = diag::err_int_to_block_pointer;
8707 break;
8708 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008709 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008710 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008711 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008712 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008713 // it can give a more specific diagnostic.
8714 DiagKind = diag::warn_incompatible_qualified_id;
8715 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008716 case IncompatibleVectors:
8717 DiagKind = diag::warn_incompatible_vectors;
8718 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008719 case IncompatibleObjCWeakRef:
8720 DiagKind = diag::err_arc_weak_unavailable_assign;
8721 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008722 case Incompatible:
8723 DiagKind = diag::err_typecheck_convert_incompatible;
8724 isInvalid = true;
8725 break;
8726 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008727
Douglas Gregorc68e1402010-04-09 00:35:39 +00008728 QualType FirstType, SecondType;
8729 switch (Action) {
8730 case AA_Assigning:
8731 case AA_Initializing:
8732 // The destination type comes first.
8733 FirstType = DstType;
8734 SecondType = SrcType;
8735 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008736
Douglas Gregorc68e1402010-04-09 00:35:39 +00008737 case AA_Returning:
8738 case AA_Passing:
8739 case AA_Converting:
8740 case AA_Sending:
8741 case AA_Casting:
8742 // The source type comes first.
8743 FirstType = SrcType;
8744 SecondType = DstType;
8745 break;
8746 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008747
Douglas Gregorc68e1402010-04-09 00:35:39 +00008748 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008749 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +00008750 if (CheckInferredResultType)
8751 EmitRelatedResultTypeNote(SrcExpr);
8752
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008753 if (Complained)
8754 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008755 return isInvalid;
8756}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008757
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008758bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008759 llvm::APSInt ICEResult;
8760 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8761 if (Result)
8762 *Result = ICEResult;
8763 return false;
8764 }
8765
Anders Carlssone54e8a12008-11-30 19:50:32 +00008766 Expr::EvalResult EvalResult;
8767
Mike Stump4e1f26a2009-02-19 03:04:26 +00008768 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008769 EvalResult.HasSideEffects) {
8770 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8771
8772 if (EvalResult.Diag) {
8773 // We only show the note if it's not the usual "invalid subexpression"
8774 // or if it's actually in a subexpression.
8775 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8776 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8777 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8778 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008779
Anders Carlssone54e8a12008-11-30 19:50:32 +00008780 return true;
8781 }
8782
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008783 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8784 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008785
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008786 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008787 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8788 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008789 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008790
Anders Carlssone54e8a12008-11-30 19:50:32 +00008791 if (Result)
8792 *Result = EvalResult.Val.getInt();
8793 return false;
8794}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008795
Douglas Gregorff790f12009-11-26 00:44:06 +00008796void
Mike Stump11289f42009-09-09 15:08:12 +00008797Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008798 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008799 ExpressionEvaluationContextRecord(NewContext,
8800 ExprTemporaries.size(),
8801 ExprNeedsCleanups));
8802 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008803}
8804
Mike Stump11289f42009-09-09 15:08:12 +00008805void
Douglas Gregorff790f12009-11-26 00:44:06 +00008806Sema::PopExpressionEvaluationContext() {
8807 // Pop the current expression evaluation context off the stack.
8808 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8809 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008810
Douglas Gregorfab31f42009-12-12 07:57:52 +00008811 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8812 if (Rec.PotentiallyReferenced) {
8813 // Mark any remaining declarations in the current position of the stack
8814 // as "referenced". If they were not meant to be referenced, semantic
8815 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008816 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008817 I = Rec.PotentiallyReferenced->begin(),
8818 IEnd = Rec.PotentiallyReferenced->end();
8819 I != IEnd; ++I)
8820 MarkDeclarationReferenced(I->first, I->second);
8821 }
8822
8823 if (Rec.PotentiallyDiagnosed) {
8824 // Emit any pending diagnostics.
8825 for (PotentiallyEmittedDiagnostics::iterator
8826 I = Rec.PotentiallyDiagnosed->begin(),
8827 IEnd = Rec.PotentiallyDiagnosed->end();
8828 I != IEnd; ++I)
8829 Diag(I->first, I->second);
8830 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008831 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008832
8833 // When are coming out of an unevaluated context, clear out any
8834 // temporaries that we may have created as part of the evaluation of
8835 // the expression in that context: they aren't relevant because they
8836 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00008837 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008838 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8839 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00008840 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8841
8842 // Otherwise, merge the contexts together.
8843 } else {
8844 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8845 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008846
8847 // Destroy the popped expression evaluation record.
8848 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008849}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008850
John McCall31168b02011-06-15 23:02:42 +00008851void Sema::DiscardCleanupsInEvaluationContext() {
8852 ExprTemporaries.erase(
8853 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8854 ExprTemporaries.end());
8855 ExprNeedsCleanups = false;
8856}
8857
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008858/// \brief Note that the given declaration was referenced in the source code.
8859///
8860/// This routine should be invoke whenever a given declaration is referenced
8861/// in the source code, and where that reference occurred. If this declaration
8862/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8863/// C99 6.9p3), then the declaration will be marked as used.
8864///
8865/// \param Loc the location where the declaration was referenced.
8866///
8867/// \param D the declaration that has been referenced by the source code.
8868void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8869 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008870
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00008871 D->setReferenced();
8872
Douglas Gregorebada0772010-06-17 23:14:26 +00008873 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008874 return;
Mike Stump11289f42009-09-09 15:08:12 +00008875
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008876 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8877 // template or not. The reason for this is that unevaluated expressions
8878 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8879 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008880 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008881 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008882 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008883 return;
8884 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008885
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008886 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8887 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008888
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008889 // Do not mark anything as "used" within a dependent context; wait for
8890 // an instantiation.
8891 if (CurContext->isDependentContext())
8892 return;
Mike Stump11289f42009-09-09 15:08:12 +00008893
Douglas Gregorff790f12009-11-26 00:44:06 +00008894 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008895 case Unevaluated:
8896 // We are in an expression that is not potentially evaluated; do nothing.
8897 return;
Mike Stump11289f42009-09-09 15:08:12 +00008898
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008899 case PotentiallyEvaluated:
8900 // We are in a potentially-evaluated expression, so this declaration is
8901 // "used"; handle this below.
8902 break;
Mike Stump11289f42009-09-09 15:08:12 +00008903
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008904 case PotentiallyPotentiallyEvaluated:
8905 // We are in an expression that may be potentially evaluated; queue this
8906 // declaration reference until we know whether the expression is
8907 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008908 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008909 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008910
8911 case PotentiallyEvaluatedIfUsed:
8912 // Referenced declarations will only be used if the construct in the
8913 // containing expression is used.
8914 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008915 }
Mike Stump11289f42009-09-09 15:08:12 +00008916
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008917 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008918 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008919 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8920 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00008921 return;
8922 if (!Constructor->isUsed(false))
8923 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00008924 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00008925 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008926 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00008927 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008928 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008929
Douglas Gregor88d292c2010-05-13 16:44:06 +00008930 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008931 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00008932 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008933 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008934 if (Destructor->isVirtual())
8935 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008936 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00008937 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008938 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008939 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008940 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008941 } else if (MethodDecl->isVirtual())
8942 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008943 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008944 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00008945 // Recursive functions should be marked when used from another function.
8946 if (CurContext == Function) return;
8947
Mike Stump11289f42009-09-09 15:08:12 +00008948 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008949 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008950 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008951 bool AlreadyInstantiated = false;
8952 if (FunctionTemplateSpecializationInfo *SpecInfo
8953 = Function->getTemplateSpecializationInfo()) {
8954 if (SpecInfo->getPointOfInstantiation().isInvalid())
8955 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008956 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008957 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008958 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008959 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008960 = Function->getMemberSpecializationInfo()) {
8961 if (MSInfo->getPointOfInstantiation().isInvalid())
8962 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008963 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008964 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008965 AlreadyInstantiated = true;
8966 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008967
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008968 if (!AlreadyInstantiated) {
8969 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8970 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8971 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8972 Loc));
8973 else
Chandler Carruth54080172010-08-25 08:44:16 +00008974 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008975 }
John McCall83779672011-02-19 02:53:41 +00008976 } else {
8977 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008978 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8979 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008980 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008981 MarkDeclarationReferenced(Loc, *i);
8982 }
John McCall83779672011-02-19 02:53:41 +00008983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008984
John McCall83779672011-02-19 02:53:41 +00008985 // Keep track of used but undefined functions.
8986 if (!Function->isPure() && !Function->hasBody() &&
8987 Function->getLinkage() != ExternalLinkage) {
8988 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
8989 if (old.isInvalid()) old = Loc;
8990 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008991
John McCall83779672011-02-19 02:53:41 +00008992 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008993 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008994 }
Mike Stump11289f42009-09-09 15:08:12 +00008995
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008996 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008997 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008998 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008999 Var->getInstantiatedFromStaticDataMember()) {
9000 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9001 assert(MSInfo && "Missing member specialization information?");
9002 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9003 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9004 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009005 // This is a modification of an existing AST node. Notify listeners.
9006 if (ASTMutationListener *L = getASTMutationListener())
9007 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009008 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009009 }
9010 }
Mike Stump11289f42009-09-09 15:08:12 +00009011
John McCall15dd4042011-02-21 19:25:48 +00009012 // Keep track of used but undefined variables. We make a hole in
9013 // the warning for static const data members with in-line
9014 // initializers.
John McCall83779672011-02-19 02:53:41 +00009015 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009016 && Var->getLinkage() != ExternalLinkage
9017 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009018 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9019 if (old.isInvalid()) old = Loc;
9020 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009021
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009022 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009023 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009024 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009025}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009026
Douglas Gregor5597ab42010-05-07 23:12:07 +00009027namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009028 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009029 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009030 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009031 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9032 Sema &S;
9033 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009034
Douglas Gregor5597ab42010-05-07 23:12:07 +00009035 public:
9036 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009037
Douglas Gregor5597ab42010-05-07 23:12:07 +00009038 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009039
9040 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9041 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009042 };
9043}
9044
Chandler Carruthaf80f662010-06-09 08:17:30 +00009045bool MarkReferencedDecls::TraverseTemplateArgument(
9046 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009047 if (Arg.getKind() == TemplateArgument::Declaration) {
9048 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9049 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009050
9051 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009052}
9053
Chandler Carruthaf80f662010-06-09 08:17:30 +00009054bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009055 if (ClassTemplateSpecializationDecl *Spec
9056 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9057 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009058 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009059 }
9060
Chandler Carruthc65667c2010-06-10 10:31:57 +00009061 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009062}
9063
9064void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9065 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009066 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009067}
9068
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009069namespace {
9070 /// \brief Helper class that marks all of the declarations referenced by
9071 /// potentially-evaluated subexpressions as "referenced".
9072 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9073 Sema &S;
9074
9075 public:
9076 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9077
9078 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9079
9080 void VisitDeclRefExpr(DeclRefExpr *E) {
9081 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9082 }
9083
9084 void VisitMemberExpr(MemberExpr *E) {
9085 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009086 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009087 }
9088
9089 void VisitCXXNewExpr(CXXNewExpr *E) {
9090 if (E->getConstructor())
9091 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9092 if (E->getOperatorNew())
9093 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9094 if (E->getOperatorDelete())
9095 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009096 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009097 }
9098
9099 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9100 if (E->getOperatorDelete())
9101 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009102 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9103 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9104 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9105 S.MarkDeclarationReferenced(E->getLocStart(),
9106 S.LookupDestructor(Record));
9107 }
9108
Douglas Gregor32b3de52010-09-11 23:32:50 +00009109 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009110 }
9111
9112 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9113 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009114 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009115 }
9116
9117 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9118 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9119 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009120
9121 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9122 Visit(E->getExpr());
9123 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009124 };
9125}
9126
9127/// \brief Mark any declarations that appear within this expression or any
9128/// potentially-evaluated subexpressions as "referenced".
9129void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9130 EvaluatedExprMarker(*this).Visit(E);
9131}
9132
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009133/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9134/// of the program being compiled.
9135///
9136/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009137/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009138/// possibility that the code will actually be executable. Code in sizeof()
9139/// expressions, code used only during overload resolution, etc., are not
9140/// potentially evaluated. This routine will suppress such diagnostics or,
9141/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009142/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009143/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009144///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009145/// This routine should be used for all diagnostics that describe the run-time
9146/// behavior of a program, such as passing a non-POD value through an ellipsis.
9147/// Failure to do so will likely result in spurious diagnostics or failures
9148/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009149bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009150 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009151 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009152 case Unevaluated:
9153 // The argument will never be evaluated, so don't complain.
9154 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009155
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009156 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009157 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009158 if (stmt && getCurFunctionOrMethodDecl()) {
9159 FunctionScopes.back()->PossiblyUnreachableDiags.
9160 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9161 }
9162 else
9163 Diag(Loc, PD);
9164
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009165 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009166
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009167 case PotentiallyPotentiallyEvaluated:
9168 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9169 break;
9170 }
9171
9172 return false;
9173}
9174
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009175bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9176 CallExpr *CE, FunctionDecl *FD) {
9177 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9178 return false;
9179
9180 PartialDiagnostic Note =
9181 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9182 << FD->getDeclName() : PDiag();
9183 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009184
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009185 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009186 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009187 PDiag(diag::err_call_function_incomplete_return)
9188 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009189 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009190 << CE->getSourceRange(),
9191 std::make_pair(NoteLoc, Note)))
9192 return true;
9193
9194 return false;
9195}
9196
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009197// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009198// will prevent this condition from triggering, which is what we want.
9199void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9200 SourceLocation Loc;
9201
John McCall0506e4a2009-11-11 02:41:58 +00009202 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009203 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009204
John McCalld5707ab2009-10-12 21:59:07 +00009205 if (isa<BinaryOperator>(E)) {
9206 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009207 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009208 return;
9209
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009210 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9211
John McCallb0e419e2009-11-12 00:06:05 +00009212 // Greylist some idioms by putting them into a warning subcategory.
9213 if (ObjCMessageExpr *ME
9214 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9215 Selector Sel = ME->getSelector();
9216
John McCallb0e419e2009-11-12 00:06:05 +00009217 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009218 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009219 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9220
9221 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009222 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009223 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9224 }
John McCall0506e4a2009-11-11 02:41:58 +00009225
John McCalld5707ab2009-10-12 21:59:07 +00009226 Loc = Op->getOperatorLoc();
9227 } else if (isa<CXXOperatorCallExpr>(E)) {
9228 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009229 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009230 return;
9231
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009232 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009233 Loc = Op->getOperatorLoc();
9234 } else {
9235 // Not an assignment.
9236 return;
9237 }
9238
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009239 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009240
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009241 SourceLocation Open = E->getSourceRange().getBegin();
9242 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9243 Diag(Loc, diag::note_condition_assign_silence)
9244 << FixItHint::CreateInsertion(Open, "(")
9245 << FixItHint::CreateInsertion(Close, ")");
9246
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009247 if (IsOrAssign)
9248 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9249 << FixItHint::CreateReplacement(Loc, "!=");
9250 else
9251 Diag(Loc, diag::note_condition_assign_to_comparison)
9252 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009253}
9254
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009255/// \brief Redundant parentheses over an equality comparison can indicate
9256/// that the user intended an assignment used as condition.
9257void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009258 // Don't warn if the parens came from a macro.
9259 SourceLocation parenLoc = parenE->getLocStart();
9260 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9261 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009262 // Don't warn for dependent expressions.
9263 if (parenE->isTypeDependent())
9264 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009265
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009266 Expr *E = parenE->IgnoreParens();
9267
9268 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009269 if (opE->getOpcode() == BO_EQ &&
9270 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9271 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009272 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009273
Ted Kremenekae022092011-02-02 02:20:30 +00009274 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009275 Diag(Loc, diag::note_equality_comparison_silence)
9276 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9277 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009278 Diag(Loc, diag::note_equality_comparison_to_assign)
9279 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009280 }
9281}
9282
John Wiegley01296292011-04-08 18:41:53 +00009283ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009284 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009285 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9286 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009287
John McCall0009fcc2011-04-26 20:42:42 +00009288 ExprResult result = CheckPlaceholderExpr(E);
9289 if (result.isInvalid()) return ExprError();
9290 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009291
John McCall0009fcc2011-04-26 20:42:42 +00009292 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009293 if (getLangOptions().CPlusPlus)
9294 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9295
John Wiegley01296292011-04-08 18:41:53 +00009296 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9297 if (ERes.isInvalid())
9298 return ExprError();
9299 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009300
9301 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009302 if (!T->isScalarType()) { // C99 6.8.4.1p1
9303 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9304 << T << E->getSourceRange();
9305 return ExprError();
9306 }
John McCalld5707ab2009-10-12 21:59:07 +00009307 }
9308
John Wiegley01296292011-04-08 18:41:53 +00009309 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009310}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009311
John McCalldadc5752010-08-24 06:29:42 +00009312ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9313 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009314 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009315 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009316
9317 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009318}
John McCall36e7fe32010-10-12 00:20:44 +00009319
John McCall31996342011-04-07 08:22:57 +00009320namespace {
John McCall2979fe02011-04-12 00:42:48 +00009321 /// A visitor for rebuilding a call to an __unknown_any expression
9322 /// to have an appropriate type.
9323 struct RebuildUnknownAnyFunction
9324 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9325
9326 Sema &S;
9327
9328 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9329
9330 ExprResult VisitStmt(Stmt *S) {
9331 llvm_unreachable("unexpected statement!");
9332 return ExprError();
9333 }
9334
9335 ExprResult VisitExpr(Expr *expr) {
9336 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9337 << expr->getSourceRange();
9338 return ExprError();
9339 }
9340
9341 /// Rebuild an expression which simply semantically wraps another
9342 /// expression which it shares the type and value kind of.
9343 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9344 ExprResult subResult = Visit(expr->getSubExpr());
9345 if (subResult.isInvalid()) return ExprError();
9346
9347 Expr *subExpr = subResult.take();
9348 expr->setSubExpr(subExpr);
9349 expr->setType(subExpr->getType());
9350 expr->setValueKind(subExpr->getValueKind());
9351 assert(expr->getObjectKind() == OK_Ordinary);
9352 return expr;
9353 }
9354
9355 ExprResult VisitParenExpr(ParenExpr *paren) {
9356 return rebuildSugarExpr(paren);
9357 }
9358
9359 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9360 return rebuildSugarExpr(op);
9361 }
9362
9363 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9364 ExprResult subResult = Visit(op->getSubExpr());
9365 if (subResult.isInvalid()) return ExprError();
9366
9367 Expr *subExpr = subResult.take();
9368 op->setSubExpr(subExpr);
9369 op->setType(S.Context.getPointerType(subExpr->getType()));
9370 assert(op->getValueKind() == VK_RValue);
9371 assert(op->getObjectKind() == OK_Ordinary);
9372 return op;
9373 }
9374
9375 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9376 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9377
9378 expr->setType(decl->getType());
9379
9380 assert(expr->getValueKind() == VK_RValue);
9381 if (S.getLangOptions().CPlusPlus &&
9382 !(isa<CXXMethodDecl>(decl) &&
9383 cast<CXXMethodDecl>(decl)->isInstance()))
9384 expr->setValueKind(VK_LValue);
9385
9386 return expr;
9387 }
9388
9389 ExprResult VisitMemberExpr(MemberExpr *mem) {
9390 return resolveDecl(mem, mem->getMemberDecl());
9391 }
9392
9393 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9394 return resolveDecl(ref, ref->getDecl());
9395 }
9396 };
9397}
9398
9399/// Given a function expression of unknown-any type, try to rebuild it
9400/// to have a function type.
9401static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9402 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9403 if (result.isInvalid()) return ExprError();
9404 return S.DefaultFunctionArrayConversion(result.take());
9405}
9406
9407namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009408 /// A visitor for rebuilding an expression of type __unknown_anytype
9409 /// into one which resolves the type directly on the referring
9410 /// expression. Strict preservation of the original source
9411 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009412 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009413 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009414
9415 Sema &S;
9416
9417 /// The current destination type.
9418 QualType DestType;
9419
9420 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9421 : S(S), DestType(castType) {}
9422
John McCall39439732011-04-09 22:50:59 +00009423 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009424 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009425 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009426 }
9427
John McCall2d2e8702011-04-11 07:02:50 +00009428 ExprResult VisitExpr(Expr *expr) {
9429 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9430 << expr->getSourceRange();
9431 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009432 }
9433
John McCall2d2e8702011-04-11 07:02:50 +00009434 ExprResult VisitCallExpr(CallExpr *call);
9435 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9436
John McCall39439732011-04-09 22:50:59 +00009437 /// Rebuild an expression which simply semantically wraps another
9438 /// expression which it shares the type and value kind of.
9439 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9440 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009441 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009442 Expr *subExpr = subResult.take();
9443 expr->setSubExpr(subExpr);
9444 expr->setType(subExpr->getType());
9445 expr->setValueKind(subExpr->getValueKind());
9446 assert(expr->getObjectKind() == OK_Ordinary);
9447 return expr;
9448 }
John McCall31996342011-04-07 08:22:57 +00009449
John McCall39439732011-04-09 22:50:59 +00009450 ExprResult VisitParenExpr(ParenExpr *paren) {
9451 return rebuildSugarExpr(paren);
9452 }
9453
9454 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9455 return rebuildSugarExpr(op);
9456 }
9457
John McCall2979fe02011-04-12 00:42:48 +00009458 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9459 const PointerType *ptr = DestType->getAs<PointerType>();
9460 if (!ptr) {
9461 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9462 << op->getSourceRange();
9463 return ExprError();
9464 }
9465 assert(op->getValueKind() == VK_RValue);
9466 assert(op->getObjectKind() == OK_Ordinary);
9467 op->setType(DestType);
9468
9469 // Build the sub-expression as if it were an object of the pointee type.
9470 DestType = ptr->getPointeeType();
9471 ExprResult subResult = Visit(op->getSubExpr());
9472 if (subResult.isInvalid()) return ExprError();
9473 op->setSubExpr(subResult.take());
9474 return op;
9475 }
9476
John McCall2d2e8702011-04-11 07:02:50 +00009477 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009478
John McCall2979fe02011-04-12 00:42:48 +00009479 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009480
John McCall2979fe02011-04-12 00:42:48 +00009481 ExprResult VisitMemberExpr(MemberExpr *mem) {
9482 return resolveDecl(mem, mem->getMemberDecl());
9483 }
John McCall39439732011-04-09 22:50:59 +00009484
9485 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009486 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009487 }
9488 };
9489}
9490
John McCall2d2e8702011-04-11 07:02:50 +00009491/// Rebuilds a call expression which yielded __unknown_anytype.
9492ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9493 Expr *callee = call->getCallee();
9494
9495 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009496 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009497 FK_FunctionPointer,
9498 FK_BlockPointer
9499 };
9500
9501 FnKind kind;
9502 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009503 if (type == S.Context.BoundMemberTy) {
9504 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9505 kind = FK_MemberFunction;
9506 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009507 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9508 type = ptr->getPointeeType();
9509 kind = FK_FunctionPointer;
9510 } else {
9511 type = type->castAs<BlockPointerType>()->getPointeeType();
9512 kind = FK_BlockPointer;
9513 }
9514 const FunctionType *fnType = type->castAs<FunctionType>();
9515
9516 // Verify that this is a legal result type of a function.
9517 if (DestType->isArrayType() || DestType->isFunctionType()) {
9518 unsigned diagID = diag::err_func_returning_array_function;
9519 if (kind == FK_BlockPointer)
9520 diagID = diag::err_block_returning_array_function;
9521
9522 S.Diag(call->getExprLoc(), diagID)
9523 << DestType->isFunctionType() << DestType;
9524 return ExprError();
9525 }
9526
9527 // Otherwise, go ahead and set DestType as the call's result.
9528 call->setType(DestType.getNonLValueExprType(S.Context));
9529 call->setValueKind(Expr::getValueKindForType(DestType));
9530 assert(call->getObjectKind() == OK_Ordinary);
9531
9532 // Rebuild the function type, replacing the result type with DestType.
9533 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9534 DestType = S.Context.getFunctionType(DestType,
9535 proto->arg_type_begin(),
9536 proto->getNumArgs(),
9537 proto->getExtProtoInfo());
9538 else
9539 DestType = S.Context.getFunctionNoProtoType(DestType,
9540 fnType->getExtInfo());
9541
9542 // Rebuild the appropriate pointer-to-function type.
9543 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009544 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009545 // Nothing to do.
9546 break;
9547
9548 case FK_FunctionPointer:
9549 DestType = S.Context.getPointerType(DestType);
9550 break;
9551
9552 case FK_BlockPointer:
9553 DestType = S.Context.getBlockPointerType(DestType);
9554 break;
9555 }
9556
9557 // Finally, we can recurse.
9558 ExprResult calleeResult = Visit(callee);
9559 if (!calleeResult.isUsable()) return ExprError();
9560 call->setCallee(calleeResult.take());
9561
9562 // Bind a temporary if necessary.
9563 return S.MaybeBindToTemporary(call);
9564}
9565
9566ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009567 // Verify that this is a legal result type of a call.
9568 if (DestType->isArrayType() || DestType->isFunctionType()) {
9569 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9570 << DestType->isFunctionType() << DestType;
9571 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009572 }
9573
John McCall3f4138c2011-07-13 17:56:40 +00009574 // Rewrite the method result type if available.
9575 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9576 assert(method->getResultType() == S.Context.UnknownAnyTy);
9577 method->setResultType(DestType);
9578 }
John McCall2979fe02011-04-12 00:42:48 +00009579
John McCall2d2e8702011-04-11 07:02:50 +00009580 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009581 msg->setType(DestType.getNonReferenceType());
9582 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009583
John McCall2979fe02011-04-12 00:42:48 +00009584 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009585}
9586
9587ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009588 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009589 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009590 assert(ice->getValueKind() == VK_RValue);
9591 assert(ice->getObjectKind() == OK_Ordinary);
9592
John McCall2979fe02011-04-12 00:42:48 +00009593 ice->setType(DestType);
9594
John McCall2d2e8702011-04-11 07:02:50 +00009595 // Rebuild the sub-expression as the pointee (function) type.
9596 DestType = DestType->castAs<PointerType>()->getPointeeType();
9597
9598 ExprResult result = Visit(ice->getSubExpr());
9599 if (!result.isUsable()) return ExprError();
9600
9601 ice->setSubExpr(result.take());
9602 return S.Owned(ice);
9603}
9604
John McCall2979fe02011-04-12 00:42:48 +00009605ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009606 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009607 QualType type = DestType;
9608
9609 // We know how to make this work for certain kinds of decls:
9610
9611 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009612 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009613 // This is true because FunctionDecls must always have function
9614 // type, so we can't be resolving the entire thing at once.
9615 assert(type->isFunctionType());
9616
John McCall4adb38c2011-04-27 00:36:17 +00009617 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9618 if (method->isInstance()) {
9619 valueKind = VK_RValue;
9620 type = S.Context.BoundMemberTy;
9621 }
9622
John McCall2d2e8702011-04-11 07:02:50 +00009623 // Function references aren't l-values in C.
9624 if (!S.getLangOptions().CPlusPlus)
9625 valueKind = VK_RValue;
9626
9627 // - variables
9628 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009629 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9630 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009631 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009632 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9633 << decl << expr->getSourceRange();
9634 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009635 }
9636
9637 // - nothing else
9638 } else {
9639 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9640 << decl << expr->getSourceRange();
9641 return ExprError();
9642 }
9643
John McCall2979fe02011-04-12 00:42:48 +00009644 decl->setType(DestType);
9645 expr->setType(type);
9646 expr->setValueKind(valueKind);
9647 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009648}
9649
John McCall31996342011-04-07 08:22:57 +00009650/// Check a cast of an unknown-any type. We intentionally only
9651/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009652ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9653 Expr *castExpr, CastKind &castKind,
9654 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009655 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009656 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9657 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009658
John McCall39439732011-04-09 22:50:59 +00009659 castExpr = result.take();
9660 VK = castExpr->getValueKind();
9661 castKind = CK_NoOp;
9662
9663 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009664}
9665
9666static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9667 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009668 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009669 while (true) {
9670 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009671 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009672 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009673 diagID = diag::err_uncasted_call_of_unknown_any;
9674 } else {
John McCall31996342011-04-07 08:22:57 +00009675 break;
John McCall2d2e8702011-04-11 07:02:50 +00009676 }
John McCall31996342011-04-07 08:22:57 +00009677 }
9678
John McCall2d2e8702011-04-11 07:02:50 +00009679 SourceLocation loc;
9680 NamedDecl *d;
9681 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9682 loc = ref->getLocation();
9683 d = ref->getDecl();
9684 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9685 loc = mem->getMemberLoc();
9686 d = mem->getMemberDecl();
9687 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9688 diagID = diag::err_uncasted_call_of_unknown_any;
9689 loc = msg->getSelectorLoc();
9690 d = msg->getMethodDecl();
9691 assert(d && "unknown method returning __unknown_any?");
9692 } else {
9693 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9694 << e->getSourceRange();
9695 return ExprError();
9696 }
9697
9698 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009699
9700 // Never recoverable.
9701 return ExprError();
9702}
9703
John McCall36e7fe32010-10-12 00:20:44 +00009704/// Check for operands with placeholder types and complain if found.
9705/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009706ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009707 // Placeholder types are always *exactly* the appropriate builtin type.
9708 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009709
John McCall31996342011-04-07 08:22:57 +00009710 // Overloaded expressions.
9711 if (type == Context.OverloadTy)
9712 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009713 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009714 QualType(),
9715 diag::err_ovl_unresolvable);
9716
John McCall0009fcc2011-04-26 20:42:42 +00009717 // Bound member functions.
9718 if (type == Context.BoundMemberTy) {
9719 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9720 << E->getSourceRange();
9721 return ExprError();
9722 }
9723
John McCall31996342011-04-07 08:22:57 +00009724 // Expressions of unknown type.
9725 if (type == Context.UnknownAnyTy)
9726 return diagnoseUnknownAnyExpr(*this, E);
9727
9728 assert(!type->isPlaceholderType());
9729 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009730}
Richard Trieu2c850c02011-04-21 21:44:26 +00009731
9732bool Sema::CheckCaseExpression(Expr *expr) {
9733 if (expr->isTypeDependent())
9734 return true;
9735 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9736 return expr->getType()->isIntegralOrEnumerationType();
9737 return false;
9738}