blob: 31eb19e1747824731251cb47c18c5432ce286130 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
John McCallb46f2872011-09-09 07:56:05 +0000149/// DiagnoseSentinelCalls - This routine checks whether a call or
150/// message-send is to a declaration with the sentinel attribute, and
151/// if so, it checks that the requirements of the sentinel are
152/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000154 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
John McCallb46f2872011-09-09 07:56:05 +0000159 // The number of formal parameters of the declaration.
160 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000161
John McCallb46f2872011-09-09 07:56:05 +0000162 // The kind of declaration. This is also an index into a %select in
163 // the diagnostic.
164 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
165
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000166 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000167 numFormalParams = MD->param_size();
168 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000169 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000170 numFormalParams = FD->param_size();
171 calleeType = CT_Function;
172 } else if (isa<VarDecl>(D)) {
173 QualType type = cast<ValueDecl>(D)->getType();
174 const FunctionType *fn = 0;
175 if (const PointerType *ptr = type->getAs<PointerType>()) {
176 fn = ptr->getPointeeType()->getAs<FunctionType>();
177 if (!fn) return;
178 calleeType = CT_Function;
179 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
180 fn = ptr->getPointeeType()->castAs<FunctionType>();
181 calleeType = CT_Block;
182 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000183 return;
John McCallb46f2872011-09-09 07:56:05 +0000184 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000185
John McCallb46f2872011-09-09 07:56:05 +0000186 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
187 numFormalParams = proto->getNumArgs();
188 } else {
189 numFormalParams = 0;
190 }
191 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000192 return;
193 }
John McCallb46f2872011-09-09 07:56:05 +0000194
195 // "nullPos" is the number of formal parameters at the end which
196 // effectively count as part of the variadic arguments. This is
197 // useful if you would prefer to not have *any* formal parameters,
198 // but the language forces you to have at least one.
199 unsigned nullPos = attr->getNullPos();
200 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
201 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
202
203 // The number of arguments which should follow the sentinel.
204 unsigned numArgsAfterSentinel = attr->getSentinel();
205
206 // If there aren't enough arguments for all the formal parameters,
207 // the sentinel, and the args after the sentinel, complain.
208 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000209 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000210 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000211 return;
212 }
John McCallb46f2872011-09-09 07:56:05 +0000213
214 // Otherwise, find the sentinel expression.
215 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000216 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000217 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000218
219 // nullptr_t is always treated as null.
220 if (sentinelExpr->getType()->isNullPtrType()) return;
221
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000222 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000223 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
224 Expr::NPC_ValueDependentIsNull))
225 return;
226
227 // Unfortunately, __null has type 'int'.
228 if (isa<GNUNullExpr>(sentinelExpr)) return;
229
John McCallb46f2872011-09-09 07:56:05 +0000230 // Pick a reasonable string to insert. Optimistically use 'nil' or
231 // 'NULL' if those are actually defined in the context. Only use
232 // 'nil' for ObjC methods, where it's much more likely that the
233 // variadic arguments form a list of object pointers.
234 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000235 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
236 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000237 if (calleeType == CT_Method &&
238 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000239 NullValue = "nil";
240 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
241 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000242 else
John McCallb46f2872011-09-09 07:56:05 +0000243 NullValue = "(void*) 0";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000244
245 Diag(MissingNilLoc, diag::warn_missing_sentinel)
John McCallb46f2872011-09-09 07:56:05 +0000246 << calleeType
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000247 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000248 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000249}
250
Richard Trieuba63ce62011-09-09 01:45:06 +0000251SourceRange Sema::getExprRange(Expr *E) const {
252 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000253}
254
Chris Lattner513165e2008-07-25 21:10:04 +0000255//===----------------------------------------------------------------------===//
256// Standard Promotions and Conversions
257//===----------------------------------------------------------------------===//
258
Chris Lattner513165e2008-07-25 21:10:04 +0000259/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000260ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000261 QualType Ty = E->getType();
262 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
263
Chris Lattner513165e2008-07-25 21:10:04 +0000264 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000265 E = ImpCastExprToType(E, Context.getPointerType(Ty),
266 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000267 else if (Ty->isArrayType()) {
268 // In C90 mode, arrays only promote to pointers if the array expression is
269 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
270 // type 'array of type' is converted to an expression that has type 'pointer
271 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
272 // that has type 'array of type' ...". The relevant change is "an lvalue"
273 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000274 //
275 // C++ 4.2p1:
276 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
277 // T" can be converted to an rvalue of type "pointer to T".
278 //
John McCall086a4642010-11-24 05:12:34 +0000279 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
281 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000282 }
John Wiegley01296292011-04-08 18:41:53 +0000283 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000284}
285
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000286static void CheckForNullPointerDereference(Sema &S, Expr *E) {
287 // Check to see if we are dereferencing a null pointer. If so,
288 // and if not volatile-qualified, this is undefined behavior that the
289 // optimizer will delete, so warn about it. People sometimes try to use this
290 // to get a deterministic trap and are surprised by clang's behavior. This
291 // only handles the pattern "*null", which is a very syntactic check.
292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
293 if (UO->getOpcode() == UO_Deref &&
294 UO->getSubExpr()->IgnoreParenCasts()->
295 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
296 !UO->getType().isVolatileQualified()) {
297 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
298 S.PDiag(diag::warn_indirection_through_null)
299 << UO->getSubExpr()->getSourceRange());
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::note_indirection_through_null));
302 }
303}
304
John Wiegley01296292011-04-08 18:41:53 +0000305ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000306 // C++ [conv.lval]p1:
307 // A glvalue of a non-function, non-array type T can be
308 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000309 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000310
John McCall27584242010-12-06 20:48:59 +0000311 QualType T = E->getType();
312 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000313
John McCall27584242010-12-06 20:48:59 +0000314 // Create a load out of an ObjCProperty l-value, if necessary.
315 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000316 ExprResult Res = ConvertPropertyForRValue(E);
317 if (Res.isInvalid())
318 return Owned(E);
319 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000320 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000321 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000322 }
John McCall27584242010-12-06 20:48:59 +0000323
324 // We don't want to throw lvalue-to-rvalue casts on top of
325 // expressions of certain types in C++.
326 if (getLangOptions().CPlusPlus &&
327 (E->getType() == Context.OverloadTy ||
328 T->isDependentType() ||
329 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000330 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000331
332 // The C standard is actually really unclear on this point, and
333 // DR106 tells us what the result should be but not why. It's
334 // generally best to say that void types just doesn't undergo
335 // lvalue-to-rvalue at all. Note that expressions of unqualified
336 // 'void' type are never l-values, but qualified void can be.
337 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000338 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000339
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000340 CheckForNullPointerDereference(*this, E);
341
John McCall27584242010-12-06 20:48:59 +0000342 // C++ [conv.lval]p1:
343 // [...] If T is a non-class type, the type of the prvalue is the
344 // cv-unqualified version of T. Otherwise, the type of the
345 // rvalue is T.
346 //
347 // C99 6.3.2.1p2:
348 // If the lvalue has qualified type, the value has the unqualified
349 // version of the type of the lvalue; otherwise, the value has the
350 // type of the lvalue.
351 if (T.hasQualifiers())
352 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000353
John Wiegley01296292011-04-08 18:41:53 +0000354 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
355 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000356}
357
John Wiegley01296292011-04-08 18:41:53 +0000358ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
359 ExprResult Res = DefaultFunctionArrayConversion(E);
360 if (Res.isInvalid())
361 return ExprError();
362 Res = DefaultLvalueConversion(Res.take());
363 if (Res.isInvalid())
364 return ExprError();
365 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000366}
367
368
Chris Lattner513165e2008-07-25 21:10:04 +0000369/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000370/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000371/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000372/// apply if the array is an argument to the sizeof or address (&) operators.
373/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000374ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000375 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000376 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
377 if (Res.isInvalid())
378 return Owned(E);
379 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000380
381 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000382 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000383
384 // Try to perform integral promotions if the object has a theoretically
385 // promotable type.
386 if (Ty->isIntegralOrUnscopedEnumerationType()) {
387 // C99 6.3.1.1p2:
388 //
389 // The following may be used in an expression wherever an int or
390 // unsigned int may be used:
391 // - an object or expression with an integer type whose integer
392 // conversion rank is less than or equal to the rank of int
393 // and unsigned int.
394 // - A bit-field of type _Bool, int, signed int, or unsigned int.
395 //
396 // If an int can represent all values of the original type, the
397 // value is converted to an int; otherwise, it is converted to an
398 // unsigned int. These are called the integer promotions. All
399 // other types are unchanged by the integer promotions.
400
401 QualType PTy = Context.isPromotableBitField(E);
402 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000403 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
404 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000405 }
406 if (Ty->isPromotableIntegerType()) {
407 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
409 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000410 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000411 }
John Wiegley01296292011-04-08 18:41:53 +0000412 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000413}
414
Chris Lattner2ce500f2008-07-25 22:25:12 +0000415/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000416/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000417/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000418ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
419 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000420 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000421
John Wiegley01296292011-04-08 18:41:53 +0000422 ExprResult Res = UsualUnaryConversions(E);
423 if (Res.isInvalid())
424 return Owned(E);
425 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000426
Chris Lattner2ce500f2008-07-25 22:25:12 +0000427 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000428 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000429 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
430
John McCall4bb057d2011-08-27 22:06:17 +0000431 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000432 // promotion, even on class types, but note:
433 // C++11 [conv.lval]p2:
434 // When an lvalue-to-rvalue conversion occurs in an unevaluated
435 // operand or a subexpression thereof the value contained in the
436 // referenced object is not accessed. Otherwise, if the glvalue
437 // has a class type, the conversion copy-initializes a temporary
438 // of type T from the glvalue and the result of the conversion
439 // is a prvalue for the temporary.
440 // FIXME: add some way to gate this entire thing for correctness in
441 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000442 if (getLangOptions().CPlusPlus && E->isGLValue() &&
443 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000444 ExprResult Temp = PerformCopyInitialization(
445 InitializedEntity::InitializeTemporary(E->getType()),
446 E->getExprLoc(),
447 Owned(E));
448 if (Temp.isInvalid())
449 return ExprError();
450 E = Temp.get();
451 }
452
John Wiegley01296292011-04-08 18:41:53 +0000453 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000454}
455
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000456/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
457/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000458/// interfaces passed by value.
459ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000460 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000461 ExprResult ExprRes = CheckPlaceholderExpr(E);
462 if (ExprRes.isInvalid())
463 return ExprError();
464
465 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000466 if (ExprRes.isInvalid())
467 return ExprError();
468 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000469
Douglas Gregor347e0f22011-05-21 19:26:31 +0000470 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000471 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000472 DiagRuntimeBehavior(E->getLocStart(), 0,
473 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
474 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000475 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000476
John McCall31168b02011-06-15 23:02:42 +0000477 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000478 // C++0x [expr.call]p7:
479 // Passing a potentially-evaluated argument of class type (Clause 9)
480 // having a non-trivial copy constructor, a non-trivial move constructor,
481 // or a non-trivial destructor, with no corresponding parameter,
482 // is conditionally-supported with implementation-defined semantics.
483 bool TrivialEnough = false;
484 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
485 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
486 if (Record->hasTrivialCopyConstructor() &&
487 Record->hasTrivialMoveConstructor() &&
488 Record->hasTrivialDestructor())
489 TrivialEnough = true;
490 }
491 }
John McCall31168b02011-06-15 23:02:42 +0000492
493 if (!TrivialEnough &&
494 getLangOptions().ObjCAutoRefCount &&
495 E->getType()->isObjCLifetimeType())
496 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000497
498 if (TrivialEnough) {
499 // Nothing to diagnose. This is okay.
500 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000501 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000502 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000503 << CT)) {
504 // Turn this into a trap.
505 CXXScopeSpec SS;
506 UnqualifiedId Name;
507 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
508 E->getLocStart());
509 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
510 if (TrapFn.isInvalid())
511 return ExprError();
512
513 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
514 MultiExprArg(), E->getLocEnd());
515 if (Call.isInvalid())
516 return ExprError();
517
518 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
519 Call.get(), E);
520 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000521 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000522 E = Comma.get();
523 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000524 }
525
John Wiegley01296292011-04-08 18:41:53 +0000526 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000527}
528
Richard Trieu7aa58f12011-09-02 20:58:51 +0000529/// \brief Converts an integer to complex float type. Helper function of
530/// UsualArithmeticConversions()
531///
532/// \return false if the integer expression is an integer type and is
533/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000534static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
535 ExprResult &ComplexExpr,
536 QualType IntTy,
537 QualType ComplexTy,
538 bool SkipCast) {
539 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
540 if (SkipCast) return false;
541 if (IntTy->isIntegerType()) {
542 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
543 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
544 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000545 CK_FloatingRealToComplex);
546 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000547 assert(IntTy->isComplexIntegerType());
548 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000549 CK_IntegralComplexToFloatingComplex);
550 }
551 return false;
552}
553
554/// \brief Takes two complex float types and converts them to the same type.
555/// Helper function of UsualArithmeticConversions()
556static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000557handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
558 ExprResult &RHS, QualType LHSType,
559 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000560 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000561 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000562
563 if (order < 0) {
564 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000565 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000566 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
567 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000568 }
569 if (order > 0)
570 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000571 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
572 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000573}
574
575/// \brief Converts otherExpr to complex float and promotes complexExpr if
576/// necessary. Helper function of UsualArithmeticConversions()
577static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000578 ExprResult &ComplexExpr,
579 ExprResult &OtherExpr,
580 QualType ComplexTy,
581 QualType OtherTy,
582 bool ConvertComplexExpr,
583 bool ConvertOtherExpr) {
584 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000585
586 // If just the complexExpr is complex, the otherExpr needs to be converted,
587 // and the complexExpr might need to be promoted.
588 if (order > 0) { // complexExpr is wider
589 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000590 if (ConvertOtherExpr) {
591 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
592 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
593 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000594 CK_FloatingRealToComplex);
595 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000596 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000597 }
598
599 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000600 QualType result = (order == 0 ? ComplexTy :
601 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000602
603 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000604 if (ConvertOtherExpr)
605 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000606 CK_FloatingRealToComplex);
607
608 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000609 if (ConvertComplexExpr && order < 0)
610 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000611 CK_FloatingComplexCast);
612
613 return result;
614}
615
616/// \brief Handle arithmetic conversion with complex types. Helper function of
617/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000618static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
619 ExprResult &RHS, QualType LHSType,
620 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000621 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000622 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000623 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000624 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000625 return LHSType;
626 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000627 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000628 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000629
630 // This handles complex/complex, complex/float, or float/complex.
631 // When both operands are complex, the shorter operand is converted to the
632 // type of the longer, and that is the type of the result. This corresponds
633 // to what is done when combining two real floating-point operands.
634 // The fun begins when size promotion occur across type domains.
635 // From H&S 6.3.4: When one operand is complex and the other is a real
636 // floating-point type, the less precise type is converted, within it's
637 // real or complex domain, to the precision of the other type. For example,
638 // when combining a "long double" with a "double _Complex", the
639 // "double _Complex" is promoted to "long double _Complex".
640
Richard Trieu5065cdd2011-09-06 18:25:09 +0000641 bool LHSComplexFloat = LHSType->isComplexType();
642 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643
644 // If both are complex, just cast to the more precise type.
645 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000646 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
647 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000648 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000649
650 // If only one operand is complex, promote it if necessary and convert the
651 // other operand to complex.
652 if (LHSComplexFloat)
653 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000654 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000655 /*convertOtherExpr*/ true);
656
657 assert(RHSComplexFloat);
658 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000659 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000660 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000661}
662
663/// \brief Hande arithmetic conversion from integer to float. Helper function
664/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000665static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
666 ExprResult &IntExpr,
667 QualType FloatTy, QualType IntTy,
668 bool ConvertFloat, bool ConvertInt) {
669 if (IntTy->isIntegerType()) {
670 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000671 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000672 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000673 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000674 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675 }
676
677 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000678 assert(IntTy->isComplexIntegerType());
679 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000680
681 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000682 if (ConvertInt)
683 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000684 CK_IntegralComplexToFloatingComplex);
685
686 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000687 if (ConvertFloat)
688 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000689 CK_FloatingRealToComplex);
690
691 return result;
692}
693
694/// \brief Handle arithmethic conversion with floating point types. Helper
695/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000696static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
697 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000698 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000699 bool LHSFloat = LHSType->isRealFloatingType();
700 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000701
702 // If we have two real floating types, convert the smaller operand
703 // to the bigger result.
704 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000705 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000706 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000707 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
708 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000709 }
710
711 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000712 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000713 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
714 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715 }
716
717 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000718 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000719 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 /*convertInt=*/ true);
721 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000722 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000723 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000724 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000725}
726
727/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000728/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000729// FIXME: if the operands are (int, _Complex long), we currently
730// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000731static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
732 ExprResult &RHS, QualType LHSType,
733 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000734 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000735 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
736 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000737
Richard Trieucfe3f212011-09-06 18:38:41 +0000738 if (LHSComplexInt && RHSComplexInt) {
739 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
740 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741 assert(order && "inequal types with equal element ordering");
742 if (order > 0) {
743 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000744 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
745 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000746 }
747
Richard Trieuba63ce62011-09-09 01:45:06 +0000748 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000749 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
750 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000751 }
752
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000755 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
756 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000757 }
758
Richard Trieucfe3f212011-09-06 18:38:41 +0000759 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000761 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000762 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
763 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000764}
765
766/// \brief Handle integer arithmetic conversions. Helper function of
767/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000768static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
769 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000772 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
773 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
774 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
775 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000776 // Same signedness; use the higher-ranked type
777 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000778 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
779 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000780 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000781 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
782 return RHSType;
783 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000784 // The unsigned type has greater than or equal rank to the
785 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000786 if (RHSSigned) {
787 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
788 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000789 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000790 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
791 return RHSType;
792 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000793 // The two types are different widths; if we are here, that
794 // means the signed type is larger than the unsigned type, so
795 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000796 if (LHSSigned) {
797 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
798 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000799 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000800 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
801 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000802 } else {
803 // The signed type is higher-ranked than the unsigned type,
804 // but isn't actually any bigger (like unsigned int and long
805 // on most 32-bit systems). Use the unsigned type corresponding
806 // to the signed type.
807 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000808 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
809 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000811 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000812 return result;
813 }
814}
815
Chris Lattner513165e2008-07-25 21:10:04 +0000816/// UsualArithmeticConversions - Performs various conversions that are common to
817/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000818/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000819/// responsible for emitting appropriate error diagnostics.
820/// FIXME: verify the conversion rules for "complex int" are consistent with
821/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000822QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000823 bool IsCompAssign) {
824 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000825 LHS = UsualUnaryConversions(LHS.take());
826 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000827 return QualType();
828 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000829
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000830 RHS = UsualUnaryConversions(RHS.take());
831 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000832 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000833
Mike Stump11289f42009-09-09 15:08:12 +0000834 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000835 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000836 QualType LHSType =
837 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
838 QualType RHSType =
839 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000840
841 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000842 if (LHSType == RHSType)
843 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000844
845 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
846 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000847 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
848 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000849
John McCalld005ac92010-11-13 08:17:45 +0000850 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000851 QualType LHSUnpromotedType = LHSType;
852 if (LHSType->isPromotableIntegerType())
853 LHSType = Context.getPromotedIntegerType(LHSType);
854 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000855 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000856 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000857 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000858 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000859
John McCalld005ac92010-11-13 08:17:45 +0000860 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000861 if (LHSType == RHSType)
862 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000863
864 // At this point, we have two different arithmetic types.
865
866 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 if (LHSType->isComplexType() || RHSType->isComplexType())
868 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000869 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000870
871 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000872 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
873 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000874 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000875
876 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000878 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000879 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000880
881 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000882 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000883 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000884}
885
Chris Lattner513165e2008-07-25 21:10:04 +0000886//===----------------------------------------------------------------------===//
887// Semantic Analysis for various Expression Types
888//===----------------------------------------------------------------------===//
889
890
Peter Collingbourne91147592011-04-15 00:35:48 +0000891ExprResult
892Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
893 SourceLocation DefaultLoc,
894 SourceLocation RParenLoc,
895 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000896 MultiTypeArg ArgTypes,
897 MultiExprArg ArgExprs) {
898 unsigned NumAssocs = ArgTypes.size();
899 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000900
Richard Trieuba63ce62011-09-09 01:45:06 +0000901 ParsedType *ParsedTypes = ArgTypes.release();
902 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000903
904 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
905 for (unsigned i = 0; i < NumAssocs; ++i) {
906 if (ParsedTypes[i])
907 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
908 else
909 Types[i] = 0;
910 }
911
912 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
913 ControllingExpr, Types, Exprs,
914 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000915 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000916 return ER;
917}
918
919ExprResult
920Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
921 SourceLocation DefaultLoc,
922 SourceLocation RParenLoc,
923 Expr *ControllingExpr,
924 TypeSourceInfo **Types,
925 Expr **Exprs,
926 unsigned NumAssocs) {
927 bool TypeErrorFound = false,
928 IsResultDependent = ControllingExpr->isTypeDependent(),
929 ContainsUnexpandedParameterPack
930 = ControllingExpr->containsUnexpandedParameterPack();
931
932 for (unsigned i = 0; i < NumAssocs; ++i) {
933 if (Exprs[i]->containsUnexpandedParameterPack())
934 ContainsUnexpandedParameterPack = true;
935
936 if (Types[i]) {
937 if (Types[i]->getType()->containsUnexpandedParameterPack())
938 ContainsUnexpandedParameterPack = true;
939
940 if (Types[i]->getType()->isDependentType()) {
941 IsResultDependent = true;
942 } else {
943 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
944 // complete object type other than a variably modified type."
945 unsigned D = 0;
946 if (Types[i]->getType()->isIncompleteType())
947 D = diag::err_assoc_type_incomplete;
948 else if (!Types[i]->getType()->isObjectType())
949 D = diag::err_assoc_type_nonobject;
950 else if (Types[i]->getType()->isVariablyModifiedType())
951 D = diag::err_assoc_type_variably_modified;
952
953 if (D != 0) {
954 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
955 << Types[i]->getTypeLoc().getSourceRange()
956 << Types[i]->getType();
957 TypeErrorFound = true;
958 }
959
960 // C1X 6.5.1.1p2 "No two generic associations in the same generic
961 // selection shall specify compatible types."
962 for (unsigned j = i+1; j < NumAssocs; ++j)
963 if (Types[j] && !Types[j]->getType()->isDependentType() &&
964 Context.typesAreCompatible(Types[i]->getType(),
965 Types[j]->getType())) {
966 Diag(Types[j]->getTypeLoc().getBeginLoc(),
967 diag::err_assoc_compatible_types)
968 << Types[j]->getTypeLoc().getSourceRange()
969 << Types[j]->getType()
970 << Types[i]->getType();
971 Diag(Types[i]->getTypeLoc().getBeginLoc(),
972 diag::note_compat_assoc)
973 << Types[i]->getTypeLoc().getSourceRange()
974 << Types[i]->getType();
975 TypeErrorFound = true;
976 }
977 }
978 }
979 }
980 if (TypeErrorFound)
981 return ExprError();
982
983 // If we determined that the generic selection is result-dependent, don't
984 // try to compute the result expression.
985 if (IsResultDependent)
986 return Owned(new (Context) GenericSelectionExpr(
987 Context, KeyLoc, ControllingExpr,
988 Types, Exprs, NumAssocs, DefaultLoc,
989 RParenLoc, ContainsUnexpandedParameterPack));
990
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000991 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000992 unsigned DefaultIndex = -1U;
993 for (unsigned i = 0; i < NumAssocs; ++i) {
994 if (!Types[i])
995 DefaultIndex = i;
996 else if (Context.typesAreCompatible(ControllingExpr->getType(),
997 Types[i]->getType()))
998 CompatIndices.push_back(i);
999 }
1000
1001 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1002 // type compatible with at most one of the types named in its generic
1003 // association list."
1004 if (CompatIndices.size() > 1) {
1005 // We strip parens here because the controlling expression is typically
1006 // parenthesized in macro definitions.
1007 ControllingExpr = ControllingExpr->IgnoreParens();
1008 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1009 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1010 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001011 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001012 E = CompatIndices.end(); I != E; ++I) {
1013 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1014 diag::note_compat_assoc)
1015 << Types[*I]->getTypeLoc().getSourceRange()
1016 << Types[*I]->getType();
1017 }
1018 return ExprError();
1019 }
1020
1021 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1022 // its controlling expression shall have type compatible with exactly one of
1023 // the types named in its generic association list."
1024 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1025 // We strip parens here because the controlling expression is typically
1026 // parenthesized in macro definitions.
1027 ControllingExpr = ControllingExpr->IgnoreParens();
1028 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1029 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1030 return ExprError();
1031 }
1032
1033 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1034 // type name that is compatible with the type of the controlling expression,
1035 // then the result expression of the generic selection is the expression
1036 // in that generic association. Otherwise, the result expression of the
1037 // generic selection is the expression in the default generic association."
1038 unsigned ResultIndex =
1039 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1040
1041 return Owned(new (Context) GenericSelectionExpr(
1042 Context, KeyLoc, ControllingExpr,
1043 Types, Exprs, NumAssocs, DefaultLoc,
1044 RParenLoc, ContainsUnexpandedParameterPack,
1045 ResultIndex));
1046}
1047
Steve Naroff83895f72007-09-16 03:34:24 +00001048/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001049/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1050/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1051/// multiple tokens. However, the common case is that StringToks points to one
1052/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001053///
John McCalldadc5752010-08-24 06:29:42 +00001054ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001055Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001056 assert(NumStringToks && "Must have at least one string!");
1057
Chris Lattner8a24e582009-01-16 18:51:42 +00001058 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001059 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001060 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001061
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001062 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001063 for (unsigned i = 0; i != NumStringToks; ++i)
1064 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001065
Chris Lattner36fc8792008-02-11 00:02:17 +00001066 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001067 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001068 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001069 else if (Literal.isUTF16())
1070 StrTy = Context.Char16Ty;
1071 else if (Literal.isUTF32())
1072 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001073 else if (Literal.Pascal)
1074 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001075
Douglas Gregorfb65e592011-07-27 05:40:30 +00001076 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1077 if (Literal.isWide())
1078 Kind = StringLiteral::Wide;
1079 else if (Literal.isUTF8())
1080 Kind = StringLiteral::UTF8;
1081 else if (Literal.isUTF16())
1082 Kind = StringLiteral::UTF16;
1083 else if (Literal.isUTF32())
1084 Kind = StringLiteral::UTF32;
1085
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001086 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001087 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001088 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001089
Chris Lattner36fc8792008-02-11 00:02:17 +00001090 // Get an array type for the string, according to C99 6.4.5. This includes
1091 // the nul terminator character as well as the string length for pascal
1092 // strings.
1093 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001094 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001095 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001096
Chris Lattner5b183d82006-11-10 05:03:26 +00001097 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001098 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001099 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001100 &StringTokLocs[0],
1101 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001102}
1103
John McCallc63de662011-02-02 13:00:07 +00001104enum CaptureResult {
1105 /// No capture is required.
1106 CR_NoCapture,
1107
1108 /// A capture is required.
1109 CR_Capture,
1110
John McCall351762c2011-02-07 10:33:21 +00001111 /// A by-ref capture is required.
1112 CR_CaptureByRef,
1113
John McCallc63de662011-02-02 13:00:07 +00001114 /// An error occurred when trying to capture the given variable.
1115 CR_Error
1116};
1117
1118/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001119///
John McCallc63de662011-02-02 13:00:07 +00001120/// \param var - the variable referenced
1121/// \param DC - the context which we couldn't capture through
1122static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001123diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001124 VarDecl *var, DeclContext *DC) {
1125 switch (S.ExprEvalContexts.back().Context) {
1126 case Sema::Unevaluated:
1127 // The argument will never be evaluated, so don't complain.
1128 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001129
John McCallc63de662011-02-02 13:00:07 +00001130 case Sema::PotentiallyEvaluated:
1131 case Sema::PotentiallyEvaluatedIfUsed:
1132 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001133
John McCallc63de662011-02-02 13:00:07 +00001134 case Sema::PotentiallyPotentiallyEvaluated:
1135 // FIXME: delay these!
1136 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001137 }
Mike Stump11289f42009-09-09 15:08:12 +00001138
John McCallc63de662011-02-02 13:00:07 +00001139 // Don't diagnose about capture if we're not actually in code right
1140 // now; in general, there are more appropriate places that will
1141 // diagnose this.
1142 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1143
John McCall92d627e2011-03-22 23:15:50 +00001144 // Certain madnesses can happen with parameter declarations, which
1145 // we want to ignore.
1146 if (isa<ParmVarDecl>(var)) {
1147 // - If the parameter still belongs to the translation unit, then
1148 // we're actually just using one parameter in the declaration of
1149 // the next. This is useful in e.g. VLAs.
1150 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1151 return CR_NoCapture;
1152
1153 // - This particular madness can happen in ill-formed default
1154 // arguments; claim it's okay and let downstream code handle it.
1155 if (S.CurContext == var->getDeclContext()->getParent())
1156 return CR_NoCapture;
1157 }
John McCallc63de662011-02-02 13:00:07 +00001158
1159 DeclarationName functionName;
1160 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1161 functionName = fn->getDeclName();
1162 // FIXME: variable from enclosing block that we couldn't capture from!
1163
1164 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1165 << var->getIdentifier() << functionName;
1166 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1167 << var->getIdentifier();
1168
1169 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001170}
1171
John McCall351762c2011-02-07 10:33:21 +00001172/// There is a well-formed capture at a particular scope level;
1173/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001174static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1175 const BlockDecl::Capture &Capture) {
1176 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001177
1178 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001179 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001180 i != e; ++i) {
1181 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1182 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001183 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1184 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001185 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1186 }
1187
Richard Trieuba63ce62011-09-09 01:45:06 +00001188 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001189}
1190
1191/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001192/// given value in the current context requires a variable capture.
1193///
1194/// This also keeps the captures set in the BlockScopeInfo records
1195/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001196static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001197 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001198 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001199 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001200 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001201
1202 // Fast path: variables from the current context never require capture.
1203 DeclContext *DC = S.CurContext;
1204 if (var->getDeclContext() == DC) return CR_NoCapture;
1205
1206 // Only variables with local storage require capture.
1207 // FIXME: What about 'const' variables in C++?
1208 if (!var->hasLocalStorage()) return CR_NoCapture;
1209
1210 // Otherwise, we need to capture.
1211
1212 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001213 do {
1214 // Only blocks (and eventually C++0x closures) can capture; other
1215 // scopes don't work.
1216 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001217 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001218
1219 BlockScopeInfo *blockScope =
1220 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1221 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1222
John McCall351762c2011-02-07 10:33:21 +00001223 // Check whether we've already captured it in this block. If so,
1224 // we're done.
1225 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1226 return propagateCapture(S, functionScopesIndex,
1227 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001228
1229 functionScopesIndex--;
1230 DC = cast<BlockDecl>(DC)->getDeclContext();
1231 } while (var->getDeclContext() != DC);
1232
John McCall351762c2011-02-07 10:33:21 +00001233 // Okay, we descended all the way to the block that defines the variable.
1234 // Actually try to capture it.
1235 QualType type = var->getType();
1236
1237 // Prohibit variably-modified types.
1238 if (type->isVariablyModifiedType()) {
1239 S.Diag(loc, diag::err_ref_vm_type);
1240 S.Diag(var->getLocation(), diag::note_declared_at);
1241 return CR_Error;
1242 }
1243
1244 // Prohibit arrays, even in __block variables, but not references to
1245 // them.
1246 if (type->isArrayType()) {
1247 S.Diag(loc, diag::err_ref_array_type);
1248 S.Diag(var->getLocation(), diag::note_declared_at);
1249 return CR_Error;
1250 }
1251
1252 S.MarkDeclarationReferenced(loc, var);
1253
1254 // The BlocksAttr indicates the variable is bound by-reference.
1255 bool byRef = var->hasAttr<BlocksAttr>();
1256
1257 // Build a copy expression.
1258 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001259 const RecordType *rtype;
1260 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1261 (rtype = type->getAs<RecordType>())) {
1262
1263 // The capture logic needs the destructor, so make sure we mark it.
1264 // Usually this is unnecessary because most local variables have
1265 // their destructors marked at declaration time, but parameters are
1266 // an exception because it's technically only the call site that
1267 // actually requires the destructor.
1268 if (isa<ParmVarDecl>(var))
1269 S.FinalizeVarWithDestructor(var, rtype);
1270
John McCall351762c2011-02-07 10:33:21 +00001271 // According to the blocks spec, the capture of a variable from
1272 // the stack requires a const copy constructor. This is not true
1273 // of the copy/move done to move a __block variable to the heap.
1274 type.addConst();
1275
1276 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1277 ExprResult result =
1278 S.PerformCopyInitialization(
1279 InitializedEntity::InitializeBlock(var->getLocation(),
1280 type, false),
1281 loc, S.Owned(declRef));
1282
1283 // Build a full-expression copy expression if initialization
1284 // succeeded and used a non-trivial constructor. Recover from
1285 // errors by pretending that the copy isn't necessary.
1286 if (!result.isInvalid() &&
1287 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1288 result = S.MaybeCreateExprWithCleanups(result);
1289 copyExpr = result.take();
1290 }
1291 }
1292
1293 // We're currently at the declarer; go back to the closure.
1294 functionScopesIndex++;
1295 BlockScopeInfo *blockScope =
1296 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1297
1298 // Build a valid capture in this scope.
1299 blockScope->Captures.push_back(
1300 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1301 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1302
1303 // Propagate that to inner captures if necessary.
1304 return propagateCapture(S, functionScopesIndex,
1305 blockScope->Captures.back());
1306}
1307
Richard Trieuba63ce62011-09-09 01:45:06 +00001308static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001309 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001310 bool ByRef) {
1311 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001312
Richard Trieuba63ce62011-09-09 01:45:06 +00001313 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001314 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001315 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001316
1317 QualType exprType = var->getType().getNonReferenceType();
1318
1319 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001320 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001321 // The variable will be bound by copy; make it const within the
1322 // closure, but record that this was done in the expression.
1323 bool constAdded = !exprType.isConstQualified();
1324 exprType.addConst();
1325
1326 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1327 NameInfo.getLoc(), false,
1328 constAdded);
1329 } else {
1330 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1331 NameInfo.getLoc(), true);
1332 }
1333
1334 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001335}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001336
John McCalldadc5752010-08-24 06:29:42 +00001337ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001338Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001339 SourceLocation Loc,
1340 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001341 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001342 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001343}
1344
John McCallf4cd4f92011-02-09 01:13:10 +00001345/// BuildDeclRefExpr - Build an expression that references a
1346/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001347ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001348Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001349 const DeclarationNameInfo &NameInfo,
1350 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001351 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCall086a4642010-11-24 05:12:34 +00001353 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001354 SS? SS->getWithLocInContext(Context)
1355 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001356 D, NameInfo, Ty, VK);
1357
1358 // Just in case we're building an illegal pointer-to-member.
1359 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1360 E->setObjectKind(OK_BitField);
1361
1362 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001363}
1364
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001365/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001366/// possibly a list of template arguments.
1367///
1368/// If this produces template arguments, it is permitted to call
1369/// DecomposeTemplateName.
1370///
1371/// This actually loses a lot of source location information for
1372/// non-standard name kinds; we should consider preserving that in
1373/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001374void
1375Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1376 TemplateArgumentListInfo &Buffer,
1377 DeclarationNameInfo &NameInfo,
1378 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001379 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1380 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1381 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1382
Douglas Gregor5476205b2011-06-23 00:49:38 +00001383 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001384 Id.TemplateId->getTemplateArgs(),
1385 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001386 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001387 TemplateArgsPtr.release();
1388
John McCall3e56fd42010-08-23 07:28:44 +00001389 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001390 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001391 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001392 TemplateArgs = &Buffer;
1393 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001394 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001395 TemplateArgs = 0;
1396 }
1397}
1398
John McCalld681c392009-12-16 08:11:27 +00001399/// Diagnose an empty lookup.
1400///
1401/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001403 CorrectTypoContext CTC,
1404 TemplateArgumentListInfo *ExplicitTemplateArgs,
1405 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001406 DeclarationName Name = R.getLookupName();
1407
John McCalld681c392009-12-16 08:11:27 +00001408 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001409 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001410 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1411 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001412 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001413 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001414 diagnostic_suggest = diag::err_undeclared_use_suggest;
1415 }
John McCalld681c392009-12-16 08:11:27 +00001416
Douglas Gregor598b08f2009-12-31 05:20:13 +00001417 // If the original lookup was an unqualified lookup, fake an
1418 // unqualified lookup. This is useful when (for example) the
1419 // original lookup would not have found something because it was a
1420 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001421 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001422 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001423 if (isa<CXXRecordDecl>(DC)) {
1424 LookupQualifiedName(R, DC);
1425
1426 if (!R.empty()) {
1427 // Don't give errors about ambiguities in this lookup.
1428 R.suppressDiagnostics();
1429
1430 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1431 bool isInstance = CurMethod &&
1432 CurMethod->isInstance() &&
1433 DC == CurMethod->getParent();
1434
1435 // Give a code modification hint to insert 'this->'.
1436 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1437 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001438 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001439 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1440 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001441 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001442 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001443 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001444 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001445 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001446 Diag(R.getNameLoc(), diagnostic) << Name
1447 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1448 QualType DepThisType = DepMethod->getThisType(Context);
1449 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1450 R.getNameLoc(), DepThisType, false);
1451 TemplateArgumentListInfo TList;
1452 if (ULE->hasExplicitTemplateArgs())
1453 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001454
Douglas Gregore16af532011-02-28 18:50:33 +00001455 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001456 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001457 CXXDependentScopeMemberExpr *DepExpr =
1458 CXXDependentScopeMemberExpr::Create(
1459 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001460 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001461 R.getLookupNameInfo(),
1462 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001463 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001464 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001465 // FIXME: we should be able to handle this case too. It is correct
1466 // to add this-> here. This is a workaround for PR7947.
1467 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001468 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001469 } else {
John McCalld681c392009-12-16 08:11:27 +00001470 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001471 }
John McCalld681c392009-12-16 08:11:27 +00001472
1473 // Do we really want to note all of these?
1474 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1475 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1476
1477 // Tell the callee to try to recover.
1478 return false;
1479 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001480
1481 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001482 }
1483 }
1484
Douglas Gregor598b08f2009-12-31 05:20:13 +00001485 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001486 TypoCorrection Corrected;
1487 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1488 S, &SS, NULL, false, CTC))) {
1489 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1490 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1491 R.setLookupName(Corrected.getCorrection());
1492
Hans Wennborg38198de2011-07-12 08:45:31 +00001493 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001494 if (Corrected.isOverloaded()) {
1495 OverloadCandidateSet OCS(R.getNameLoc());
1496 OverloadCandidateSet::iterator Best;
1497 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1498 CDEnd = Corrected.end();
1499 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001500 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001501 dyn_cast<FunctionTemplateDecl>(*CD))
1502 AddTemplateOverloadCandidate(
1503 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1504 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001505 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1506 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1507 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1508 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001509 }
1510 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1511 case OR_Success:
1512 ND = Best->Function;
1513 break;
1514 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001515 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001516 }
1517 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001518 R.addDecl(ND);
1519 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001520 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001521 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1522 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001523 else
1524 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001525 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001526 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001527 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1528 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001529 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001530 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001531
1532 // Tell the callee to try to recover.
1533 return false;
1534 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001535
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001536 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001537 // FIXME: If we ended up with a typo for a type name or
1538 // Objective-C class name, we're in trouble because the parser
1539 // is in the wrong place to recover. Suggest the typo
1540 // correction, but don't make it a fix-it since we're not going
1541 // to recover well anyway.
1542 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001543 Diag(R.getNameLoc(), diagnostic_suggest)
1544 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001545 else
1546 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001547 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001548 << SS.getRange();
1549
1550 // Don't try to recover; it won't work.
1551 return true;
1552 }
1553 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001554 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001555 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001556 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001557 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001558 else
Douglas Gregor25363982010-01-01 00:15:04 +00001559 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001560 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001561 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001562 return true;
1563 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001564 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001565 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001566
1567 // Emit a special diagnostic for failed member lookups.
1568 // FIXME: computing the declaration context might fail here (?)
1569 if (!SS.isEmpty()) {
1570 Diag(R.getNameLoc(), diag::err_no_member)
1571 << Name << computeDeclContext(SS, false)
1572 << SS.getRange();
1573 return true;
1574 }
1575
John McCalld681c392009-12-16 08:11:27 +00001576 // Give up, we can't recover.
1577 Diag(R.getNameLoc(), diagnostic) << Name;
1578 return true;
1579}
1580
John McCalldadc5752010-08-24 06:29:42 +00001581ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001582 CXXScopeSpec &SS,
1583 UnqualifiedId &Id,
1584 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001585 bool IsAddressOfOperand) {
1586 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001587 "cannot be direct & operand and have a trailing lparen");
1588
1589 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001590 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001591
John McCall10eae182009-11-30 22:42:35 +00001592 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001593
1594 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001595 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001596 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001597 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001598
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001599 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001600 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001601 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001602
John McCalle66edc12009-11-24 19:00:30 +00001603 // C++ [temp.dep.expr]p3:
1604 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001605 // -- an identifier that was declared with a dependent type,
1606 // (note: handled after lookup)
1607 // -- a template-id that is dependent,
1608 // (note: handled in BuildTemplateIdExpr)
1609 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001610 // -- a nested-name-specifier that contains a class-name that
1611 // names a dependent type.
1612 // Determine whether this is a member of an unknown specialization;
1613 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001614 bool DependentID = false;
1615 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1616 Name.getCXXNameType()->isDependentType()) {
1617 DependentID = true;
1618 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001619 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001620 if (RequireCompleteDeclContext(SS, DC))
1621 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001622 } else {
1623 DependentID = true;
1624 }
1625 }
1626
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001627 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001628 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001629 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001630
Fariborz Jahanian86151342010-07-22 23:33:21 +00001631 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001632 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001633 LookupResult R(*this, NameInfo,
1634 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1635 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001636 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001637 // Lookup the template name again to correctly establish the context in
1638 // which it was found. This is really unfortunate as we already did the
1639 // lookup to determine that it was a template name in the first place. If
1640 // this becomes a performance hit, we can work harder to preserve those
1641 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001642 bool MemberOfUnknownSpecialization;
1643 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1644 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001645
1646 if (MemberOfUnknownSpecialization ||
1647 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001648 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001649 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001650 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001651 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001652 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001653
Douglas Gregora5226932011-02-04 13:35:07 +00001654 // If the result might be in a dependent base class, this is a dependent
1655 // id-expression.
1656 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001657 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001658 TemplateArgs);
1659
John McCalle66edc12009-11-24 19:00:30 +00001660 // If this reference is in an Objective-C method, then we need to do
1661 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001662 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001663 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001664 if (E.isInvalid())
1665 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001666
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001667 if (Expr *Ex = E.takeAs<Expr>())
1668 return Owned(Ex);
1669
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001670 // for further use, this must be set to false if in class method.
1671 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001672 }
Chris Lattner59a25942008-03-31 00:36:02 +00001673 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001674
John McCalle66edc12009-11-24 19:00:30 +00001675 if (R.isAmbiguous())
1676 return ExprError();
1677
Douglas Gregor171c45a2009-02-18 21:56:37 +00001678 // Determine whether this name might be a candidate for
1679 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001680 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001681
John McCalle66edc12009-11-24 19:00:30 +00001682 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001683 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001684 // in C90, extension in C99, forbidden in C++).
1685 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1686 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1687 if (D) R.addDecl(D);
1688 }
1689
1690 // If this name wasn't predeclared and if this is not a function
1691 // call, diagnose the problem.
1692 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001693 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001694 return ExprError();
1695
1696 assert(!R.empty() &&
1697 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001698
1699 // If we found an Objective-C instance variable, let
1700 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001701 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001702 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1703 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001704 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001705 // In a hopelessly buggy code, Objective-C instance variable
1706 // lookup fails and no expression will be built to reference it.
1707 if (!E.isInvalid() && !E.get())
1708 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001709 return move(E);
1710 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001711 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
John McCalle66edc12009-11-24 19:00:30 +00001714 // This is guaranteed from this point on.
1715 assert(!R.empty() || ADL);
1716
John McCall2d74de92009-12-01 22:10:20 +00001717 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001718 // C++ [class.mfct.non-static]p3:
1719 // When an id-expression that is not part of a class member access
1720 // syntax and not used to form a pointer to member is used in the
1721 // body of a non-static member function of class X, if name lookup
1722 // resolves the name in the id-expression to a non-static non-type
1723 // member of some class C, the id-expression is transformed into a
1724 // class member access expression using (*this) as the
1725 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001726 //
1727 // But we don't actually need to do this for '&' operands if R
1728 // resolved to a function or overloaded function set, because the
1729 // expression is ill-formed if it actually works out to be a
1730 // non-static member function:
1731 //
1732 // C++ [expr.ref]p4:
1733 // Otherwise, if E1.E2 refers to a non-static member function. . .
1734 // [t]he expression can be used only as the left-hand operand of a
1735 // member function call.
1736 //
1737 // There are other safeguards against such uses, but it's important
1738 // to get this right here so that we don't end up making a
1739 // spuriously dependent expression if we're inside a dependent
1740 // instance method.
John McCall57500772009-12-16 12:17:52 +00001741 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001742 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001743 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001744 MightBeImplicitMember = true;
1745 else if (!SS.isEmpty())
1746 MightBeImplicitMember = false;
1747 else if (R.isOverloadedResult())
1748 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001749 else if (R.isUnresolvableResult())
1750 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001751 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001752 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1753 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001754
1755 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001756 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001757 }
1758
John McCalle66edc12009-11-24 19:00:30 +00001759 if (TemplateArgs)
1760 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001761
John McCalle66edc12009-11-24 19:00:30 +00001762 return BuildDeclarationNameExpr(SS, R, ADL);
1763}
1764
John McCall10eae182009-11-30 22:42:35 +00001765/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1766/// declaration name, generally during template instantiation.
1767/// There's a large number of things which don't need to be done along
1768/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001769ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001770Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001771 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001772 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001773 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001774 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001775
John McCall0b66eb32010-05-01 00:40:08 +00001776 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001777 return ExprError();
1778
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001779 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001780 LookupQualifiedName(R, DC);
1781
1782 if (R.isAmbiguous())
1783 return ExprError();
1784
1785 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001786 Diag(NameInfo.getLoc(), diag::err_no_member)
1787 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001788 return ExprError();
1789 }
1790
1791 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1792}
1793
1794/// LookupInObjCMethod - The parser has read a name in, and Sema has
1795/// detected that we're currently inside an ObjC method. Perform some
1796/// additional lookup.
1797///
1798/// Ideally, most of this would be done by lookup, but there's
1799/// actually quite a lot of extra work involved.
1800///
1801/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001802ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001803Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001804 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001805 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001806 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001807
John McCalle66edc12009-11-24 19:00:30 +00001808 // There are two cases to handle here. 1) scoped lookup could have failed,
1809 // in which case we should look for an ivar. 2) scoped lookup could have
1810 // found a decl, but that decl is outside the current instance method (i.e.
1811 // a global variable). In these two cases, we do a lookup for an ivar with
1812 // this name, if the lookup sucedes, we replace it our current decl.
1813
1814 // If we're in a class method, we don't normally want to look for
1815 // ivars. But if we don't find anything else, and there's an
1816 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001817 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001818
1819 bool LookForIvars;
1820 if (Lookup.empty())
1821 LookForIvars = true;
1822 else if (IsClassMethod)
1823 LookForIvars = false;
1824 else
1825 LookForIvars = (Lookup.isSingleResult() &&
1826 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001827 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001828 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001829 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001830 ObjCInterfaceDecl *ClassDeclared;
1831 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1832 // Diagnose using an ivar in a class method.
1833 if (IsClassMethod)
1834 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1835 << IV->getDeclName());
1836
1837 // If we're referencing an invalid decl, just return this as a silent
1838 // error node. The error diagnostic was already emitted on the decl.
1839 if (IV->isInvalidDecl())
1840 return ExprError();
1841
1842 // Check if referencing a field with __attribute__((deprecated)).
1843 if (DiagnoseUseOfDecl(IV, Loc))
1844 return ExprError();
1845
1846 // Diagnose the use of an ivar outside of the declaring class.
1847 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1848 ClassDeclared != IFace)
1849 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1850
1851 // FIXME: This should use a new expr for a direct reference, don't
1852 // turn this into Self->ivar, just return a BareIVarExpr or something.
1853 IdentifierInfo &II = Context.Idents.get("self");
1854 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001855 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001856 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001857 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001858 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001859 SelfName, false, false);
1860 if (SelfExpr.isInvalid())
1861 return ExprError();
1862
John Wiegley01296292011-04-08 18:41:53 +00001863 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1864 if (SelfExpr.isInvalid())
1865 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001866
John McCalle66edc12009-11-24 19:00:30 +00001867 MarkDeclarationReferenced(Loc, IV);
1868 return Owned(new (Context)
1869 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001870 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001871 }
Chris Lattner87313662010-04-12 05:10:17 +00001872 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001873 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001874 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001875 ObjCInterfaceDecl *ClassDeclared;
1876 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1877 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1878 IFace == ClassDeclared)
1879 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1880 }
1881 }
1882
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001883 if (Lookup.empty() && II && AllowBuiltinCreation) {
1884 // FIXME. Consolidate this with similar code in LookupName.
1885 if (unsigned BuiltinID = II->getBuiltinID()) {
1886 if (!(getLangOptions().CPlusPlus &&
1887 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1888 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1889 S, Lookup.isForRedeclaration(),
1890 Lookup.getNameLoc());
1891 if (D) Lookup.addDecl(D);
1892 }
1893 }
1894 }
John McCalle66edc12009-11-24 19:00:30 +00001895 // Sentinel value saying that we didn't do anything special.
1896 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001897}
John McCalld14a8642009-11-21 08:51:07 +00001898
John McCall16df1e52010-03-30 21:47:33 +00001899/// \brief Cast a base object to a member's actual type.
1900///
1901/// Logically this happens in three phases:
1902///
1903/// * First we cast from the base type to the naming class.
1904/// The naming class is the class into which we were looking
1905/// when we found the member; it's the qualifier type if a
1906/// qualifier was provided, and otherwise it's the base type.
1907///
1908/// * Next we cast from the naming class to the declaring class.
1909/// If the member we found was brought into a class's scope by
1910/// a using declaration, this is that class; otherwise it's
1911/// the class declaring the member.
1912///
1913/// * Finally we cast from the declaring class to the "true"
1914/// declaring class of the member. This conversion does not
1915/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001916ExprResult
1917Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001918 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001919 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001920 NamedDecl *Member) {
1921 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1922 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001923 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001924
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 QualType DestRecordType;
1926 QualType DestType;
1927 QualType FromRecordType;
1928 QualType FromType = From->getType();
1929 bool PointerConversions = false;
1930 if (isa<FieldDecl>(Member)) {
1931 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001932
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001933 if (FromType->getAs<PointerType>()) {
1934 DestType = Context.getPointerType(DestRecordType);
1935 FromRecordType = FromType->getPointeeType();
1936 PointerConversions = true;
1937 } else {
1938 DestType = DestRecordType;
1939 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001940 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1942 if (Method->isStatic())
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 DestType = Method->getThisType(Context);
1946 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001947
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001948 if (FromType->getAs<PointerType>()) {
1949 FromRecordType = FromType->getPointeeType();
1950 PointerConversions = true;
1951 } else {
1952 FromRecordType = FromType;
1953 DestType = DestRecordType;
1954 }
1955 } else {
1956 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001957 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001958 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001959
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001961 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 // If the unqualified types are the same, no conversion is necessary.
1964 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001965 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001966
John McCall16df1e52010-03-30 21:47:33 +00001967 SourceRange FromRange = From->getSourceRange();
1968 SourceLocation FromLoc = FromRange.getBegin();
1969
John McCall2536c6d2010-08-25 10:28:54 +00001970 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001971
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 // class name.
1975 //
1976 // If the member was a qualified name and the qualified referred to a
1977 // specific base subobject type, we'll cast to that intermediate type
1978 // first and then to the object in which the member is declared. That allows
1979 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1980 //
1981 // class Base { public: int x; };
1982 // class Derived1 : public Base { };
1983 // class Derived2 : public Base { };
1984 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1985 //
1986 // void VeryDerived::f() {
1987 // x = 17; // error: ambiguous base subobjects
1988 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1989 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001991 QualType QType = QualType(Qualifier->getAsType(), 0);
1992 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1993 assert(QType->isRecordType() && "lookup done with non-record type");
1994
1995 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1996
1997 // In C++98, the qualifier type doesn't actually have to be a base
1998 // type of the object type, in which case we just ignore it.
1999 // Otherwise build the appropriate casts.
2000 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002001 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002002 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002003 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002004 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002005
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002006 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002007 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002008 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2009 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002010
2011 FromType = QType;
2012 FromRecordType = QRecordType;
2013
2014 // If the qualifier type was the same as the destination type,
2015 // we're done.
2016 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002017 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002018 }
2019 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002020
John McCall16df1e52010-03-30 21:47:33 +00002021 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022
John McCall16df1e52010-03-30 21:47:33 +00002023 // If we actually found the member through a using declaration, cast
2024 // down to the using declaration's type.
2025 //
2026 // Pointer equality is fine here because only one declaration of a
2027 // class ever has member declarations.
2028 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2029 assert(isa<UsingShadowDecl>(FoundDecl));
2030 QualType URecordType = Context.getTypeDeclType(
2031 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2032
2033 // We only need to do this if the naming-class to declaring-class
2034 // conversion is non-trivial.
2035 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2036 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002037 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002038 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002039 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002040 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002041
John McCall16df1e52010-03-30 21:47:33 +00002042 QualType UType = URecordType;
2043 if (PointerConversions)
2044 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002045 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2046 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002047 FromType = UType;
2048 FromRecordType = URecordType;
2049 }
2050
2051 // We don't do access control for the conversion from the
2052 // declaring class to the true declaring class.
2053 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002054 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002055
John McCallcf142162010-08-07 06:22:56 +00002056 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002057 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2058 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002059 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002060 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002061
John Wiegley01296292011-04-08 18:41:53 +00002062 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2063 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002064}
Douglas Gregor3256d042009-06-30 15:47:41 +00002065
John McCalle66edc12009-11-24 19:00:30 +00002066bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002067 const LookupResult &R,
2068 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002069 // Only when used directly as the postfix-expression of a call.
2070 if (!HasTrailingLParen)
2071 return false;
2072
2073 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002074 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002075 return false;
2076
2077 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002078 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002079 return false;
2080
2081 // Turn off ADL when we find certain kinds of declarations during
2082 // normal lookup:
2083 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2084 NamedDecl *D = *I;
2085
2086 // C++0x [basic.lookup.argdep]p3:
2087 // -- a declaration of a class member
2088 // Since using decls preserve this property, we check this on the
2089 // original decl.
John McCall57500772009-12-16 12:17:52 +00002090 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002091 return false;
2092
2093 // C++0x [basic.lookup.argdep]p3:
2094 // -- a block-scope function declaration that is not a
2095 // using-declaration
2096 // NOTE: we also trigger this for function templates (in fact, we
2097 // don't check the decl type at all, since all other decl types
2098 // turn off ADL anyway).
2099 if (isa<UsingShadowDecl>(D))
2100 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2101 else if (D->getDeclContext()->isFunctionOrMethod())
2102 return false;
2103
2104 // C++0x [basic.lookup.argdep]p3:
2105 // -- a declaration that is neither a function or a function
2106 // template
2107 // And also for builtin functions.
2108 if (isa<FunctionDecl>(D)) {
2109 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2110
2111 // But also builtin functions.
2112 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2113 return false;
2114 } else if (!isa<FunctionTemplateDecl>(D))
2115 return false;
2116 }
2117
2118 return true;
2119}
2120
2121
John McCalld14a8642009-11-21 08:51:07 +00002122/// Diagnoses obvious problems with the use of the given declaration
2123/// as an expression. This is only actually called for lookups that
2124/// were not overloaded, and it doesn't promise that the declaration
2125/// will in fact be used.
2126static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002127 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002128 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2129 return true;
2130 }
2131
2132 if (isa<ObjCInterfaceDecl>(D)) {
2133 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2134 return true;
2135 }
2136
2137 if (isa<NamespaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2139 return true;
2140 }
2141
2142 return false;
2143}
2144
John McCalldadc5752010-08-24 06:29:42 +00002145ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002146Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002147 LookupResult &R,
2148 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002149 // If this is a single, fully-resolved result and we don't need ADL,
2150 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002151 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002152 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2153 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002154
2155 // We only need to check the declaration if there's exactly one
2156 // result, because in the overloaded case the results can only be
2157 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002158 if (R.isSingleResult() &&
2159 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002160 return ExprError();
2161
John McCall58cc69d2010-01-27 01:50:18 +00002162 // Otherwise, just build an unresolved lookup expression. Suppress
2163 // any lookup-related diagnostics; we'll hash these out later, when
2164 // we've picked a target.
2165 R.suppressDiagnostics();
2166
John McCalld14a8642009-11-21 08:51:07 +00002167 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002168 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002169 SS.getWithLocInContext(Context),
2170 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002171 NeedsADL, R.isOverloadedResult(),
2172 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002173
2174 return Owned(ULE);
2175}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002176
John McCalld14a8642009-11-21 08:51:07 +00002177/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002178ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002179Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002180 const DeclarationNameInfo &NameInfo,
2181 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002182 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002183 assert(!isa<FunctionTemplateDecl>(D) &&
2184 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002185
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002186 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002187 if (CheckDeclInExpr(*this, Loc, D))
2188 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002189
Douglas Gregore7488b92009-12-01 16:58:18 +00002190 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2191 // Specifically diagnose references to class templates that are missing
2192 // a template argument list.
2193 Diag(Loc, diag::err_template_decl_ref)
2194 << Template << SS.getRange();
2195 Diag(Template->getLocation(), diag::note_template_decl_here);
2196 return ExprError();
2197 }
2198
2199 // Make sure that we're referring to a value.
2200 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2201 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002202 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002203 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002204 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002205 return ExprError();
2206 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002207
Douglas Gregor171c45a2009-02-18 21:56:37 +00002208 // Check whether this declaration can be used. Note that we suppress
2209 // this check when we're going to perform argument-dependent lookup
2210 // on this function name, because this might not be the function
2211 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002212 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002213 return ExprError();
2214
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002215 // Only create DeclRefExpr's for valid Decl's.
2216 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002217 return ExprError();
2218
John McCallf3a88602011-02-03 08:15:49 +00002219 // Handle members of anonymous structs and unions. If we got here,
2220 // and the reference is to a class member indirect field, then this
2221 // must be the subject of a pointer-to-member expression.
2222 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2223 if (!indirectField->isCXXClassMember())
2224 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2225 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002226
Chris Lattner2a9d9892008-10-20 05:16:36 +00002227 // If the identifier reference is inside a block, and it refers to a value
2228 // that is outside the block, create a BlockDeclRefExpr instead of a
2229 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2230 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002231 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002232 // We do not do this for things like enum constants, global variables, etc,
2233 // as they do not get snapshotted.
2234 //
John McCall351762c2011-02-07 10:33:21 +00002235 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002236 case CR_Error:
2237 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002238
John McCallc63de662011-02-02 13:00:07 +00002239 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002240 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2241 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2242
2243 case CR_CaptureByRef:
2244 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2245 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002246
2247 case CR_NoCapture: {
2248 // If this reference is not in a block or if the referenced
2249 // variable is within the block, create a normal DeclRefExpr.
2250
2251 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002252 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002253
2254 switch (D->getKind()) {
2255 // Ignore all the non-ValueDecl kinds.
2256#define ABSTRACT_DECL(kind)
2257#define VALUE(type, base)
2258#define DECL(type, base) \
2259 case Decl::type:
2260#include "clang/AST/DeclNodes.inc"
2261 llvm_unreachable("invalid value decl kind");
2262 return ExprError();
2263
2264 // These shouldn't make it here.
2265 case Decl::ObjCAtDefsField:
2266 case Decl::ObjCIvar:
2267 llvm_unreachable("forming non-member reference to ivar?");
2268 return ExprError();
2269
2270 // Enum constants are always r-values and never references.
2271 // Unresolved using declarations are dependent.
2272 case Decl::EnumConstant:
2273 case Decl::UnresolvedUsingValue:
2274 valueKind = VK_RValue;
2275 break;
2276
2277 // Fields and indirect fields that got here must be for
2278 // pointer-to-member expressions; we just call them l-values for
2279 // internal consistency, because this subexpression doesn't really
2280 // exist in the high-level semantics.
2281 case Decl::Field:
2282 case Decl::IndirectField:
2283 assert(getLangOptions().CPlusPlus &&
2284 "building reference to field in C?");
2285
2286 // These can't have reference type in well-formed programs, but
2287 // for internal consistency we do this anyway.
2288 type = type.getNonReferenceType();
2289 valueKind = VK_LValue;
2290 break;
2291
2292 // Non-type template parameters are either l-values or r-values
2293 // depending on the type.
2294 case Decl::NonTypeTemplateParm: {
2295 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2296 type = reftype->getPointeeType();
2297 valueKind = VK_LValue; // even if the parameter is an r-value reference
2298 break;
2299 }
2300
2301 // For non-references, we need to strip qualifiers just in case
2302 // the template parameter was declared as 'const int' or whatever.
2303 valueKind = VK_RValue;
2304 type = type.getUnqualifiedType();
2305 break;
2306 }
2307
2308 case Decl::Var:
2309 // In C, "extern void blah;" is valid and is an r-value.
2310 if (!getLangOptions().CPlusPlus &&
2311 !type.hasQualifiers() &&
2312 type->isVoidType()) {
2313 valueKind = VK_RValue;
2314 break;
2315 }
2316 // fallthrough
2317
2318 case Decl::ImplicitParam:
2319 case Decl::ParmVar:
2320 // These are always l-values.
2321 valueKind = VK_LValue;
2322 type = type.getNonReferenceType();
2323 break;
2324
2325 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002326 const FunctionType *fty = type->castAs<FunctionType>();
2327
2328 // If we're referring to a function with an __unknown_anytype
2329 // result type, make the entire expression __unknown_anytype.
2330 if (fty->getResultType() == Context.UnknownAnyTy) {
2331 type = Context.UnknownAnyTy;
2332 valueKind = VK_RValue;
2333 break;
2334 }
2335
John McCallf4cd4f92011-02-09 01:13:10 +00002336 // Functions are l-values in C++.
2337 if (getLangOptions().CPlusPlus) {
2338 valueKind = VK_LValue;
2339 break;
2340 }
2341
2342 // C99 DR 316 says that, if a function type comes from a
2343 // function definition (without a prototype), that type is only
2344 // used for checking compatibility. Therefore, when referencing
2345 // the function, we pretend that we don't have the full function
2346 // type.
John McCall2979fe02011-04-12 00:42:48 +00002347 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2348 isa<FunctionProtoType>(fty))
2349 type = Context.getFunctionNoProtoType(fty->getResultType(),
2350 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002351
2352 // Functions are r-values in C.
2353 valueKind = VK_RValue;
2354 break;
2355 }
2356
2357 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002358 // If we're referring to a method with an __unknown_anytype
2359 // result type, make the entire expression __unknown_anytype.
2360 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002361 if (const FunctionProtoType *proto
2362 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002363 if (proto->getResultType() == Context.UnknownAnyTy) {
2364 type = Context.UnknownAnyTy;
2365 valueKind = VK_RValue;
2366 break;
2367 }
2368
John McCallf4cd4f92011-02-09 01:13:10 +00002369 // C++ methods are l-values if static, r-values if non-static.
2370 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2371 valueKind = VK_LValue;
2372 break;
2373 }
2374 // fallthrough
2375
2376 case Decl::CXXConversion:
2377 case Decl::CXXDestructor:
2378 case Decl::CXXConstructor:
2379 valueKind = VK_RValue;
2380 break;
2381 }
2382
2383 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2384 }
2385
John McCallc63de662011-02-02 13:00:07 +00002386 }
John McCall7decc9e2010-11-18 06:31:45 +00002387
John McCall351762c2011-02-07 10:33:21 +00002388 llvm_unreachable("unknown capture result");
2389 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002390}
Chris Lattnere168f762006-11-10 05:29:30 +00002391
John McCall2979fe02011-04-12 00:42:48 +00002392ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002393 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002394
Chris Lattnere168f762006-11-10 05:29:30 +00002395 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002396 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002397 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2398 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2399 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002400 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002401
Chris Lattnera81a0272008-01-12 08:14:25 +00002402 // Pre-defined identifiers are of type char[x], where x is the length of the
2403 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002404
Anders Carlsson2fb08242009-09-08 18:24:21 +00002405 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002406 if (!currentDecl && getCurBlock())
2407 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002408 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002409 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002410 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002411 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002412
Anders Carlsson0b209a82009-09-11 01:22:35 +00002413 QualType ResTy;
2414 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2415 ResTy = Context.DependentTy;
2416 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002417 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002418
Anders Carlsson0b209a82009-09-11 01:22:35 +00002419 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002420 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002421 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2422 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002423 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002424}
2425
John McCalldadc5752010-08-24 06:29:42 +00002426ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002427 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002428 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002429 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002430 if (Invalid)
2431 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002432
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002433 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002434 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002435 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002436 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002437
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002438 QualType Ty;
2439 if (!getLangOptions().CPlusPlus)
2440 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2441 else if (Literal.isWide())
2442 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002443 else if (Literal.isUTF16())
2444 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2445 else if (Literal.isUTF32())
2446 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002447 else if (Literal.isMultiChar())
2448 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002449 else
2450 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002451
Douglas Gregorfb65e592011-07-27 05:40:30 +00002452 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2453 if (Literal.isWide())
2454 Kind = CharacterLiteral::Wide;
2455 else if (Literal.isUTF16())
2456 Kind = CharacterLiteral::UTF16;
2457 else if (Literal.isUTF32())
2458 Kind = CharacterLiteral::UTF32;
2459
2460 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2461 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002462}
2463
John McCalldadc5752010-08-24 06:29:42 +00002464ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002465 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002466 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2467 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002468 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002469 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002470 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002471 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002472 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002473
Chris Lattner23b7eb62007-06-15 23:05:46 +00002474 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002475 // Add padding so that NumericLiteralParser can overread by one character.
2476 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002477 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002478
Chris Lattner67ca9252007-05-21 01:08:44 +00002479 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002480 bool Invalid = false;
2481 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2482 if (Invalid)
2483 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002484
Mike Stump11289f42009-09-09 15:08:12 +00002485 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002486 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002487 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002488 return ExprError();
2489
Chris Lattner1c20a172007-08-26 03:42:43 +00002490 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002491
Chris Lattner1c20a172007-08-26 03:42:43 +00002492 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002493 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002494 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002495 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002496 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002497 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002498 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002499 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002500
2501 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2502
John McCall53b93a02009-12-24 09:08:04 +00002503 using llvm::APFloat;
2504 APFloat Val(Format);
2505
2506 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002507
2508 // Overflow is always an error, but underflow is only an error if
2509 // we underflowed to zero (APFloat reports denormals as underflow).
2510 if ((result & APFloat::opOverflow) ||
2511 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002512 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002513 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002514 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002515 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002516 APFloat::getLargest(Format).toString(buffer);
2517 } else {
John McCall62abc942010-02-26 23:35:57 +00002518 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002519 APFloat::getSmallest(Format).toString(buffer);
2520 }
2521
2522 Diag(Tok.getLocation(), diagnostic)
2523 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002524 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002525 }
2526
2527 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002528 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002530 if (Ty == Context.DoubleTy) {
2531 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002532 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002533 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2534 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002535 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002536 }
2537 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002538 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002539 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002540 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002541 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002542
Neil Boothac582c52007-08-29 22:00:19 +00002543 // long long is a C99 feature.
2544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002545 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002546 Diag(Tok.getLocation(), diag::ext_longlong);
2547
Chris Lattner67ca9252007-05-21 01:08:44 +00002548 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002549 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550
Chris Lattner67ca9252007-05-21 01:08:44 +00002551 if (Literal.GetIntegerValue(ResultVal)) {
2552 // If this value didn't fit into uintmax_t, warn and force to ull.
2553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002554 Ty = Context.UnsignedLongLongTy;
2555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002556 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002557 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002558 // If this value fits into a ULL, try to figure out what else it fits into
2559 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002560
Chris Lattner67ca9252007-05-21 01:08:44 +00002561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2562 // be an unsigned int.
2563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2564
2565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002566 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002567 if (!Literal.isLong && !Literal.isLongLong) {
2568 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002569 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Chris Lattner67ca9252007-05-21 01:08:44 +00002571 // Does it fit in a unsigned int?
2572 if (ResultVal.isIntN(IntSize)) {
2573 // Does it fit in a signed int?
2574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002575 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002576 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002577 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002578 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002579 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002580 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002583 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002584 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002585
Chris Lattner67ca9252007-05-21 01:08:44 +00002586 // Does it fit in a unsigned long?
2587 if (ResultVal.isIntN(LongSize)) {
2588 // Does it fit in a signed long?
2589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002590 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002591 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002592 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002593 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002594 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002595 }
2596
Chris Lattner67ca9252007-05-21 01:08:44 +00002597 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002598 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002599 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002600
Chris Lattner67ca9252007-05-21 01:08:44 +00002601 // Does it fit in a unsigned long long?
2602 if (ResultVal.isIntN(LongLongSize)) {
2603 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002604 // To be compatible with MSVC, hex integer literals ending with the
2605 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002606 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002607 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002608 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002609 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002610 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002611 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 }
2613 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002614
Chris Lattner67ca9252007-05-21 01:08:44 +00002615 // If we still couldn't decide a type, we probably have something that
2616 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002617 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002618 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002619 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002620 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622
Chris Lattner55258cf2008-05-09 05:59:00 +00002623 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002624 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002625 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002626 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002627 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002628
Chris Lattner1c20a172007-08-26 03:42:43 +00002629 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2630 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002631 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002632 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002633
2634 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002635}
2636
Richard Trieuba63ce62011-09-09 01:45:06 +00002637ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002638 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002639 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002640}
2641
Chandler Carruth62da79c2011-05-26 08:53:12 +00002642static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2643 SourceLocation Loc,
2644 SourceRange ArgRange) {
2645 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2646 // scalar or vector data type argument..."
2647 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2648 // type (C99 6.2.5p18) or void.
2649 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2650 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2651 << T << ArgRange;
2652 return true;
2653 }
2654
2655 assert((T->isVoidType() || !T->isIncompleteType()) &&
2656 "Scalar types should always be complete");
2657 return false;
2658}
2659
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002660static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2661 SourceLocation Loc,
2662 SourceRange ArgRange,
2663 UnaryExprOrTypeTrait TraitKind) {
2664 // C99 6.5.3.4p1:
2665 if (T->isFunctionType()) {
2666 // alignof(function) is allowed as an extension.
2667 if (TraitKind == UETT_SizeOf)
2668 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2669 return false;
2670 }
2671
2672 // Allow sizeof(void)/alignof(void) as an extension.
2673 if (T->isVoidType()) {
2674 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2675 return false;
2676 }
2677
2678 return true;
2679}
2680
2681static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2682 SourceLocation Loc,
2683 SourceRange ArgRange,
2684 UnaryExprOrTypeTrait TraitKind) {
2685 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2686 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2687 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2688 << T << (TraitKind == UETT_SizeOf)
2689 << ArgRange;
2690 return true;
2691 }
2692
2693 return false;
2694}
2695
Chandler Carruth14502c22011-05-26 08:53:10 +00002696/// \brief Check the constrains on expression operands to unary type expression
2697/// and type traits.
2698///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002699/// Completes any types necessary and validates the constraints on the operand
2700/// expression. The logic mostly mirrors the type-based overload, but may modify
2701/// the expression as it completes the type for that expression through template
2702/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002703bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002704 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002705 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002706
2707 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2708 // the result is the size of the referenced type."
2709 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2710 // result shall be the alignment of the referenced type."
2711 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2712 ExprTy = Ref->getPointeeType();
2713
2714 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002715 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2716 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002717
2718 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002719 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2720 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002721 return false;
2722
Richard Trieuba63ce62011-09-09 01:45:06 +00002723 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002724 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002725 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002726 std::make_pair(SourceLocation(), PDiag(0))))
2727 return true;
2728
2729 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002730 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002731 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2732 ExprTy = Ref->getPointeeType();
2733
Richard Trieuba63ce62011-09-09 01:45:06 +00002734 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2735 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002736 return true;
2737
Nico Weber0870deb2011-06-15 02:47:03 +00002738 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002739 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002740 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2741 QualType OType = PVD->getOriginalType();
2742 QualType Type = PVD->getType();
2743 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002744 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002745 << Type << OType;
2746 Diag(PVD->getLocation(), diag::note_declared_at);
2747 }
2748 }
2749 }
2750 }
2751
Chandler Carruth7c430c02011-05-27 01:33:31 +00002752 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002753}
2754
2755/// \brief Check the constraints on operands to unary expression and type
2756/// traits.
2757///
2758/// This will complete any types necessary, and validate the various constraints
2759/// on those operands.
2760///
Steve Naroff71b59a92007-06-04 22:22:31 +00002761/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002762/// C99 6.3.2.1p[2-4] all state:
2763/// Except when it is the operand of the sizeof operator ...
2764///
2765/// C++ [expr.sizeof]p4
2766/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2767/// standard conversions are not applied to the operand of sizeof.
2768///
2769/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002770bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002771 SourceLocation OpLoc,
2772 SourceRange ExprRange,
2773 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002774 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002775 return false;
2776
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002777 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2778 // the result is the size of the referenced type."
2779 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2780 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002781 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2782 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002783
Chandler Carruth62da79c2011-05-26 08:53:12 +00002784 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002785 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002786
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002787 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002788 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002789 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002790 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Richard Trieuba63ce62011-09-09 01:45:06 +00002792 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002793 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002794 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002795 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002796
Richard Trieuba63ce62011-09-09 01:45:06 +00002797 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002798 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002799 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002800
Chris Lattner62975a72009-04-24 00:30:45 +00002801 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002802}
2803
Chandler Carruth14502c22011-05-26 08:53:10 +00002804static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002805 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002806
Mike Stump11289f42009-09-09 15:08:12 +00002807 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002808 if (isa<DeclRefExpr>(E))
2809 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002810
2811 // Cannot know anything else if the expression is dependent.
2812 if (E->isTypeDependent())
2813 return false;
2814
Douglas Gregor71235ec2009-05-02 02:18:30 +00002815 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002816 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2817 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002818 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002819 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002820
2821 // Alignment of a field access is always okay, so long as it isn't a
2822 // bit-field.
2823 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002824 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002825 return false;
2826
Chandler Carruth14502c22011-05-26 08:53:10 +00002827 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002828}
2829
Chandler Carruth14502c22011-05-26 08:53:10 +00002830bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002831 E = E->IgnoreParens();
2832
2833 // Cannot know anything else if the expression is dependent.
2834 if (E->isTypeDependent())
2835 return false;
2836
Chandler Carruth14502c22011-05-26 08:53:10 +00002837 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002838}
2839
Douglas Gregor0950e412009-03-13 21:01:28 +00002840/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002841ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002842Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2843 SourceLocation OpLoc,
2844 UnaryExprOrTypeTrait ExprKind,
2845 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002846 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002847 return ExprError();
2848
John McCallbcd03502009-12-07 02:54:59 +00002849 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002850
Douglas Gregor0950e412009-03-13 21:01:28 +00002851 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002853 return ExprError();
2854
2855 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002856 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2857 Context.getSizeType(),
2858 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002859}
2860
2861/// \brief Build a sizeof or alignof expression given an expression
2862/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002863ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002864Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2865 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002866 ExprResult PE = CheckPlaceholderExpr(E);
2867 if (PE.isInvalid())
2868 return ExprError();
2869
2870 E = PE.get();
2871
Douglas Gregor0950e412009-03-13 21:01:28 +00002872 // Verify that the operand is valid.
2873 bool isInvalid = false;
2874 if (E->isTypeDependent()) {
2875 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002876 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002877 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002878 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002879 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002880 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002881 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002882 isInvalid = true;
2883 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002884 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002885 }
2886
2887 if (isInvalid)
2888 return ExprError();
2889
2890 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002891 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002892 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002893 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002894}
2895
Peter Collingbournee190dee2011-03-11 19:24:49 +00002896/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2897/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002898/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002899ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002900Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002901 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002903 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002904 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002905
Richard Trieuba63ce62011-09-09 01:45:06 +00002906 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002907 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002908 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002909 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002910 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002911
Douglas Gregor0950e412009-03-13 21:01:28 +00002912 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002913 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002914 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002915}
2916
John Wiegley01296292011-04-08 18:41:53 +00002917static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002918 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002919 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002920 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002921
John McCall34376a62010-12-04 03:47:34 +00002922 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002923 if (V.get()->getObjectKind() != OK_Ordinary) {
2924 V = S.DefaultLvalueConversion(V.take());
2925 if (V.isInvalid())
2926 return QualType();
2927 }
John McCall34376a62010-12-04 03:47:34 +00002928
Chris Lattnere267f5d2007-08-26 05:39:26 +00002929 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002930 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002931 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002932
Chris Lattnere267f5d2007-08-26 05:39:26 +00002933 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002934 if (V.get()->getType()->isArithmeticType())
2935 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002936
John McCall36226622010-10-12 02:09:17 +00002937 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002938 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002939 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002940 if (PR.get() != V.get()) {
2941 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002942 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002943 }
2944
Chris Lattnere267f5d2007-08-26 05:39:26 +00002945 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002946 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002948 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002949}
2950
2951
Chris Lattnere168f762006-11-10 05:29:30 +00002952
John McCalldadc5752010-08-24 06:29:42 +00002953ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002954Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002955 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002956 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002957 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002958 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002959 case tok::plusplus: Opc = UO_PostInc; break;
2960 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002961 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962
John McCallb268a282010-08-23 23:25:46 +00002963 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002964}
2965
John McCalldadc5752010-08-24 06:29:42 +00002966ExprResult
John McCallb268a282010-08-23 23:25:46 +00002967Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2968 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002969 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002970 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002971 if (Result.isInvalid()) return ExprError();
2972 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002973
John McCallb268a282010-08-23 23:25:46 +00002974 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002975
Douglas Gregor40412ac2008-11-19 17:17:41 +00002976 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002977 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002978 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002979 Context.DependentTy,
2980 VK_LValue, OK_Ordinary,
2981 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002982 }
2983
Mike Stump11289f42009-09-09 15:08:12 +00002984 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002985 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002986 LHSExp->getType()->isEnumeralType() ||
2987 RHSExp->getType()->isRecordType() ||
2988 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002989 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002990 }
2991
John McCallb268a282010-08-23 23:25:46 +00002992 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002993}
2994
2995
John McCalldadc5752010-08-24 06:29:42 +00002996ExprResult
John McCallb268a282010-08-23 23:25:46 +00002997Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002998 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00002999 Expr *LHSExp = Base;
3000 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003001
Chris Lattner36d572b2007-07-16 00:14:47 +00003002 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003003 if (!LHSExp->getType()->getAs<VectorType>()) {
3004 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3005 if (Result.isInvalid())
3006 return ExprError();
3007 LHSExp = Result.take();
3008 }
3009 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3010 if (Result.isInvalid())
3011 return ExprError();
3012 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003013
Chris Lattner36d572b2007-07-16 00:14:47 +00003014 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003015 ExprValueKind VK = VK_LValue;
3016 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003017
Steve Naroffc1aadb12007-03-28 21:49:40 +00003018 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003019 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003020 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003021 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003022 Expr *BaseExpr, *IndexExpr;
3023 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003024 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3025 BaseExpr = LHSExp;
3026 IndexExpr = RHSExp;
3027 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003028 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003029 BaseExpr = LHSExp;
3030 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003031 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003032 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003033 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003034 BaseExpr = RHSExp;
3035 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003036 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003037 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003038 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003039 BaseExpr = LHSExp;
3040 IndexExpr = RHSExp;
3041 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003042 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003043 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003044 // Handle the uncommon case of "123[Ptr]".
3045 BaseExpr = RHSExp;
3046 IndexExpr = LHSExp;
3047 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003048 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003049 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003050 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003051 VK = LHSExp->getValueKind();
3052 if (VK != VK_RValue)
3053 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003054
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 // FIXME: need to deal with const...
3056 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003057 } else if (LHSTy->isArrayType()) {
3058 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003059 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003060 // wasn't promoted because of the C90 rule that doesn't
3061 // allow promoting non-lvalue arrays. Warn, then
3062 // force the promotion here.
3063 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3064 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003065 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3066 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003067 LHSTy = LHSExp->getType();
3068
3069 BaseExpr = LHSExp;
3070 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003071 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003072 } else if (RHSTy->isArrayType()) {
3073 // Same as previous, except for 123[f().a] case
3074 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3075 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003076 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3077 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003078 RHSTy = RHSExp->getType();
3079
3080 BaseExpr = RHSExp;
3081 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003082 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003083 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003084 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3085 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003086 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003087 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003088 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003089 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3090 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003091
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003092 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003093 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3094 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003095 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3096
Douglas Gregorac1fb652009-03-24 19:52:54 +00003097 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003098 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3099 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003100 // incomplete types are not object types.
3101 if (ResultType->isFunctionType()) {
3102 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3103 << ResultType << BaseExpr->getSourceRange();
3104 return ExprError();
3105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003107 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3108 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003109 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3110 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003111
3112 // C forbids expressions of unqualified void type from being l-values.
3113 // See IsCForbiddenLValueType.
3114 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003115 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003116 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003117 PDiag(diag::err_subscript_incomplete_type)
3118 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003119 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003120
Chris Lattner62975a72009-04-24 00:30:45 +00003121 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003122 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003123 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3124 << ResultType << BaseExpr->getSourceRange();
3125 return ExprError();
3126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
John McCall4bc41ae2010-11-18 19:01:18 +00003128 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003129 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003130
Mike Stump4e1f26a2009-02-19 03:04:26 +00003131 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003132 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003133}
3134
John McCalldadc5752010-08-24 06:29:42 +00003135ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003136 FunctionDecl *FD,
3137 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003138 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003139 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003140 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003141 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003142 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003143 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003144 return ExprError();
3145 }
3146
3147 if (Param->hasUninstantiatedDefaultArg()) {
3148 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003149
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003150 // Instantiate the expression.
3151 MultiLevelTemplateArgumentList ArgList
3152 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003153
Nico Weber44887f62010-11-29 18:19:25 +00003154 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003155 = ArgList.getInnermost();
3156 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3157 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003158
Nico Weber44887f62010-11-29 18:19:25 +00003159 ExprResult Result;
3160 {
3161 // C++ [dcl.fct.default]p5:
3162 // The names in the [default argument] expression are bound, and
3163 // the semantic constraints are checked, at the point where the
3164 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003165 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003166 Result = SubstExpr(UninstExpr, ArgList);
3167 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003168 if (Result.isInvalid())
3169 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003171 // Check the expression as an initializer for the parameter.
3172 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003173 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003174 InitializationKind Kind
3175 = InitializationKind::CreateCopy(Param->getLocation(),
3176 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3177 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003178
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003179 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3180 Result = InitSeq.Perform(*this, Entity, Kind,
3181 MultiExprArg(*this, &ResultE, 1));
3182 if (Result.isInvalid())
3183 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003184
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003185 // Build the default argument expression.
3186 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3187 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003188 }
3189
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003190 // If the default expression creates temporaries, we need to
3191 // push them to the current stack of expression temporaries so they'll
3192 // be properly destroyed.
3193 // FIXME: We should really be rebuilding the default argument with new
3194 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003195 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3196 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3197 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3198 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3199 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003200 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003201 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003202
3203 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003204 // Just mark all of the declarations in this potentially-evaluated expression
3205 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003206 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003207 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003208}
3209
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003210/// ConvertArgumentsForCall - Converts the arguments specified in
3211/// Args/NumArgs to the parameter types of the function FDecl with
3212/// function prototype Proto. Call is the call expression itself, and
3213/// Fn is the function expression. For a C++ member function, this
3214/// routine does not attempt to convert the object argument. Returns
3215/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003216bool
3217Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003218 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003219 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003220 Expr **Args, unsigned NumArgs,
3221 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003222 // Bail out early if calling a builtin with custom typechecking.
3223 // We don't need to do this in the
3224 if (FDecl)
3225 if (unsigned ID = FDecl->getBuiltinID())
3226 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3227 return false;
3228
Mike Stump4e1f26a2009-02-19 03:04:26 +00003229 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003230 // assignment, to the types of the corresponding parameter, ...
3231 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003232 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003233
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003234 // If too few arguments are available (and we don't have default
3235 // arguments for the remaining parameters), don't make the call.
3236 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003237 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3238 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003239 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003240 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003241
3242 // Emit the location of the prototype.
3243 if (FDecl && !FDecl->getBuiltinID())
3244 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3245 << FDecl;
3246
3247 return true;
3248 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003249 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003250 }
3251
3252 // If too many are passed and not variadic, error on the extras and drop
3253 // them.
3254 if (NumArgs > NumArgsInProto) {
3255 if (!Proto->isVariadic()) {
3256 Diag(Args[NumArgsInProto]->getLocStart(),
3257 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003258 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003259 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003260 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3261 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003262
3263 // Emit the location of the prototype.
3264 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003265 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3266 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003267
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003268 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003269 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003270 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003271 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003272 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003273 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003274 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003275 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3276 if (Fn->getType()->isBlockPointerType())
3277 CallType = VariadicBlock; // Block
3278 else if (isa<MemberExpr>(Fn))
3279 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003280 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003281 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003282 if (Invalid)
3283 return true;
3284 unsigned TotalNumArgs = AllArgs.size();
3285 for (unsigned i = 0; i < TotalNumArgs; ++i)
3286 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003287
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003288 return false;
3289}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003290
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003291bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3292 FunctionDecl *FDecl,
3293 const FunctionProtoType *Proto,
3294 unsigned FirstProtoArg,
3295 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003296 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003297 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003298 unsigned NumArgsInProto = Proto->getNumArgs();
3299 unsigned NumArgsToCheck = NumArgs;
3300 bool Invalid = false;
3301 if (NumArgs != NumArgsInProto)
3302 // Use default arguments for missing arguments
3303 NumArgsToCheck = NumArgsInProto;
3304 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003305 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003306 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003307 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003308
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003309 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003310 if (ArgIx < NumArgs) {
3311 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003312
Eli Friedman3164fb12009-03-22 22:00:50 +00003313 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3314 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003315 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003316 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003317 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003318
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003319 // Pass the argument
3320 ParmVarDecl *Param = 0;
3321 if (FDecl && i < FDecl->getNumParams())
3322 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003323
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003324 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003325 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003326 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3327 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003328 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003329 SourceLocation(),
3330 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003331 if (ArgE.isInvalid())
3332 return true;
3333
3334 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003335 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003336 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003337
John McCalldadc5752010-08-24 06:29:42 +00003338 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003339 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003340 if (ArgExpr.isInvalid())
3341 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003342
Anders Carlsson355933d2009-08-25 03:49:14 +00003343 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003344 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003345
3346 // Check for array bounds violations for each argument to the call. This
3347 // check only triggers warnings when the argument isn't a more complex Expr
3348 // with its own checking, such as a BinaryOperator.
3349 CheckArrayAccess(Arg);
3350
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003351 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003352 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003353
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003354 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003355 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003356
3357 // Assume that extern "C" functions with variadic arguments that
3358 // return __unknown_anytype aren't *really* variadic.
3359 if (Proto->getResultType() == Context.UnknownAnyTy &&
3360 FDecl && FDecl->isExternC()) {
3361 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3362 ExprResult arg;
3363 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3364 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3365 else
3366 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3367 Invalid |= arg.isInvalid();
3368 AllArgs.push_back(arg.take());
3369 }
3370
3371 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3372 } else {
3373 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003374 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3375 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003376 Invalid |= Arg.isInvalid();
3377 AllArgs.push_back(Arg.take());
3378 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003379 }
3380 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003381 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003382}
3383
John McCall2979fe02011-04-12 00:42:48 +00003384/// Given a function expression of unknown-any type, try to rebuild it
3385/// to have a function type.
3386static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3387
Steve Naroff83895f72007-09-16 03:34:24 +00003388/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003389/// This provides the location of the left/right parens and a list of comma
3390/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003391ExprResult
John McCallb268a282010-08-23 23:25:46 +00003392Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003393 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003394 Expr *ExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003395 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003396
3397 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003398 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003399 if (Result.isInvalid()) return ExprError();
3400 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003401
Richard Trieuba63ce62011-09-09 01:45:06 +00003402 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003403
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003404 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003405 // If this is a pseudo-destructor expression, build the call immediately.
3406 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3407 if (NumArgs > 0) {
3408 // Pseudo-destructor calls should not have any arguments.
3409 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003410 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003411 SourceRange(Args[0]->getLocStart(),
3412 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003413
Douglas Gregorad8a3362009-09-04 17:36:40 +00003414 NumArgs = 0;
3415 }
Mike Stump11289f42009-09-09 15:08:12 +00003416
Douglas Gregorad8a3362009-09-04 17:36:40 +00003417 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003418 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003419 }
Mike Stump11289f42009-09-09 15:08:12 +00003420
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003421 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003422 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003423 // FIXME: Will need to cache the results of name lookup (including ADL) in
3424 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003425 bool Dependent = false;
3426 if (Fn->isTypeDependent())
3427 Dependent = true;
3428 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3429 Dependent = true;
3430
Peter Collingbourne41f85462011-02-09 21:07:24 +00003431 if (Dependent) {
3432 if (ExecConfig) {
3433 return Owned(new (Context) CUDAKernelCallExpr(
3434 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3435 Context.DependentTy, VK_RValue, RParenLoc));
3436 } else {
3437 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3438 Context.DependentTy, VK_RValue,
3439 RParenLoc));
3440 }
3441 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003442
3443 // Determine whether this is a call to an object (C++ [over.call.object]).
3444 if (Fn->getType()->isRecordType())
3445 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003446 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003447
John McCall2979fe02011-04-12 00:42:48 +00003448 if (Fn->getType() == Context.UnknownAnyTy) {
3449 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3450 if (result.isInvalid()) return ExprError();
3451 Fn = result.take();
3452 }
3453
John McCall0009fcc2011-04-26 20:42:42 +00003454 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003455 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003456 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003457 }
John McCall0009fcc2011-04-26 20:42:42 +00003458 }
John McCall10eae182009-11-30 22:42:35 +00003459
John McCall0009fcc2011-04-26 20:42:42 +00003460 // Check for overloaded calls. This can happen even in C due to extensions.
3461 if (Fn->getType() == Context.OverloadTy) {
3462 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3463
3464 // We aren't supposed to apply this logic if there's an '&' involved.
3465 if (!find.IsAddressOfOperand) {
3466 OverloadExpr *ovl = find.Expression;
3467 if (isa<UnresolvedLookupExpr>(ovl)) {
3468 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3469 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3470 RParenLoc, ExecConfig);
3471 } else {
John McCall2d74de92009-12-01 22:10:20 +00003472 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003473 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003474 }
3475 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003476 }
3477
Douglas Gregore254f902009-02-04 00:32:51 +00003478 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003479
Eli Friedmane14b1992009-12-26 03:35:45 +00003480 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003481
John McCall57500772009-12-16 12:17:52 +00003482 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003483 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3484 if (UnOp->getOpcode() == UO_AddrOf)
3485 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3486
John McCall57500772009-12-16 12:17:52 +00003487 if (isa<DeclRefExpr>(NakedFn))
3488 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003489 else if (isa<MemberExpr>(NakedFn))
3490 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003491
Peter Collingbourne41f85462011-02-09 21:07:24 +00003492 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3493 ExecConfig);
3494}
3495
3496ExprResult
3497Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003498 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003499 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3500 if (!ConfigDecl)
3501 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3502 << "cudaConfigureCall");
3503 QualType ConfigQTy = ConfigDecl->getType();
3504
3505 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3506 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3507
Richard Trieuba63ce62011-09-09 01:45:06 +00003508 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003509}
3510
Tanya Lattner55808c12011-06-04 00:47:47 +00003511/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3512///
3513/// __builtin_astype( value, dst type )
3514///
Richard Trieuba63ce62011-09-09 01:45:06 +00003515ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003516 SourceLocation BuiltinLoc,
3517 SourceLocation RParenLoc) {
3518 ExprValueKind VK = VK_RValue;
3519 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003520 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3521 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003522 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3523 return ExprError(Diag(BuiltinLoc,
3524 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003525 << DstTy
3526 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003527 << E->getSourceRange());
3528 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003529 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003530}
3531
John McCall57500772009-12-16 12:17:52 +00003532/// BuildResolvedCallExpr - Build a call to a resolved expression,
3533/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003534/// unary-convert to an expression of function-pointer or
3535/// block-pointer type.
3536///
3537/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003538ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003539Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3540 SourceLocation LParenLoc,
3541 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003542 SourceLocation RParenLoc,
3543 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003544 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3545
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003546 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003547 ExprResult Result = UsualUnaryConversions(Fn);
3548 if (Result.isInvalid())
3549 return ExprError();
3550 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003551
Chris Lattner08464942007-12-28 05:29:59 +00003552 // Make the call expr early, before semantic checks. This guarantees cleanup
3553 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003554 CallExpr *TheCall;
3555 if (Config) {
3556 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3557 cast<CallExpr>(Config),
3558 Args, NumArgs,
3559 Context.BoolTy,
3560 VK_RValue,
3561 RParenLoc);
3562 } else {
3563 TheCall = new (Context) CallExpr(Context, Fn,
3564 Args, NumArgs,
3565 Context.BoolTy,
3566 VK_RValue,
3567 RParenLoc);
3568 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003569
John McCallbebede42011-02-26 05:39:39 +00003570 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3571
3572 // Bail out early if calling a builtin with custom typechecking.
3573 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3574 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3575
John McCall31996342011-04-07 08:22:57 +00003576 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003577 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003578 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003579 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3580 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003581 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003582 if (FuncT == 0)
3583 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3584 << Fn->getType() << Fn->getSourceRange());
3585 } else if (const BlockPointerType *BPT =
3586 Fn->getType()->getAs<BlockPointerType>()) {
3587 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3588 } else {
John McCall31996342011-04-07 08:22:57 +00003589 // Handle calls to expressions of unknown-any type.
3590 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003591 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003592 if (rewrite.isInvalid()) return ExprError();
3593 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003594 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003595 goto retry;
3596 }
3597
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003598 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3599 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003600 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003601
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003602 if (getLangOptions().CUDA) {
3603 if (Config) {
3604 // CUDA: Kernel calls must be to global functions
3605 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3606 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3607 << FDecl->getName() << Fn->getSourceRange());
3608
3609 // CUDA: Kernel function must have 'void' return type
3610 if (!FuncT->getResultType()->isVoidType())
3611 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3612 << Fn->getType() << Fn->getSourceRange());
3613 }
3614 }
3615
Eli Friedman3164fb12009-03-22 22:00:50 +00003616 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003617 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003618 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003619 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003620 return ExprError();
3621
Chris Lattner08464942007-12-28 05:29:59 +00003622 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003623 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003624 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003625
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003626 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003627 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003628 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003629 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003630 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003631 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003632
Douglas Gregord8e97de2009-04-02 15:37:10 +00003633 if (FDecl) {
3634 // Check if we have too few/too many template arguments, based
3635 // on our knowledge of the function definition.
3636 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003637 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003638 const FunctionProtoType *Proto
3639 = Def->getType()->getAs<FunctionProtoType>();
3640 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003641 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3642 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003643 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003644
3645 // If the function we're calling isn't a function prototype, but we have
3646 // a function prototype from a prior declaratiom, use that prototype.
3647 if (!FDecl->hasPrototype())
3648 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003649 }
3650
Steve Naroff0b661582007-08-28 23:30:39 +00003651 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003652 for (unsigned i = 0; i != NumArgs; i++) {
3653 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003654
3655 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003656 InitializedEntity Entity
3657 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003658 Proto->getArgType(i),
3659 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003660 ExprResult ArgE = PerformCopyInitialization(Entity,
3661 SourceLocation(),
3662 Owned(Arg));
3663 if (ArgE.isInvalid())
3664 return true;
3665
3666 Arg = ArgE.takeAs<Expr>();
3667
3668 } else {
John Wiegley01296292011-04-08 18:41:53 +00003669 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3670
3671 if (ArgE.isInvalid())
3672 return true;
3673
3674 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003675 }
3676
Douglas Gregor83025412010-10-26 05:45:40 +00003677 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3678 Arg->getType(),
3679 PDiag(diag::err_call_incomplete_argument)
3680 << Arg->getSourceRange()))
3681 return ExprError();
3682
Chris Lattner08464942007-12-28 05:29:59 +00003683 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003684 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003685 }
Chris Lattner08464942007-12-28 05:29:59 +00003686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003687 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3688 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003689 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3690 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003691
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003692 // Check for sentinels
3693 if (NDecl)
3694 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003695
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003696 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003697 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003698 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003699 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003700
John McCallbebede42011-02-26 05:39:39 +00003701 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003702 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003703 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003704 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003705 return ExprError();
3706 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003707
John McCallb268a282010-08-23 23:25:46 +00003708 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003709}
3710
John McCalldadc5752010-08-24 06:29:42 +00003711ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003712Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003713 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003714 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003715 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003716 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003717
3718 TypeSourceInfo *TInfo;
3719 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3720 if (!TInfo)
3721 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3722
John McCallb268a282010-08-23 23:25:46 +00003723 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003724}
3725
John McCalldadc5752010-08-24 06:29:42 +00003726ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003727Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003728 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003729 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003730
Eli Friedman37a186d2008-05-20 05:22:08 +00003731 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003732 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3733 PDiag(diag::err_illegal_decl_array_incomplete_type)
3734 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003735 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003736 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003737 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003738 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003739 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003740 } else if (!literalType->isDependentType() &&
3741 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003742 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003743 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003744 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003745 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003746
Douglas Gregor85dabae2009-12-16 01:38:02 +00003747 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003748 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003749 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003750 = InitializationKind::CreateCStyleCast(LParenLoc,
3751 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003752 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003753 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003754 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003755 &literalType);
3756 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003757 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003758 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003759
Chris Lattner79413952008-12-04 23:50:19 +00003760 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003761 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003762 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003763 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003764 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003765
John McCall7decc9e2010-11-18 06:31:45 +00003766 // In C, compound literals are l-values for some reason.
3767 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3768
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003769 return MaybeBindToTemporary(
3770 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003771 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003772}
3773
John McCalldadc5752010-08-24 06:29:42 +00003774ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003775Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003776 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003777 unsigned NumInit = InitArgList.size();
3778 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003779
Steve Naroff30d242c2007-09-15 18:49:24 +00003780 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003781 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003782
Ted Kremenekac034612010-04-13 23:39:13 +00003783 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3784 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003785 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003786 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003787}
3788
John McCallcd78e802011-09-10 01:16:55 +00003789/// Do an explicit extend of the given block pointer if we're in ARC.
3790static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3791 assert(E.get()->getType()->isBlockPointerType());
3792 assert(E.get()->isRValue());
3793
3794 // Only do this in an r-value context.
3795 if (!S.getLangOptions().ObjCAutoRefCount) return;
3796
3797 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003798 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003799 /*base path*/ 0, VK_RValue);
3800 S.ExprNeedsCleanups = true;
3801}
3802
3803/// Prepare a conversion of the given expression to an ObjC object
3804/// pointer type.
3805CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3806 QualType type = E.get()->getType();
3807 if (type->isObjCObjectPointerType()) {
3808 return CK_BitCast;
3809 } else if (type->isBlockPointerType()) {
3810 maybeExtendBlockObject(*this, E);
3811 return CK_BlockPointerToObjCPointerCast;
3812 } else {
3813 assert(type->isPointerType());
3814 return CK_CPointerToObjCPointerCast;
3815 }
3816}
3817
John McCalld7646252010-11-14 08:17:51 +00003818/// Prepares for a scalar cast, performing all the necessary stages
3819/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003820static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003821 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3822 // Also, callers should have filtered out the invalid cases with
3823 // pointers. Everything else should be possible.
3824
John Wiegley01296292011-04-08 18:41:53 +00003825 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003826 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003827 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003828
John McCall9320b872011-09-09 05:25:32 +00003829 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003830 case Type::STK_MemberPointer:
3831 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003832
John McCall9320b872011-09-09 05:25:32 +00003833 case Type::STK_CPointer:
3834 case Type::STK_BlockPointer:
3835 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003836 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003837 case Type::STK_CPointer:
3838 return CK_BitCast;
3839 case Type::STK_BlockPointer:
3840 return (SrcKind == Type::STK_BlockPointer
3841 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3842 case Type::STK_ObjCObjectPointer:
3843 if (SrcKind == Type::STK_ObjCObjectPointer)
3844 return CK_BitCast;
3845 else if (SrcKind == Type::STK_CPointer)
3846 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003847 else {
3848 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003849 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003850 }
John McCall8cb679e2010-11-15 09:13:47 +00003851 case Type::STK_Bool:
3852 return CK_PointerToBoolean;
3853 case Type::STK_Integral:
3854 return CK_PointerToIntegral;
3855 case Type::STK_Floating:
3856 case Type::STK_FloatingComplex:
3857 case Type::STK_IntegralComplex:
3858 case Type::STK_MemberPointer:
3859 llvm_unreachable("illegal cast from pointer");
3860 }
3861 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003862
John McCall8cb679e2010-11-15 09:13:47 +00003863 case Type::STK_Bool: // casting from bool is like casting from an integer
3864 case Type::STK_Integral:
3865 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003866 case Type::STK_CPointer:
3867 case Type::STK_ObjCObjectPointer:
3868 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003869 if (Src.get()->isNullPointerConstant(S.Context,
3870 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003871 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003872 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003873 case Type::STK_Bool:
3874 return CK_IntegralToBoolean;
3875 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003876 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003877 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003878 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003879 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003880 Src = S.ImpCastExprToType(Src.take(),
3881 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003882 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003883 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003884 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003885 Src = S.ImpCastExprToType(Src.take(),
3886 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003887 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003888 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003889 case Type::STK_MemberPointer:
3890 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003891 }
3892 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003893
John McCall8cb679e2010-11-15 09:13:47 +00003894 case Type::STK_Floating:
3895 switch (DestTy->getScalarTypeKind()) {
3896 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003897 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003898 case Type::STK_Bool:
3899 return CK_FloatingToBoolean;
3900 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003901 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003902 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003903 Src = S.ImpCastExprToType(Src.take(),
3904 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003905 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003906 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003907 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003908 Src = S.ImpCastExprToType(Src.take(),
3909 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003910 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003911 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003912 case Type::STK_CPointer:
3913 case Type::STK_ObjCObjectPointer:
3914 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003915 llvm_unreachable("valid float->pointer cast?");
3916 case Type::STK_MemberPointer:
3917 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003918 }
3919 break;
3920
John McCall8cb679e2010-11-15 09:13:47 +00003921 case Type::STK_FloatingComplex:
3922 switch (DestTy->getScalarTypeKind()) {
3923 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003924 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003925 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003926 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003927 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003928 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003929 if (S.Context.hasSameType(ET, DestTy))
3930 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003931 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003932 return CK_FloatingCast;
3933 }
John McCall8cb679e2010-11-15 09:13:47 +00003934 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003935 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003936 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003937 Src = S.ImpCastExprToType(Src.take(),
3938 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003939 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003940 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00003941 case Type::STK_CPointer:
3942 case Type::STK_ObjCObjectPointer:
3943 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003944 llvm_unreachable("valid complex float->pointer cast?");
3945 case Type::STK_MemberPointer:
3946 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003947 }
3948 break;
3949
John McCall8cb679e2010-11-15 09:13:47 +00003950 case Type::STK_IntegralComplex:
3951 switch (DestTy->getScalarTypeKind()) {
3952 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003953 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003954 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003955 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003956 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003957 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003958 if (S.Context.hasSameType(ET, DestTy))
3959 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003960 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003961 return CK_IntegralCast;
3962 }
John McCall8cb679e2010-11-15 09:13:47 +00003963 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003964 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003965 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003966 Src = S.ImpCastExprToType(Src.take(),
3967 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003968 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003969 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00003970 case Type::STK_CPointer:
3971 case Type::STK_ObjCObjectPointer:
3972 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003973 llvm_unreachable("valid complex int->pointer cast?");
3974 case Type::STK_MemberPointer:
3975 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003976 }
3977 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003978 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
John McCalld7646252010-11-14 08:17:51 +00003980 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00003981}
3982
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003983/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00003984ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
3985 SourceRange TypeRange, QualType CastType,
3986 Expr *CastExpr, CastKind &Kind,
3987 ExprValueKind &VK, CXXCastPath &BasePath,
3988 bool FunctionalStyle) {
3989 if (CastExpr->getType() == Context.UnknownAnyTy)
3990 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
3991 BasePath);
John McCall31996342011-04-07 08:22:57 +00003992
Sebastian Redl9f831db2009-07-25 15:41:38 +00003993 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003994 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003995 CastExpr->getLocEnd()),
3996 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003997 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003998
Richard Trieuba63ce62011-09-09 01:45:06 +00003999 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004000
John McCall7decc9e2010-11-18 06:31:45 +00004001 // We only support r-value casts in C.
4002 VK = VK_RValue;
4003
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004004 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4005 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004006 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004007 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004008 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004009 if (castExprRes.isInvalid())
4010 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004011 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004012
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004013 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004014 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004015 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004016 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004017
Richard Trieuba63ce62011-09-09 01:45:06 +00004018 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004019 if (castExprRes.isInvalid())
4020 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004021 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004022
Richard Trieuba63ce62011-09-09 01:45:06 +00004023 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004024 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004025 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004026
Richard Trieuba63ce62011-09-09 01:45:06 +00004027 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4028 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4029 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004030 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004031 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004032 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4033 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004034 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004035 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004036 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004037
Richard Trieuba63ce62011-09-09 01:45:06 +00004038 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004039 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004040 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004041 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004042 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004043 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004044 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004045 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004046 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004047 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4048 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004049 break;
4050 }
4051 }
John Wiegley01296292011-04-08 18:41:53 +00004052 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004053 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4054 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004055 return ExprError();
4056 }
John McCalle3027922010-08-25 11:45:40 +00004057 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004058 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004059 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004060
Anders Carlsson525b76b2009-10-16 02:48:28 +00004061 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004062 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4063 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004064 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004065 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004066
John McCalld7646252010-11-14 08:17:51 +00004067 // The type we're casting to is known to be a scalar or vector.
4068
4069 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004070 if (!CastExpr->getType()->isScalarType() &&
4071 !CastExpr->getType()->isVectorType()) {
4072 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004073 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004074 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004075 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004076 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004077
Richard Trieuba63ce62011-09-09 01:45:06 +00004078 if (CastType->isExtVectorType())
4079 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004080
Richard Trieuba63ce62011-09-09 01:45:06 +00004081 if (CastType->isVectorType()) {
4082 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004083 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004084 (CastExpr->getType()->isIntegerType() ||
4085 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004086 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004087 return Owned(CastExpr);
4088 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4089 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004090 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004091 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004092 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004093 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004094 if (CastExpr->getType()->isVectorType()) {
4095 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004096 return ExprError();
4097 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004098 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004099 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004100
John McCalld7646252010-11-14 08:17:51 +00004101 // The source and target types are both scalars, i.e.
4102 // - arithmetic types (fundamental, enum, and complex)
4103 // - all kinds of pointers
4104 // Note that member pointers were filtered out with C++, above.
4105
Richard Trieuba63ce62011-09-09 01:45:06 +00004106 if (isa<ObjCSelectorExpr>(CastExpr)) {
4107 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004108 return ExprError();
4109 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004110
John McCalld7646252010-11-14 08:17:51 +00004111 // If either type is a pointer, the other type has to be either an
4112 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004113 QualType CastExprType = CastExpr->getType();
4114 if (!CastType->isArithmeticType()) {
4115 if (!CastExprType->isIntegralType(Context) &&
4116 CastExprType->isArithmeticType()) {
4117 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004118 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004119 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004120 return ExprError();
4121 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004122 } else if (!CastExpr->getType()->isArithmeticType()) {
4123 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4124 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4125 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004126 return ExprError();
4127 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004128 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004129
John McCall31168b02011-06-15 23:02:42 +00004130 if (getLangOptions().ObjCAutoRefCount) {
4131 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004132 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4133 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004134
Richard Trieuba63ce62011-09-09 01:45:06 +00004135 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4136 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004137 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4138 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4139 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4140 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4141 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004143 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004144 << CastExprType << CastType << AA_Casting
4145 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004146
4147 return ExprError();
4148 }
4149 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004150 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004151 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4152 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004153 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004154 << CastExprType << CastType
4155 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004156 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004157 }
4158 }
4159
Richard Trieuba63ce62011-09-09 01:45:06 +00004160 castExprRes = Owned(CastExpr);
4161 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004162 if (castExprRes.isInvalid())
4163 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004164 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004165
John McCalld7646252010-11-14 08:17:51 +00004166 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004167 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004168
Richard Trieuba63ce62011-09-09 01:45:06 +00004169 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004170}
4171
Anders Carlsson525b76b2009-10-16 02:48:28 +00004172bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004173 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004174 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004175
Anders Carlssonde71adf2007-11-27 05:51:55 +00004176 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004177 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004178 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004179 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004180 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004181 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004182 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004183 } else
4184 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004185 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004186 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004187
John McCalle3027922010-08-25 11:45:40 +00004188 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004189 return false;
4190}
4191
John Wiegley01296292011-04-08 18:41:53 +00004192ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4193 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004194 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004195
Anders Carlsson43d70f82009-10-16 05:23:41 +00004196 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004197
Nate Begemanc8961a42009-06-27 22:05:55 +00004198 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4199 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004200 // In OpenCL, casts between vectors of different types are not allowed.
4201 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004202 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004203 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4204 || (getLangOptions().OpenCL &&
4205 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004206 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004207 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004208 return ExprError();
4209 }
John McCalle3027922010-08-25 11:45:40 +00004210 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004211 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004212 }
4213
Nate Begemanbd956c42009-06-28 02:36:38 +00004214 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004215 // conversion will take place first from scalar to elt type, and then
4216 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004217 if (SrcTy->isPointerType())
4218 return Diag(R.getBegin(),
4219 diag::err_invalid_conversion_between_vector_and_scalar)
4220 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004221
4222 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004223 ExprResult CastExprRes = Owned(CastExpr);
4224 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4225 if (CastExprRes.isInvalid())
4226 return ExprError();
4227 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004228
John McCalle3027922010-08-25 11:45:40 +00004229 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004230 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004231}
4232
John McCalldadc5752010-08-24 06:29:42 +00004233ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004234Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4235 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004236 SourceLocation RParenLoc, Expr *CastExpr) {
4237 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004238 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004239
Richard Trieuba63ce62011-09-09 01:45:06 +00004240 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004241 if (D.isInvalidType())
4242 return ExprError();
4243
4244 if (getLangOptions().CPlusPlus) {
4245 // Check that there are no default arguments (C++ only).
4246 CheckExtraCXXDefaultArguments(D);
4247 }
4248
4249 QualType castType = castTInfo->getType();
4250 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004251
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004252 bool isVectorLiteral = false;
4253
4254 // Check for an altivec or OpenCL literal,
4255 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004256 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4257 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004258 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4259 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004260 if (PLE && PLE->getNumExprs() == 0) {
4261 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4262 return ExprError();
4263 }
4264 if (PE || PLE->getNumExprs() == 1) {
4265 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4266 if (!E->getType()->isVectorType())
4267 isVectorLiteral = true;
4268 }
4269 else
4270 isVectorLiteral = true;
4271 }
4272
4273 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4274 // then handle it as such.
4275 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004276 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004277
Nate Begeman5ec4b312009-08-10 23:49:36 +00004278 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004279 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4280 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004281 if (isa<ParenListExpr>(CastExpr)) {
4282 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004283 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004284 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004285 }
John McCallebe54742010-01-15 18:56:44 +00004286
Richard Trieuba63ce62011-09-09 01:45:06 +00004287 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004288}
4289
John McCalldadc5752010-08-24 06:29:42 +00004290ExprResult
John McCallebe54742010-01-15 18:56:44 +00004291Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004292 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004293 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004294 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004295 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004296 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004297 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004298 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004299 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004300 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004301 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004302
Richard Trieucfc491d2011-08-02 04:35:43 +00004303 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004304 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004305 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004306}
4307
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004308ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4309 SourceLocation RParenLoc, Expr *E,
4310 TypeSourceInfo *TInfo) {
4311 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4312 "Expected paren or paren list expression");
4313
4314 Expr **exprs;
4315 unsigned numExprs;
4316 Expr *subExpr;
4317 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4318 exprs = PE->getExprs();
4319 numExprs = PE->getNumExprs();
4320 } else {
4321 subExpr = cast<ParenExpr>(E)->getSubExpr();
4322 exprs = &subExpr;
4323 numExprs = 1;
4324 }
4325
4326 QualType Ty = TInfo->getType();
4327 assert(Ty->isVectorType() && "Expected vector type");
4328
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004329 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004330 const VectorType *VTy = Ty->getAs<VectorType>();
4331 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4332
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004333 // '(...)' form of vector initialization in AltiVec: the number of
4334 // initializers must be one or must match the size of the vector.
4335 // If a single value is specified in the initializer then it will be
4336 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004337 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004338 // The number of initializers must be one or must match the size of the
4339 // vector. If a single value is specified in the initializer then it will
4340 // be replicated to all the components of the vector
4341 if (numExprs == 1) {
4342 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4343 ExprResult Literal = Owned(exprs[0]);
4344 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4345 PrepareScalarCast(*this, Literal, ElemTy));
4346 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4347 }
4348 else if (numExprs < numElems) {
4349 Diag(E->getExprLoc(),
4350 diag::err_incorrect_number_of_vector_initializers);
4351 return ExprError();
4352 }
4353 else
4354 for (unsigned i = 0, e = numExprs; i != e; ++i)
4355 initExprs.push_back(exprs[i]);
4356 }
Tanya Lattner83559382011-07-15 23:07:01 +00004357 else {
4358 // For OpenCL, when the number of initializers is a single value,
4359 // it will be replicated to all components of the vector.
4360 if (getLangOptions().OpenCL &&
4361 VTy->getVectorKind() == VectorType::GenericVector &&
4362 numExprs == 1) {
4363 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4364 ExprResult Literal = Owned(exprs[0]);
4365 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4366 PrepareScalarCast(*this, Literal, ElemTy));
4367 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4368 }
4369
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004370 for (unsigned i = 0, e = numExprs; i != e; ++i)
4371 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004372 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004373 // FIXME: This means that pretty-printing the final AST will produce curly
4374 // braces instead of the original commas.
4375 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4376 &initExprs[0],
4377 initExprs.size(), RParenLoc);
4378 initE->setType(Ty);
4379 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4380}
4381
Nate Begeman5ec4b312009-08-10 23:49:36 +00004382/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4383/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004384ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004385Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4386 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004387 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004388 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004389
John McCalldadc5752010-08-24 06:29:42 +00004390 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004391
Nate Begeman5ec4b312009-08-10 23:49:36 +00004392 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004393 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4394 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004395
John McCallb268a282010-08-23 23:25:46 +00004396 if (Result.isInvalid()) return ExprError();
4397
4398 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004399}
4400
John McCalldadc5752010-08-24 06:29:42 +00004401ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004402 SourceLocation R,
4403 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004404 unsigned nexprs = Val.size();
4405 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004406 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4407 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004408 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004409 expr = new (Context) ParenExpr(L, R, exprs[0]);
4410 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004411 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4412 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004413 return Owned(expr);
4414}
4415
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004416/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004417/// constant and the other is not a pointer. Returns true if a diagnostic is
4418/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004419bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004420 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004421 Expr *NullExpr = LHSExpr;
4422 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004423 Expr::NullPointerConstantKind NullKind =
4424 NullExpr->isNullPointerConstant(Context,
4425 Expr::NPC_ValueDependentIsNotNull);
4426
4427 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004428 NullExpr = RHSExpr;
4429 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004430 NullKind =
4431 NullExpr->isNullPointerConstant(Context,
4432 Expr::NPC_ValueDependentIsNotNull);
4433 }
4434
4435 if (NullKind == Expr::NPCK_NotNull)
4436 return false;
4437
4438 if (NullKind == Expr::NPCK_ZeroInteger) {
4439 // In this case, check to make sure that we got here from a "NULL"
4440 // string in the source code.
4441 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004442 SourceLocation loc = NullExpr->getExprLoc();
4443 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004444 return false;
4445 }
4446
4447 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4448 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4449 << NonPointerExpr->getType() << DiagType
4450 << NonPointerExpr->getSourceRange();
4451 return true;
4452}
4453
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004454/// \brief Return false if the condition expression is valid, true otherwise.
4455static bool checkCondition(Sema &S, Expr *Cond) {
4456 QualType CondTy = Cond->getType();
4457
4458 // C99 6.5.15p2
4459 if (CondTy->isScalarType()) return false;
4460
4461 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4462 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4463 return false;
4464
4465 // Emit the proper error message.
4466 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4467 diag::err_typecheck_cond_expect_scalar :
4468 diag::err_typecheck_cond_expect_scalar_or_vector)
4469 << CondTy;
4470 return true;
4471}
4472
4473/// \brief Return false if the two expressions can be converted to a vector,
4474/// true otherwise
4475static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4476 ExprResult &RHS,
4477 QualType CondTy) {
4478 // Both operands should be of scalar type.
4479 if (!LHS.get()->getType()->isScalarType()) {
4480 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4481 << CondTy;
4482 return true;
4483 }
4484 if (!RHS.get()->getType()->isScalarType()) {
4485 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4486 << CondTy;
4487 return true;
4488 }
4489
4490 // Implicity convert these scalars to the type of the condition.
4491 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4492 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4493 return false;
4494}
4495
4496/// \brief Handle when one or both operands are void type.
4497static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4498 ExprResult &RHS) {
4499 Expr *LHSExpr = LHS.get();
4500 Expr *RHSExpr = RHS.get();
4501
4502 if (!LHSExpr->getType()->isVoidType())
4503 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4504 << RHSExpr->getSourceRange();
4505 if (!RHSExpr->getType()->isVoidType())
4506 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4507 << LHSExpr->getSourceRange();
4508 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4509 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4510 return S.Context.VoidTy;
4511}
4512
4513/// \brief Return false if the NullExpr can be promoted to PointerTy,
4514/// true otherwise.
4515static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4516 QualType PointerTy) {
4517 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4518 !NullExpr.get()->isNullPointerConstant(S.Context,
4519 Expr::NPC_ValueDependentIsNull))
4520 return true;
4521
4522 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4523 return false;
4524}
4525
4526/// \brief Checks compatibility between two pointers and return the resulting
4527/// type.
4528static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4529 ExprResult &RHS,
4530 SourceLocation Loc) {
4531 QualType LHSTy = LHS.get()->getType();
4532 QualType RHSTy = RHS.get()->getType();
4533
4534 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4535 // Two identical pointers types are always compatible.
4536 return LHSTy;
4537 }
4538
4539 QualType lhptee, rhptee;
4540
4541 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004542 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4543 lhptee = LHSBTy->getPointeeType();
4544 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004545 } else {
John McCall9320b872011-09-09 05:25:32 +00004546 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4547 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004548 }
4549
4550 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4551 rhptee.getUnqualifiedType())) {
4552 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4553 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4554 << RHS.get()->getSourceRange();
4555 // In this situation, we assume void* type. No especially good
4556 // reason, but this is what gcc does, and we do have to pick
4557 // to get a consistent AST.
4558 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4559 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4560 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4561 return incompatTy;
4562 }
4563
4564 // The pointer types are compatible.
4565 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4566 // differently qualified versions of compatible types, the result type is
4567 // a pointer to an appropriately qualified version of the *composite*
4568 // type.
4569 // FIXME: Need to calculate the composite type.
4570 // FIXME: Need to add qualifiers
4571
4572 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4573 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4574 return LHSTy;
4575}
4576
4577/// \brief Return the resulting type when the operands are both block pointers.
4578static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4579 ExprResult &LHS,
4580 ExprResult &RHS,
4581 SourceLocation Loc) {
4582 QualType LHSTy = LHS.get()->getType();
4583 QualType RHSTy = RHS.get()->getType();
4584
4585 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4586 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4587 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4588 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4589 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4590 return destType;
4591 }
4592 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4593 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4594 << RHS.get()->getSourceRange();
4595 return QualType();
4596 }
4597
4598 // We have 2 block pointer types.
4599 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4600}
4601
4602/// \brief Return the resulting type when the operands are both pointers.
4603static QualType
4604checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4605 ExprResult &RHS,
4606 SourceLocation Loc) {
4607 // get the pointer types
4608 QualType LHSTy = LHS.get()->getType();
4609 QualType RHSTy = RHS.get()->getType();
4610
4611 // get the "pointed to" types
4612 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4613 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4614
4615 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4616 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4617 // Figure out necessary qualifiers (C99 6.5.15p6)
4618 QualType destPointee
4619 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4620 QualType destType = S.Context.getPointerType(destPointee);
4621 // Add qualifiers if necessary.
4622 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4623 // Promote to void*.
4624 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4625 return destType;
4626 }
4627 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4628 QualType destPointee
4629 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4630 QualType destType = S.Context.getPointerType(destPointee);
4631 // Add qualifiers if necessary.
4632 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4633 // Promote to void*.
4634 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4635 return destType;
4636 }
4637
4638 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4639}
4640
4641/// \brief Return false if the first expression is not an integer and the second
4642/// expression is not a pointer, true otherwise.
4643static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4644 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004645 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004646 if (!PointerExpr->getType()->isPointerType() ||
4647 !Int.get()->getType()->isIntegerType())
4648 return false;
4649
Richard Trieuba63ce62011-09-09 01:45:06 +00004650 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4651 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004652
4653 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4654 << Expr1->getType() << Expr2->getType()
4655 << Expr1->getSourceRange() << Expr2->getSourceRange();
4656 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4657 CK_IntegralToPointer);
4658 return true;
4659}
4660
Richard Trieud33e46e2011-09-06 20:06:39 +00004661/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4662/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004663/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004664QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4665 ExprResult &RHS, ExprValueKind &VK,
4666 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004667 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004668
Richard Trieud33e46e2011-09-06 20:06:39 +00004669 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4670 if (!LHSResult.isUsable()) return QualType();
4671 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004672
Richard Trieud33e46e2011-09-06 20:06:39 +00004673 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4674 if (!RHSResult.isUsable()) return QualType();
4675 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004676
Sebastian Redl1a99f442009-04-16 17:51:27 +00004677 // C++ is sufficiently different to merit its own checker.
4678 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004679 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004680
4681 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004682 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004683
John Wiegley01296292011-04-08 18:41:53 +00004684 Cond = UsualUnaryConversions(Cond.take());
4685 if (Cond.isInvalid())
4686 return QualType();
4687 LHS = UsualUnaryConversions(LHS.take());
4688 if (LHS.isInvalid())
4689 return QualType();
4690 RHS = UsualUnaryConversions(RHS.take());
4691 if (RHS.isInvalid())
4692 return QualType();
4693
4694 QualType CondTy = Cond.get()->getType();
4695 QualType LHSTy = LHS.get()->getType();
4696 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004697
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004698 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004699 if (checkCondition(*this, Cond.get()))
4700 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004701
Chris Lattnere2949f42008-01-06 22:42:25 +00004702 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004703 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004704 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004705
Nate Begemanabb5a732010-09-20 22:41:17 +00004706 // OpenCL: If the condition is a vector, and both operands are scalar,
4707 // attempt to implicity convert them to the vector type to act like the
4708 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004709 if (getLangOptions().OpenCL && CondTy->isVectorType())
4710 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004711 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004712
Chris Lattnere2949f42008-01-06 22:42:25 +00004713 // If both operands have arithmetic type, do the usual arithmetic conversions
4714 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004715 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4716 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004717 if (LHS.isInvalid() || RHS.isInvalid())
4718 return QualType();
4719 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004720 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004721
Chris Lattnere2949f42008-01-06 22:42:25 +00004722 // If both operands are the same structure or union type, the result is that
4723 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004724 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4725 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004726 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004727 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004728 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004729 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004730 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004731 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004732
Chris Lattnere2949f42008-01-06 22:42:25 +00004733 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004734 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004735 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004736 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004737 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004738
Steve Naroff039ad3c2008-01-08 01:11:38 +00004739 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4740 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004741 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4742 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004743
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004744 // All objective-c pointer type analysis is done here.
4745 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4746 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004747 if (LHS.isInvalid() || RHS.isInvalid())
4748 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 if (!compositeType.isNull())
4750 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004751
4752
Steve Naroff05efa972009-07-01 14:36:47 +00004753 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004754 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4755 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4756 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004757
Steve Naroff05efa972009-07-01 14:36:47 +00004758 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004759 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4760 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4761 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004762
John McCalle84af4e2010-11-13 01:35:44 +00004763 // GCC compatibility: soften pointer/integer mismatch. Note that
4764 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004765 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4766 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004767 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004768 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4769 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004770 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004771
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004772 // Emit a better diagnostic if one of the expressions is a null pointer
4773 // constant and the other is not a pointer type. In this case, the user most
4774 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004775 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004776 return QualType();
4777
Chris Lattnere2949f42008-01-06 22:42:25 +00004778 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004779 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004780 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4781 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004782 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004783}
4784
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004785/// FindCompositeObjCPointerType - Helper method to find composite type of
4786/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004787QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004788 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004789 QualType LHSTy = LHS.get()->getType();
4790 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004791
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004792 // Handle things like Class and struct objc_class*. Here we case the result
4793 // to the pseudo-builtin, because that will be implicitly cast back to the
4794 // redefinition type if an attempt is made to access its fields.
4795 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004796 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004797 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004798 return LHSTy;
4799 }
4800 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004801 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004802 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004803 return RHSTy;
4804 }
4805 // And the same for struct objc_object* / id
4806 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004807 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004808 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004809 return LHSTy;
4810 }
4811 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004812 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004813 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004814 return RHSTy;
4815 }
4816 // And the same for struct objc_selector* / SEL
4817 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004818 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004819 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004820 return LHSTy;
4821 }
4822 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004823 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004824 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004825 return RHSTy;
4826 }
4827 // Check constraints for Objective-C object pointers types.
4828 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004829
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004830 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4831 // Two identical object pointer types are always compatible.
4832 return LHSTy;
4833 }
John McCall9320b872011-09-09 05:25:32 +00004834 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4835 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004836 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004837
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004838 // If both operands are interfaces and either operand can be
4839 // assigned to the other, use that type as the composite
4840 // type. This allows
4841 // xxx ? (A*) a : (B*) b
4842 // where B is a subclass of A.
4843 //
4844 // Additionally, as for assignment, if either type is 'id'
4845 // allow silent coercion. Finally, if the types are
4846 // incompatible then make sure to use 'id' as the composite
4847 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004848
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4850 // It could return the composite type.
4851 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4852 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4853 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4854 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4855 } else if ((LHSTy->isObjCQualifiedIdType() ||
4856 RHSTy->isObjCQualifiedIdType()) &&
4857 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4858 // Need to handle "id<xx>" explicitly.
4859 // GCC allows qualified id and any Objective-C type to devolve to
4860 // id. Currently localizing to here until clear this should be
4861 // part of ObjCQualifiedIdTypesAreCompatible.
4862 compositeType = Context.getObjCIdType();
4863 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4864 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004865 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004866 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4867 ;
4868 else {
4869 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4870 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004871 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004872 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004873 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4874 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004875 return incompatTy;
4876 }
4877 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004878 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4879 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004880 return compositeType;
4881 }
4882 // Check Objective-C object pointer types and 'void *'
4883 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4884 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4885 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4886 QualType destPointee
4887 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4888 QualType destType = Context.getPointerType(destPointee);
4889 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004890 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004891 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004892 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004893 return destType;
4894 }
4895 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4896 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4897 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4898 QualType destPointee
4899 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4900 QualType destType = Context.getPointerType(destPointee);
4901 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004902 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004903 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004904 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004905 return destType;
4906 }
4907 return QualType();
4908}
4909
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004910/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004911/// ParenRange in parentheses.
4912static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004913 const PartialDiagnostic &Note,
4914 SourceRange ParenRange) {
4915 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4916 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4917 EndLoc.isValid()) {
4918 Self.Diag(Loc, Note)
4919 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4920 << FixItHint::CreateInsertion(EndLoc, ")");
4921 } else {
4922 // We can't display the parentheses, so just show the bare note.
4923 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004924 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004925}
4926
4927static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4928 return Opc >= BO_Mul && Opc <= BO_Shr;
4929}
4930
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004931/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4932/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004933/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4934/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004935static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004936 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004937 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4938 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004939 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004940 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004941
4942 // Built-in binary operator.
4943 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4944 if (IsArithmeticOp(OP->getOpcode())) {
4945 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004946 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004947 return true;
4948 }
4949 }
4950
4951 // Overloaded operator.
4952 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4953 if (Call->getNumArgs() != 2)
4954 return false;
4955
4956 // Make sure this is really a binary operator that is safe to pass into
4957 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4958 OverloadedOperatorKind OO = Call->getOperator();
4959 if (OO < OO_Plus || OO > OO_Arrow)
4960 return false;
4961
4962 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4963 if (IsArithmeticOp(OpKind)) {
4964 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004965 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004966 return true;
4967 }
4968 }
4969
4970 return false;
4971}
4972
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004973static bool IsLogicOp(BinaryOperatorKind Opc) {
4974 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4975}
4976
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004977/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4978/// or is a logical expression such as (x==y) which has int type, but is
4979/// commonly interpreted as boolean.
4980static bool ExprLooksBoolean(Expr *E) {
4981 E = E->IgnoreParenImpCasts();
4982
4983 if (E->getType()->isBooleanType())
4984 return true;
4985 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4986 return IsLogicOp(OP->getOpcode());
4987 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4988 return OP->getOpcode() == UO_LNot;
4989
4990 return false;
4991}
4992
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004993/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4994/// and binary operator are mixed in a way that suggests the programmer assumed
4995/// the conditional operator has higher precedence, for example:
4996/// "int x = a + someBinaryCondition ? 1 : 2".
4997static void DiagnoseConditionalPrecedence(Sema &Self,
4998 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004999 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005000 Expr *LHSExpr,
5001 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005002 BinaryOperatorKind CondOpcode;
5003 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005004
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005005 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005006 return;
5007 if (!ExprLooksBoolean(CondRHS))
5008 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005009
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005010 // The condition is an arithmetic binary expression, with a right-
5011 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005012
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005013 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005014 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005015 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005016
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005017 SuggestParentheses(Self, OpLoc,
5018 Self.PDiag(diag::note_precedence_conditional_silence)
5019 << BinaryOperator::getOpcodeStr(CondOpcode),
5020 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005021
5022 SuggestParentheses(Self, OpLoc,
5023 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005024 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005025}
5026
Steve Naroff83895f72007-09-16 03:34:24 +00005027/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005028/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005029ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005030 SourceLocation ColonLoc,
5031 Expr *CondExpr, Expr *LHSExpr,
5032 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005033 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5034 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005035 OpaqueValueExpr *opaqueValue = 0;
5036 Expr *commonExpr = 0;
5037 if (LHSExpr == 0) {
5038 commonExpr = CondExpr;
5039
5040 // We usually want to apply unary conversions *before* saving, except
5041 // in the special case of a C++ l-value conditional.
5042 if (!(getLangOptions().CPlusPlus
5043 && !commonExpr->isTypeDependent()
5044 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5045 && commonExpr->isGLValue()
5046 && commonExpr->isOrdinaryOrBitFieldObject()
5047 && RHSExpr->isOrdinaryOrBitFieldObject()
5048 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005049 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5050 if (commonRes.isInvalid())
5051 return ExprError();
5052 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005053 }
5054
5055 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5056 commonExpr->getType(),
5057 commonExpr->getValueKind(),
5058 commonExpr->getObjectKind());
5059 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005060 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005061
John McCall7decc9e2010-11-18 06:31:45 +00005062 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005063 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005064 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5065 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005066 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005067 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5068 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005069 return ExprError();
5070
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005071 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5072 RHS.get());
5073
John McCallc07a0c72011-02-17 10:25:35 +00005074 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005075 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5076 LHS.take(), ColonLoc,
5077 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005078
5079 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005080 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005081 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5082 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005083}
5084
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005085/// ConvertObjCSelfToClassRootType - convet type of 'self' in class method
Fariborz Jahaniandb8015c2011-09-17 19:23:40 +00005086/// to pointer to root of method's class.
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005087static QualType
5088ConvertObjCSelfToClassRootType(Sema &S, Expr *selfExpr) {
5089 QualType SelfType;
Fariborz Jahaniandb8015c2011-09-17 19:23:40 +00005090 if (const ObjCMethodDecl *MD = S.GetMethodIfSelfExpr(selfExpr))
5091 if (MD->isClassMethod()) {
5092 const ObjCInterfaceDecl *Root = 0;
5093 if (const ObjCInterfaceDecl * IDecl = MD->getClassInterface())
5094 do {
5095 Root = IDecl;
5096 } while ((IDecl = IDecl->getSuperClass()));
5097 if (Root)
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005098 SelfType = S.Context.getObjCObjectPointerType(
5099 S.Context.getObjCInterfaceType(Root));
Fariborz Jahaniandb8015c2011-09-17 19:23:40 +00005100 }
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005101 return SelfType;
Fariborz Jahaniandb8015c2011-09-17 19:23:40 +00005102}
5103
John McCallaba90822011-01-31 23:13:11 +00005104// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005105// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005106// routine is it effectively iqnores the qualifiers on the top level pointee.
5107// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5108// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005109static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005110checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5111 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5112 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005113
Steve Naroff1f4d7272007-05-11 04:00:31 +00005114 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005115 const Type *lhptee, *rhptee;
5116 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005117 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5118 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005119
John McCallaba90822011-01-31 23:13:11 +00005120 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005121
5122 // C99 6.5.16.1p1: This following citation is common to constraints
5123 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5124 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005125 Qualifiers lq;
5126
John McCall31168b02011-06-15 23:02:42 +00005127 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5128 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5129 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5130 // Ignore lifetime for further calculation.
5131 lhq.removeObjCLifetime();
5132 rhq.removeObjCLifetime();
5133 }
5134
John McCall4fff8f62011-02-01 00:10:29 +00005135 if (!lhq.compatiblyIncludes(rhq)) {
5136 // Treat address-space mismatches as fatal. TODO: address subspaces
5137 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5138 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5139
John McCall31168b02011-06-15 23:02:42 +00005140 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005141 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005142 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5143 .compatiblyIncludes(
5144 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005145 && (lhptee->isVoidType() || rhptee->isVoidType()))
5146 ; // keep old
5147
John McCall31168b02011-06-15 23:02:42 +00005148 // Treat lifetime mismatches as fatal.
5149 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5150 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5151
John McCall4fff8f62011-02-01 00:10:29 +00005152 // For GCC compatibility, other qualifier mismatches are treated
5153 // as still compatible in C.
5154 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5155 }
Steve Naroff3f597292007-05-11 22:18:03 +00005156
Mike Stump4e1f26a2009-02-19 03:04:26 +00005157 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5158 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005159 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005160 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005161 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005162 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163
Chris Lattner0a788432008-01-03 22:56:36 +00005164 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005165 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005166 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005167 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005168
Chris Lattner0a788432008-01-03 22:56:36 +00005169 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005170 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005171 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005172
5173 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005174 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005175 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005176 }
John McCall4fff8f62011-02-01 00:10:29 +00005177
Mike Stump4e1f26a2009-02-19 03:04:26 +00005178 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005179 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005180 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5181 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005182 // Check if the pointee types are compatible ignoring the sign.
5183 // We explicitly check for char so that we catch "char" vs
5184 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005185 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005186 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005187 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005188 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005189
Chris Lattnerec3a1562009-10-17 20:33:28 +00005190 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005191 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005192 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005193 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005194
John McCall4fff8f62011-02-01 00:10:29 +00005195 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005196 // Types are compatible ignoring the sign. Qualifier incompatibility
5197 // takes priority over sign incompatibility because the sign
5198 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005199 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005200 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005201
John McCallaba90822011-01-31 23:13:11 +00005202 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005203 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005204
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005205 // If we are a multi-level pointer, it's possible that our issue is simply
5206 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5207 // the eventual target type is the same and the pointers have the same
5208 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005209 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005210 do {
John McCall4fff8f62011-02-01 00:10:29 +00005211 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5212 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005213 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005214
John McCall4fff8f62011-02-01 00:10:29 +00005215 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005216 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005217 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005218
Eli Friedman80160bd2009-03-22 23:59:44 +00005219 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005220 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005221 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005222 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005223}
5224
John McCallaba90822011-01-31 23:13:11 +00005225/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005226/// block pointer types are compatible or whether a block and normal pointer
5227/// are compatible. It is more restrict than comparing two function pointer
5228// types.
John McCallaba90822011-01-31 23:13:11 +00005229static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005230checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5231 QualType RHSType) {
5232 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5233 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005234
Steve Naroff081c7422008-09-04 15:10:53 +00005235 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005236
Steve Naroff081c7422008-09-04 15:10:53 +00005237 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005238 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5239 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005240
John McCallaba90822011-01-31 23:13:11 +00005241 // In C++, the types have to match exactly.
5242 if (S.getLangOptions().CPlusPlus)
5243 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005244
John McCallaba90822011-01-31 23:13:11 +00005245 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005246
Steve Naroff081c7422008-09-04 15:10:53 +00005247 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005248 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5249 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005250
Richard Trieua871b972011-09-06 20:21:22 +00005251 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005252 return Sema::IncompatibleBlockPointer;
5253
Steve Naroff081c7422008-09-04 15:10:53 +00005254 return ConvTy;
5255}
5256
John McCallaba90822011-01-31 23:13:11 +00005257/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005258/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005259static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005260checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5261 QualType RHSType) {
5262 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5263 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005264
Richard Trieua871b972011-09-06 20:21:22 +00005265 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005266 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005267 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5268 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005269 return Sema::IncompatiblePointer;
5270 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005271 }
Richard Trieua871b972011-09-06 20:21:22 +00005272 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005273 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5274 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005275 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005276 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005277 }
Richard Trieua871b972011-09-06 20:21:22 +00005278 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5279 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005280
John McCallaba90822011-01-31 23:13:11 +00005281 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5282 return Sema::CompatiblePointerDiscardsQualifiers;
5283
Richard Trieua871b972011-09-06 20:21:22 +00005284 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005285 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005286 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005287 return Sema::IncompatibleObjCQualifiedId;
5288 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005289}
5290
John McCall29600e12010-11-16 02:32:08 +00005291Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005292Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005293 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005294 // Fake up an opaque expression. We don't actually care about what
5295 // cast operations are required, so if CheckAssignmentConstraints
5296 // adds casts to this they'll be wasted, but fortunately that doesn't
5297 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005298 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5299 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005300 CastKind K = CK_Invalid;
5301
Richard Trieua871b972011-09-06 20:21:22 +00005302 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005303}
5304
Mike Stump4e1f26a2009-02-19 03:04:26 +00005305/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5306/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005307/// pointers. Here are some objectionable examples that GCC considers warnings:
5308///
5309/// int a, *pint;
5310/// short *pshort;
5311/// struct foo *pfoo;
5312///
5313/// pint = pshort; // warning: assignment from incompatible pointer type
5314/// a = pint; // warning: assignment makes integer from pointer without a cast
5315/// pint = a; // warning: assignment makes pointer from integer without a cast
5316/// pint = pfoo; // warning: assignment from incompatible pointer type
5317///
5318/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005319/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005320///
John McCall8cb679e2010-11-15 09:13:47 +00005321/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005322Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005323Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005324 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005325 QualType RHSType = RHS.get()->getType();
5326 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005327
Chris Lattnera52c2f22008-01-04 23:18:45 +00005328 // Get canonical types. We're not formatting these types, just comparing
5329 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005330 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5331 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005332
John McCalle5255932011-01-31 22:28:28 +00005333 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005334 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005335 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005336 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005337 }
5338
Douglas Gregor6b754842008-10-28 00:22:11 +00005339 // If the left-hand side is a reference type, then we are in a
5340 // (rare!) case where we've allowed the use of references in C,
5341 // e.g., as a parameter type in a built-in function. In this case,
5342 // just make sure that the type referenced is compatible with the
5343 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005344 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005345 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005346 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5347 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005348 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005349 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005350 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005351 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005352 }
John McCalle5255932011-01-31 22:28:28 +00005353
Nate Begemanbd956c42009-06-28 02:36:38 +00005354 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5355 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005356 if (LHSType->isExtVectorType()) {
5357 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005358 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005359 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005360 // CK_VectorSplat does T -> vector T, so first cast to the
5361 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005362 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5363 if (elType != RHSType) {
5364 Kind = PrepareScalarCast(*this, RHS, elType);
5365 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005366 }
5367 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005368 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005369 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005370 }
Mike Stump11289f42009-09-09 15:08:12 +00005371
John McCalle5255932011-01-31 22:28:28 +00005372 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005373 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5374 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005375 // Allow assignments of an AltiVec vector type to an equivalent GCC
5376 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005377 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005378 Kind = CK_BitCast;
5379 return Compatible;
5380 }
5381
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005382 // If we are allowing lax vector conversions, and LHS and RHS are both
5383 // vectors, the total size only needs to be the same. This is a bitcast;
5384 // no bits are changed but the result type is different.
5385 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005386 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005387 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005388 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005389 }
Chris Lattner881a2122008-01-04 23:32:24 +00005390 }
5391 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005392 }
Eli Friedman3360d892008-05-30 18:07:22 +00005393
John McCalle5255932011-01-31 22:28:28 +00005394 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005395 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5396 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5397 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005398 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005399 }
Eli Friedman3360d892008-05-30 18:07:22 +00005400
John McCalle5255932011-01-31 22:28:28 +00005401 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005402 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005403 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005404 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005405 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005406 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005407 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005408
John McCalle5255932011-01-31 22:28:28 +00005409 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005410 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005411 Kind = CK_IntegralToPointer; // FIXME: null?
5412 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005413 }
John McCalle5255932011-01-31 22:28:28 +00005414
5415 // C pointers are not compatible with ObjC object pointers,
5416 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005417 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005418 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005419 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005420 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005421 return Compatible;
5422 }
5423
5424 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005425 if (RHSType->isObjCClassType() &&
5426 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005427 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005428 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005429 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005430 }
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005431
John McCalle5255932011-01-31 22:28:28 +00005432 Kind = CK_BitCast;
5433 return IncompatiblePointer;
5434 }
5435
5436 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005437 if (RHSType->getAs<BlockPointerType>()) {
5438 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005439 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005440 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005441 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005442 }
John McCalle5255932011-01-31 22:28:28 +00005443
Steve Naroff081c7422008-09-04 15:10:53 +00005444 return Incompatible;
5445 }
5446
John McCalle5255932011-01-31 22:28:28 +00005447 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005448 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005449 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005450 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005451 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005452 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005453 }
5454
5455 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005456 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005457 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005458 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005459 }
5460
John McCalle5255932011-01-31 22:28:28 +00005461 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005462 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005463 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005464 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005465 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005466
John McCalle5255932011-01-31 22:28:28 +00005467 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005469 if (RHSPT->getPointeeType()->isVoidType()) {
5470 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005471 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005472 }
John McCall8cb679e2010-11-15 09:13:47 +00005473
Chris Lattnera52c2f22008-01-04 23:18:45 +00005474 return Incompatible;
5475 }
5476
John McCalle5255932011-01-31 22:28:28 +00005477 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005478 if (isa<ObjCObjectPointerType>(LHSType)) {
Fariborz Jahaniane20c0a52011-09-19 18:06:07 +00005479 QualType RHSQT = ConvertObjCSelfToClassRootType(*this, RHS.get());
5480 if (!RHSQT.isNull())
5481 RHSType = RHSQT;
John McCalle5255932011-01-31 22:28:28 +00005482 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005483 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005484 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005485 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005486 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005487 if (getLangOptions().ObjCAutoRefCount &&
5488 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005489 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005490 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005491 return result;
John McCalle5255932011-01-31 22:28:28 +00005492 }
5493
5494 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005495 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005496 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005497 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005498 }
5499
John McCalle5255932011-01-31 22:28:28 +00005500 // In general, C pointers are not compatible with ObjC object pointers,
5501 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005502 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005503 Kind = CK_CPointerToObjCPointerCast;
5504
John McCalle5255932011-01-31 22:28:28 +00005505 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005506 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005507 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005508 }
5509
5510 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005511 if (LHSType->isObjCClassType() &&
5512 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005513 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005514 return Compatible;
5515 }
5516
Steve Naroffaccc4882009-07-20 17:56:53 +00005517 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005518 }
John McCalle5255932011-01-31 22:28:28 +00005519
5520 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005521 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005522 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005523 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005524 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005525 }
5526
Steve Naroff7cae42b2009-07-10 23:34:53 +00005527 return Incompatible;
5528 }
John McCalle5255932011-01-31 22:28:28 +00005529
5530 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005531 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005532 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005533 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005534 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005535 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005536 }
Eli Friedman3360d892008-05-30 18:07:22 +00005537
John McCalle5255932011-01-31 22:28:28 +00005538 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005539 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005540 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005541 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005542 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005543
Chris Lattnera52c2f22008-01-04 23:18:45 +00005544 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005545 }
John McCalle5255932011-01-31 22:28:28 +00005546
5547 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005548 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005549 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005550 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005551 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005552 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005553 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005554
John McCalle5255932011-01-31 22:28:28 +00005555 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005556 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005557 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005558 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005559 }
5560
Steve Naroff7cae42b2009-07-10 23:34:53 +00005561 return Incompatible;
5562 }
Eli Friedman3360d892008-05-30 18:07:22 +00005563
John McCalle5255932011-01-31 22:28:28 +00005564 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005565 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5566 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005567 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005568 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005569 }
Bill Wendling216423b2007-05-30 06:30:29 +00005570 }
John McCalle5255932011-01-31 22:28:28 +00005571
Steve Naroff98cf3e92007-06-06 18:38:38 +00005572 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005573}
5574
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005575/// \brief Constructs a transparent union from an expression that is
5576/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005577static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5578 ExprResult &EResult, QualType UnionType,
5579 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005580 // Build an initializer list that designates the appropriate member
5581 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005582 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005583 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005584 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005585 SourceLocation());
5586 Initializer->setType(UnionType);
5587 Initializer->setInitializedFieldInUnion(Field);
5588
5589 // Build a compound literal constructing a value of the transparent
5590 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005591 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005592 EResult = S.Owned(
5593 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5594 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005595}
5596
5597Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005598Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005599 ExprResult &RHS) {
5600 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005601
Mike Stump11289f42009-09-09 15:08:12 +00005602 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005603 // transparent_union GCC extension.
5604 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005605 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005606 return Incompatible;
5607
5608 // The field to initialize within the transparent union.
5609 RecordDecl *UD = UT->getDecl();
5610 FieldDecl *InitField = 0;
5611 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005612 for (RecordDecl::field_iterator it = UD->field_begin(),
5613 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005614 it != itend; ++it) {
5615 if (it->getType()->isPointerType()) {
5616 // If the transparent union contains a pointer type, we allow:
5617 // 1) void pointer
5618 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005619 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005620 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005621 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005622 InitField = *it;
5623 break;
5624 }
Mike Stump11289f42009-09-09 15:08:12 +00005625
Richard Trieueb299142011-09-06 20:40:12 +00005626 if (RHS.get()->isNullPointerConstant(Context,
5627 Expr::NPC_ValueDependentIsNull)) {
5628 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5629 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005630 InitField = *it;
5631 break;
5632 }
5633 }
5634
John McCall8cb679e2010-11-15 09:13:47 +00005635 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005636 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005637 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005638 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005639 InitField = *it;
5640 break;
5641 }
5642 }
5643
5644 if (!InitField)
5645 return Incompatible;
5646
Richard Trieueb299142011-09-06 20:40:12 +00005647 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005648 return Compatible;
5649}
5650
Chris Lattner9bad62c2008-01-04 18:04:52 +00005651Sema::AssignConvertType
Richard Trieueb299142011-09-06 20:40:12 +00005652Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005653 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005654 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005655 // C++ 5.17p3: If the left operand is not of class type, the
5656 // expression is implicitly converted (C++ 4) to the
5657 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005658 ExprResult Res = PerformImplicitConversion(RHS.get(),
5659 LHSType.getUnqualifiedType(),
John Wiegley01296292011-04-08 18:41:53 +00005660 AA_Assigning);
5661 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005662 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005663 Sema::AssignConvertType result = Compatible;
5664 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005665 !CheckObjCARCUnavailableWeakConversion(LHSType,
5666 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005667 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005668 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005669 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005670 }
5671
5672 // FIXME: Currently, we fall through and treat C++ classes like C
5673 // structures.
John McCall34376a62010-12-04 03:47:34 +00005674 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005675
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005676 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5677 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005678 if ((LHSType->isPointerType() ||
5679 LHSType->isObjCObjectPointerType() ||
5680 LHSType->isBlockPointerType())
5681 && RHS.get()->isNullPointerConstant(Context,
5682 Expr::NPC_ValueDependentIsNull)) {
5683 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005684 return Compatible;
5685 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005686
Chris Lattnere6dcd502007-10-16 02:55:40 +00005687 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005688 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005689 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005690 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005691 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005692 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005693 if (!LHSType->isReferenceType()) {
5694 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5695 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005696 return Incompatible;
5697 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005698
John McCall8cb679e2010-11-15 09:13:47 +00005699 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005700 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005701 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005702
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005703 // C99 6.5.16.1p2: The value of the right operand is converted to the
5704 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005705 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5706 // so that we can use references in built-in functions even in C.
5707 // The getNonReferenceType() call makes sure that the resulting expression
5708 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005709 if (result != Incompatible && RHS.get()->getType() != LHSType)
5710 RHS = ImpCastExprToType(RHS.take(),
5711 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005712 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005713}
5714
Richard Trieueb299142011-09-06 20:40:12 +00005715QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5716 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005717 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005718 << LHS.get()->getType() << RHS.get()->getType()
5719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005720 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005721}
5722
Richard Trieu859d23f2011-09-06 21:01:04 +00005723QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005724 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005725 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005726 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005727 QualType LHSType =
5728 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5729 QualType RHSType =
5730 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005731
Nate Begeman191a6b12008-07-14 18:02:46 +00005732 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005733 if (LHSType == RHSType)
5734 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005735
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005736 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005737 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5738 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5739 if (LHSType->isExtVectorType()) {
5740 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5741 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005742 }
5743
Richard Trieuba63ce62011-09-09 01:45:06 +00005744 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005745 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5746 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005747 }
5748
Eli Friedman1408bc92011-06-23 18:10:35 +00005749 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005750 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005751 // If we are allowing lax vector conversions, and LHS and RHS are both
5752 // vectors, the total size only needs to be the same. This is a
5753 // bitcast; no bits are changed but the result type is different.
5754 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005755 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5756 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005757 }
5758
Nate Begemanbd956c42009-06-28 02:36:38 +00005759 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5760 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5761 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005762 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005763 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005764 std::swap(RHS, LHS);
5765 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005766 }
Mike Stump11289f42009-09-09 15:08:12 +00005767
Nate Begeman886448d2009-06-28 19:12:57 +00005768 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005769 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005770 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005771 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5772 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005773 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005774 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005775 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005776 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5777 if (swapped) std::swap(RHS, LHS);
5778 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005779 }
5780 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5782 RHSType->isRealFloatingType()) {
5783 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005784 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005785 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005786 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005787 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5788 if (swapped) std::swap(RHS, LHS);
5789 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005790 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005791 }
5792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
Nate Begeman886448d2009-06-28 19:12:57 +00005794 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005795 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005796 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005797 << LHS.get()->getType() << RHS.get()->getType()
5798 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005799 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005800}
5801
Richard Trieuf8916e12011-09-16 00:53:10 +00005802// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5803// expression. These are mainly cases where the null pointer is used as an
5804// integer instead of a pointer.
5805static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5806 SourceLocation Loc, bool IsCompare) {
5807 // The canonical way to check for a GNU null is with isNullPointerConstant,
5808 // but we use a bit of a hack here for speed; this is a relatively
5809 // hot path, and isNullPointerConstant is slow.
5810 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5811 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5812
5813 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5814
5815 // Avoid analyzing cases where the result will either be invalid (and
5816 // diagnosed as such) or entirely valid and not something to warn about.
5817 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5818 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5819 return;
5820
5821 // Comparison operations would not make sense with a null pointer no matter
5822 // what the other expression is.
5823 if (!IsCompare) {
5824 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5825 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5826 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5827 return;
5828 }
5829
5830 // The rest of the operations only make sense with a null pointer
5831 // if the other expression is a pointer.
5832 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5833 NonNullType->canDecayToPointerType())
5834 return;
5835
5836 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5837 << LHSNull /* LHS is NULL */ << NonNullType
5838 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5839}
5840
Richard Trieu859d23f2011-09-06 21:01:04 +00005841QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005842 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005843 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005844 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5845
Richard Trieu859d23f2011-09-06 21:01:04 +00005846 if (LHS.get()->getType()->isVectorType() ||
5847 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005848 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005849
Richard Trieuba63ce62011-09-09 01:45:06 +00005850 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005851 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005852 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005853
Richard Trieu859d23f2011-09-06 21:01:04 +00005854 if (!LHS.get()->getType()->isArithmeticType() ||
5855 !RHS.get()->getType()->isArithmeticType())
5856 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005857
Chris Lattnerfaa54172010-01-12 21:23:57 +00005858 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005859 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005860 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005861 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005862 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5863 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005864
Chris Lattnerfaa54172010-01-12 21:23:57 +00005865 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005866}
5867
Chris Lattnerfaa54172010-01-12 21:23:57 +00005868QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005869 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005870 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5871
Richard Trieu859d23f2011-09-06 21:01:04 +00005872 if (LHS.get()->getType()->isVectorType() ||
5873 RHS.get()->getType()->isVectorType()) {
5874 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5875 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005876 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005877 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005878 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005879
Richard Trieuba63ce62011-09-09 01:45:06 +00005880 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005881 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005882 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005883
Richard Trieu859d23f2011-09-06 21:01:04 +00005884 if (!LHS.get()->getType()->isIntegerType() ||
5885 !RHS.get()->getType()->isIntegerType())
5886 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005887
Chris Lattnerfaa54172010-01-12 21:23:57 +00005888 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005889 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005890 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005891 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5892 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005893
Chris Lattnerfaa54172010-01-12 21:23:57 +00005894 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005895}
5896
Chandler Carruthc9332212011-06-27 08:02:19 +00005897/// \brief Diagnose invalid arithmetic on two void pointers.
5898static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005899 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005900 S.Diag(Loc, S.getLangOptions().CPlusPlus
5901 ? diag::err_typecheck_pointer_arith_void_type
5902 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005903 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5904 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005905}
5906
5907/// \brief Diagnose invalid arithmetic on a void pointer.
5908static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5909 Expr *Pointer) {
5910 S.Diag(Loc, S.getLangOptions().CPlusPlus
5911 ? diag::err_typecheck_pointer_arith_void_type
5912 : diag::ext_gnu_void_ptr)
5913 << 0 /* one pointer */ << Pointer->getSourceRange();
5914}
5915
5916/// \brief Diagnose invalid arithmetic on two function pointers.
5917static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5918 Expr *LHS, Expr *RHS) {
5919 assert(LHS->getType()->isAnyPointerType());
5920 assert(RHS->getType()->isAnyPointerType());
5921 S.Diag(Loc, S.getLangOptions().CPlusPlus
5922 ? diag::err_typecheck_pointer_arith_function_type
5923 : diag::ext_gnu_ptr_func_arith)
5924 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5925 // We only show the second type if it differs from the first.
5926 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5927 RHS->getType())
5928 << RHS->getType()->getPointeeType()
5929 << LHS->getSourceRange() << RHS->getSourceRange();
5930}
5931
5932/// \brief Diagnose invalid arithmetic on a function pointer.
5933static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5934 Expr *Pointer) {
5935 assert(Pointer->getType()->isAnyPointerType());
5936 S.Diag(Loc, S.getLangOptions().CPlusPlus
5937 ? diag::err_typecheck_pointer_arith_function_type
5938 : diag::ext_gnu_ptr_func_arith)
5939 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5940 << 0 /* one pointer, so only one type */
5941 << Pointer->getSourceRange();
5942}
5943
Richard Trieu993f3ab2011-09-12 18:08:02 +00005944/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005945///
5946/// \returns True if pointer has incomplete type
5947static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5948 Expr *Operand) {
5949 if ((Operand->getType()->isPointerType() &&
5950 !Operand->getType()->isDependentType()) ||
5951 Operand->getType()->isObjCObjectPointerType()) {
5952 QualType PointeeTy = Operand->getType()->getPointeeType();
5953 if (S.RequireCompleteType(
5954 Loc, PointeeTy,
5955 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5956 << PointeeTy << Operand->getSourceRange()))
5957 return true;
5958 }
5959 return false;
5960}
5961
Chandler Carruthc9332212011-06-27 08:02:19 +00005962/// \brief Check the validity of an arithmetic pointer operand.
5963///
5964/// If the operand has pointer type, this code will check for pointer types
5965/// which are invalid in arithmetic operations. These will be diagnosed
5966/// appropriately, including whether or not the use is supported as an
5967/// extension.
5968///
5969/// \returns True when the operand is valid to use (even if as an extension).
5970static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5971 Expr *Operand) {
5972 if (!Operand->getType()->isAnyPointerType()) return true;
5973
5974 QualType PointeeTy = Operand->getType()->getPointeeType();
5975 if (PointeeTy->isVoidType()) {
5976 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5977 return !S.getLangOptions().CPlusPlus;
5978 }
5979 if (PointeeTy->isFunctionType()) {
5980 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5981 return !S.getLangOptions().CPlusPlus;
5982 }
5983
Richard Trieuaba22802011-09-02 02:15:37 +00005984 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005985
5986 return true;
5987}
5988
5989/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5990/// operands.
5991///
5992/// This routine will diagnose any invalid arithmetic on pointer operands much
5993/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5994/// for emitting a single diagnostic even for operations where both LHS and RHS
5995/// are (potentially problematic) pointers.
5996///
5997/// \returns True when the operand is valid to use (even if as an extension).
5998static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005999 Expr *LHSExpr, Expr *RHSExpr) {
6000 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6001 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006002 if (!isLHSPointer && !isRHSPointer) return true;
6003
6004 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006005 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6006 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006007
6008 // Check for arithmetic on pointers to incomplete types.
6009 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6010 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6011 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006012 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6013 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6014 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006015
6016 return !S.getLangOptions().CPlusPlus;
6017 }
6018
6019 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6020 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6021 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006022 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6023 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6024 RHSExpr);
6025 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006026
6027 return !S.getLangOptions().CPlusPlus;
6028 }
6029
Richard Trieu4ae7e972011-09-06 21:13:51 +00006030 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6031 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006032
Chandler Carruthc9332212011-06-27 08:02:19 +00006033 return true;
6034}
6035
Richard Trieub10c6312011-09-01 22:53:23 +00006036/// \brief Check bad cases where we step over interface counts.
6037static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6038 SourceLocation OpLoc,
6039 Expr *Op) {
6040 assert(Op->getType()->isAnyPointerType());
6041 QualType PointeeTy = Op->getType()->getPointeeType();
6042 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6043 return true;
6044
6045 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6046 << PointeeTy << Op->getSourceRange();
6047 return false;
6048}
6049
Richard Trieu993f3ab2011-09-12 18:08:02 +00006050/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006051static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006052 Expr *LHSExpr, Expr *RHSExpr) {
6053 assert(LHSExpr->getType()->isAnyPointerType());
6054 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006055 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006056 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6057 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006058}
6059
Chris Lattnerfaa54172010-01-12 21:23:57 +00006060QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006061 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006062 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6063
Richard Trieu4ae7e972011-09-06 21:13:51 +00006064 if (LHS.get()->getType()->isVectorType() ||
6065 RHS.get()->getType()->isVectorType()) {
6066 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006067 if (CompLHSTy) *CompLHSTy = compType;
6068 return compType;
6069 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006070
Richard Trieu4ae7e972011-09-06 21:13:51 +00006071 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6072 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006073 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006074
Steve Naroffe4718892007-04-27 18:30:00 +00006075 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006076 if (LHS.get()->getType()->isArithmeticType() &&
6077 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006078 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006079 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006080 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006081
Eli Friedman8e122982008-05-18 18:08:51 +00006082 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006083 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006084 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006085 std::swap(PExp, IExp);
6086
Richard Trieub420bca2011-09-12 18:37:54 +00006087 if (!PExp->getType()->isAnyPointerType())
6088 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006089
Richard Trieub420bca2011-09-12 18:37:54 +00006090 if (!IExp->getType()->isIntegerType())
6091 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006092
Richard Trieub420bca2011-09-12 18:37:54 +00006093 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6094 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006095
Richard Trieub420bca2011-09-12 18:37:54 +00006096 // Diagnose bad cases where we step over interface counts.
6097 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6098 return QualType();
6099
6100 // Check array bounds for pointer arithemtic
6101 CheckArrayAccess(PExp, IExp);
6102
6103 if (CompLHSTy) {
6104 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6105 if (LHSTy.isNull()) {
6106 LHSTy = LHS.get()->getType();
6107 if (LHSTy->isPromotableIntegerType())
6108 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006109 }
Richard Trieub420bca2011-09-12 18:37:54 +00006110 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006111 }
6112
Richard Trieub420bca2011-09-12 18:37:54 +00006113 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006114}
6115
Chris Lattner2a3569b2008-04-07 05:30:13 +00006116// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006117QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006118 SourceLocation Loc,
6119 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006120 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6121
Richard Trieu4ae7e972011-09-06 21:13:51 +00006122 if (LHS.get()->getType()->isVectorType() ||
6123 RHS.get()->getType()->isVectorType()) {
6124 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006125 if (CompLHSTy) *CompLHSTy = compType;
6126 return compType;
6127 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006128
Richard Trieu4ae7e972011-09-06 21:13:51 +00006129 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6130 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006131 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006132
Chris Lattner4d62f422007-12-09 21:53:25 +00006133 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006134
Chris Lattner4d62f422007-12-09 21:53:25 +00006135 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006136 if (LHS.get()->getType()->isArithmeticType() &&
6137 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006138 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006139 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006140 }
Mike Stump11289f42009-09-09 15:08:12 +00006141
Chris Lattner4d62f422007-12-09 21:53:25 +00006142 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006143 if (LHS.get()->getType()->isAnyPointerType()) {
6144 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006145
Chris Lattner12bdebb2009-04-24 23:50:08 +00006146 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006147 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006148 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006149
Chris Lattner4d62f422007-12-09 21:53:25 +00006150 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006151 if (RHS.get()->getType()->isIntegerType()) {
6152 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006153 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006154
Richard Trieu4ae7e972011-09-06 21:13:51 +00006155 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006156 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6157 OK_Ordinary, IExpr->getExprLoc());
6158 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006159 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006160
Richard Trieu4ae7e972011-09-06 21:13:51 +00006161 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6162 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006163 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006164
Chris Lattner4d62f422007-12-09 21:53:25 +00006165 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006166 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006167 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006168 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006169
Eli Friedman168fe152009-05-16 13:54:38 +00006170 if (getLangOptions().CPlusPlus) {
6171 // Pointee types must be the same: C++ [expr.add]
6172 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006173 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006174 }
6175 } else {
6176 // Pointee types must be compatible C99 6.5.6p3
6177 if (!Context.typesAreCompatible(
6178 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6179 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006180 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006181 return QualType();
6182 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006183 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006184
Chandler Carruthc9332212011-06-27 08:02:19 +00006185 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006186 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006187 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006188
Richard Trieu4ae7e972011-09-06 21:13:51 +00006189 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006190 return Context.getPointerDiffType();
6191 }
6192 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006193
Richard Trieu4ae7e972011-09-06 21:13:51 +00006194 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006195}
6196
Douglas Gregor0bf31402010-10-08 23:50:27 +00006197static bool isScopedEnumerationType(QualType T) {
6198 if (const EnumType *ET = dyn_cast<EnumType>(T))
6199 return ET->getDecl()->isScoped();
6200 return false;
6201}
6202
Richard Trieue4a19fb2011-09-06 21:21:28 +00006203static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006204 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006205 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006206 llvm::APSInt Right;
6207 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006208 if (RHS.get()->isValueDependent() ||
6209 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006210 return;
6211
6212 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006213 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006214 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006215 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006216 return;
6217 }
6218 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006219 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006220 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006221 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006222 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006223 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006224 return;
6225 }
6226 if (Opc != BO_Shl)
6227 return;
6228
6229 // When left shifting an ICE which is signed, we can check for overflow which
6230 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6231 // integers have defined behavior modulo one more than the maximum value
6232 // representable in the result type, so never warn for those.
6233 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006234 if (LHS.get()->isValueDependent() ||
6235 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6236 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006237 return;
6238 llvm::APInt ResultBits =
6239 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6240 if (LeftBits.uge(ResultBits))
6241 return;
6242 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6243 Result = Result.shl(Right);
6244
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006245 // Print the bit representation of the signed integer as an unsigned
6246 // hexadecimal number.
6247 llvm::SmallString<40> HexResult;
6248 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6249
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006250 // If we are only missing a sign bit, this is less likely to result in actual
6251 // bugs -- if the result is cast back to an unsigned type, it will have the
6252 // expected value. Thus we place this behind a different warning that can be
6253 // turned off separately if needed.
6254 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006255 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006256 << HexResult.str() << LHSType
6257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006258 return;
6259 }
6260
6261 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006262 << HexResult.str() << Result.getMinSignedBits() << LHSType
6263 << Left.getBitWidth() << LHS.get()->getSourceRange()
6264 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006265}
6266
Chris Lattner2a3569b2008-04-07 05:30:13 +00006267// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006268QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006269 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006270 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006271 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6272
Chris Lattner5c11c412007-12-12 05:47:28 +00006273 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006274 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6275 !RHS.get()->getType()->hasIntegerRepresentation())
6276 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006277
Douglas Gregor0bf31402010-10-08 23:50:27 +00006278 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6279 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006280 if (isScopedEnumerationType(LHS.get()->getType()) ||
6281 isScopedEnumerationType(RHS.get()->getType())) {
6282 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006283 }
6284
Nate Begemane46ee9a2009-10-25 02:26:48 +00006285 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006286 if (LHS.get()->getType()->isVectorType() ||
6287 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006288 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006289
Chris Lattner5c11c412007-12-12 05:47:28 +00006290 // Shifts don't perform usual arithmetic conversions, they just do integer
6291 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006292
John McCall57cdd882010-12-16 19:28:59 +00006293 // For the LHS, do usual unary conversions, but then reset them away
6294 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006295 ExprResult OldLHS = LHS;
6296 LHS = UsualUnaryConversions(LHS.take());
6297 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006298 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006299 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006300 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006301
6302 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006303 RHS = UsualUnaryConversions(RHS.take());
6304 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006305 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006306
Ryan Flynnf53fab82009-08-07 16:20:20 +00006307 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006308 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006309
Chris Lattner5c11c412007-12-12 05:47:28 +00006310 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006311 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006312}
6313
Chandler Carruth17773fc2010-07-10 12:30:03 +00006314static bool IsWithinTemplateSpecialization(Decl *D) {
6315 if (DeclContext *DC = D->getDeclContext()) {
6316 if (isa<ClassTemplateSpecializationDecl>(DC))
6317 return true;
6318 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6319 return FD->isFunctionTemplateSpecialization();
6320 }
6321 return false;
6322}
6323
Richard Trieueea56f72011-09-02 03:48:46 +00006324/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006325static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6326 ExprResult &RHS) {
6327 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6328 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006329
6330 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6331 if (!LHSEnumType)
6332 return;
6333 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6334 if (!RHSEnumType)
6335 return;
6336
6337 // Ignore anonymous enums.
6338 if (!LHSEnumType->getDecl()->getIdentifier())
6339 return;
6340 if (!RHSEnumType->getDecl()->getIdentifier())
6341 return;
6342
6343 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6344 return;
6345
6346 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6347 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006348 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006349}
6350
Richard Trieudd82a5c2011-09-02 02:55:45 +00006351/// \brief Diagnose bad pointer comparisons.
6352static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006353 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006354 bool IsError) {
6355 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006356 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006357 << LHS.get()->getType() << RHS.get()->getType()
6358 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006359}
6360
6361/// \brief Returns false if the pointers are converted to a composite type,
6362/// true otherwise.
6363static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006364 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006365 // C++ [expr.rel]p2:
6366 // [...] Pointer conversions (4.10) and qualification
6367 // conversions (4.4) are performed on pointer operands (or on
6368 // a pointer operand and a null pointer constant) to bring
6369 // them to their composite pointer type. [...]
6370 //
6371 // C++ [expr.eq]p1 uses the same notion for (in)equality
6372 // comparisons of pointers.
6373
6374 // C++ [expr.eq]p2:
6375 // In addition, pointers to members can be compared, or a pointer to
6376 // member and a null pointer constant. Pointer to member conversions
6377 // (4.11) and qualification conversions (4.4) are performed to bring
6378 // them to a common type. If one operand is a null pointer constant,
6379 // the common type is the type of the other operand. Otherwise, the
6380 // common type is a pointer to member type similar (4.4) to the type
6381 // of one of the operands, with a cv-qualification signature (4.4)
6382 // that is the union of the cv-qualification signatures of the operand
6383 // types.
6384
Richard Trieu1762d7c2011-09-06 21:27:33 +00006385 QualType LHSType = LHS.get()->getType();
6386 QualType RHSType = RHS.get()->getType();
6387 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6388 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006389
6390 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006391 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006392 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006393 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006394 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006395 return true;
6396 }
6397
6398 if (NonStandardCompositeType)
6399 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006400 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6401 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006402
Richard Trieu1762d7c2011-09-06 21:27:33 +00006403 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6404 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006405 return false;
6406}
6407
6408static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006409 ExprResult &LHS,
6410 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006411 bool IsError) {
6412 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6413 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006414 << LHS.get()->getType() << RHS.get()->getType()
6415 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006416}
6417
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006418// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006419QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006420 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006421 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006422 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6423
John McCalle3027922010-08-25 11:45:40 +00006424 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006425
Chris Lattner9a152e22009-12-05 05:40:13 +00006426 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006427 if (LHS.get()->getType()->isVectorType() ||
6428 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006429 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006430
Richard Trieub80728f2011-09-06 21:43:51 +00006431 QualType LHSType = LHS.get()->getType();
6432 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006433
Richard Trieub80728f2011-09-06 21:43:51 +00006434 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6435 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006436
Richard Trieub80728f2011-09-06 21:43:51 +00006437 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006438
Richard Trieub80728f2011-09-06 21:43:51 +00006439 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006440 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006441 !LHS.get()->getLocStart().isMacroID() &&
6442 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006443 // For non-floating point types, check for self-comparisons of the form
6444 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6445 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006446 //
6447 // NOTE: Don't warn about comparison expressions resulting from macro
6448 // expansion. Also don't warn about comparisons which are only self
6449 // comparisons within a template specialization. The warnings should catch
6450 // obvious cases in the definition of the template anyways. The idea is to
6451 // warn when the typed comparison operator will always evaluate to the same
6452 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006453 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006454 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006455 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006456 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006457 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006458 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006459 << (Opc == BO_EQ
6460 || Opc == BO_LE
6461 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006462 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006463 !DRL->getDecl()->getType()->isReferenceType() &&
6464 !DRR->getDecl()->getType()->isReferenceType()) {
6465 // what is it always going to eval to?
6466 char always_evals_to;
6467 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006468 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006469 always_evals_to = 0; // false
6470 break;
John McCalle3027922010-08-25 11:45:40 +00006471 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006472 always_evals_to = 1; // true
6473 break;
6474 default:
6475 // best we can say is 'a constant'
6476 always_evals_to = 2; // e.g. array1 <= array2
6477 break;
6478 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006479 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006480 << 1 // array
6481 << always_evals_to);
6482 }
6483 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006484 }
Mike Stump11289f42009-09-09 15:08:12 +00006485
Chris Lattner222b8bd2009-03-08 19:39:53 +00006486 if (isa<CastExpr>(LHSStripped))
6487 LHSStripped = LHSStripped->IgnoreParenCasts();
6488 if (isa<CastExpr>(RHSStripped))
6489 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006490
Chris Lattner222b8bd2009-03-08 19:39:53 +00006491 // Warn about comparisons against a string constant (unless the other
6492 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006493 Expr *literalString = 0;
6494 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006495 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006496 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006497 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006498 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006499 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006500 } else if ((isa<StringLiteral>(RHSStripped) ||
6501 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006502 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006503 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006504 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006505 literalStringStripped = RHSStripped;
6506 }
6507
6508 if (literalString) {
6509 std::string resultComparison;
6510 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006511 case BO_LT: resultComparison = ") < 0"; break;
6512 case BO_GT: resultComparison = ") > 0"; break;
6513 case BO_LE: resultComparison = ") <= 0"; break;
6514 case BO_GE: resultComparison = ") >= 0"; break;
6515 case BO_EQ: resultComparison = ") == 0"; break;
6516 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006517 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006518 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006519
Ted Kremenek3427fac2011-02-23 01:52:04 +00006520 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006521 PDiag(diag::warn_stringcompare)
6522 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006523 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006524 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006525 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006526
Douglas Gregorec170db2010-06-08 19:50:34 +00006527 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006528 if (LHS.get()->getType()->isArithmeticType() &&
6529 RHS.get()->getType()->isArithmeticType()) {
6530 UsualArithmeticConversions(LHS, RHS);
6531 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006532 return QualType();
6533 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006534 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006535 LHS = UsualUnaryConversions(LHS.take());
6536 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006537 return QualType();
6538
Richard Trieub80728f2011-09-06 21:43:51 +00006539 RHS = UsualUnaryConversions(RHS.take());
6540 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006541 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006542 }
6543
Richard Trieub80728f2011-09-06 21:43:51 +00006544 LHSType = LHS.get()->getType();
6545 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006546
Douglas Gregorca63811b2008-11-19 03:25:36 +00006547 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006548 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006549
Richard Trieuba63ce62011-09-09 01:45:06 +00006550 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006551 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006552 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006553 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006554 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006555 if (LHSType->hasFloatingRepresentation())
6556 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006557
Richard Trieub80728f2011-09-06 21:43:51 +00006558 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006559 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006561
Richard Trieub80728f2011-09-06 21:43:51 +00006562 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006563 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006564 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006565 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006566
Douglas Gregorf267edd2010-06-15 21:38:40 +00006567 // All of the following pointer-related warnings are GCC extensions, except
6568 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006569 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006570 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006571 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006572 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006573 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006574
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006575 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006576 if (LCanPointeeTy == RCanPointeeTy)
6577 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006578 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006579 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6580 // Valid unless comparison between non-null pointer and function pointer
6581 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006582 // In a SFINAE context, we treat this as a hard error to maintain
6583 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006584 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6585 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006586 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006587 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006588
6589 if (isSFINAEContext())
6590 return QualType();
6591
Richard Trieub80728f2011-09-06 21:43:51 +00006592 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006593 return ResultTy;
6594 }
6595 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006596
Richard Trieub80728f2011-09-06 21:43:51 +00006597 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006598 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006599 else
6600 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006601 }
Eli Friedman16c209612009-08-23 00:27:47 +00006602 // C99 6.5.9p2 and C99 6.5.8p2
6603 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6604 RCanPointeeTy.getUnqualifiedType())) {
6605 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006606 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006607 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006608 << LHSType << RHSType << LHS.get()->getSourceRange()
6609 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006610 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006611 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006612 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6613 // Valid unless comparison between non-null pointer and function pointer
6614 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006615 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006616 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006617 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006618 } else {
6619 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006620 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006621 }
John McCall7684dde2011-03-11 04:25:25 +00006622 if (LCanPointeeTy != RCanPointeeTy) {
6623 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006624 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006625 else
Richard Trieub80728f2011-09-06 21:43:51 +00006626 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006627 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006628 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006629 }
Mike Stump11289f42009-09-09 15:08:12 +00006630
Sebastian Redl576fd422009-05-10 18:38:11 +00006631 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006632 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006633 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006634 return ResultTy;
6635
Mike Stump11289f42009-09-09 15:08:12 +00006636 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006637 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006638 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006639 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006640 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006641 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6642 RHS = ImpCastExprToType(RHS.take(), LHSType,
6643 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006644 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006645 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006646 return ResultTy;
6647 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006648 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006649 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006650 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006651 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6652 LHS = ImpCastExprToType(LHS.take(), RHSType,
6653 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006654 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006655 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006656 return ResultTy;
6657 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006658
6659 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006660 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006661 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6662 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006663 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006664 else
6665 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006666 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006667
6668 // Handle scoped enumeration types specifically, since they don't promote
6669 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006670 if (LHS.get()->getType()->isEnumeralType() &&
6671 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6672 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006673 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006674 }
Mike Stump11289f42009-09-09 15:08:12 +00006675
Steve Naroff081c7422008-09-04 15:10:53 +00006676 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006677 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006678 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006679 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6680 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006681
Steve Naroff081c7422008-09-04 15:10:53 +00006682 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006683 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006684 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006685 << LHSType << RHSType << LHS.get()->getSourceRange()
6686 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006687 }
Richard Trieub80728f2011-09-06 21:43:51 +00006688 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006689 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006690 }
John Wiegley01296292011-04-08 18:41:53 +00006691
Steve Naroffe18f94c2008-09-28 01:11:11 +00006692 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006693 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006694 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6695 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006696 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006697 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006698 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006699 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006700 ->getPointeeType()->isVoidType())))
6701 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006702 << LHSType << RHSType << LHS.get()->getSourceRange()
6703 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006704 }
John McCall7684dde2011-03-11 04:25:25 +00006705 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006706 LHS = ImpCastExprToType(LHS.take(), RHSType,
6707 RHSType->isPointerType() ? CK_BitCast
6708 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006709 else
John McCall9320b872011-09-09 05:25:32 +00006710 RHS = ImpCastExprToType(RHS.take(), LHSType,
6711 LHSType->isPointerType() ? CK_BitCast
6712 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006713 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006714 }
Steve Naroff081c7422008-09-04 15:10:53 +00006715
Richard Trieub80728f2011-09-06 21:43:51 +00006716 if (LHSType->isObjCObjectPointerType() ||
6717 RHSType->isObjCObjectPointerType()) {
6718 const PointerType *LPT = LHSType->getAs<PointerType>();
6719 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006720 if (LPT || RPT) {
6721 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6722 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006723
Steve Naroff753567f2008-11-17 19:49:16 +00006724 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006725 !Context.typesAreCompatible(LHSType, RHSType)) {
6726 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006727 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006728 }
John McCall7684dde2011-03-11 04:25:25 +00006729 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006730 LHS = ImpCastExprToType(LHS.take(), RHSType,
6731 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006732 else
John McCall9320b872011-09-09 05:25:32 +00006733 RHS = ImpCastExprToType(RHS.take(), LHSType,
6734 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006735 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006736 }
Richard Trieub80728f2011-09-06 21:43:51 +00006737 if (LHSType->isObjCObjectPointerType() &&
6738 RHSType->isObjCObjectPointerType()) {
6739 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6740 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006741 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006742 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006743 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006744 else
Richard Trieub80728f2011-09-06 21:43:51 +00006745 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006746 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006747 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006748 }
Richard Trieub80728f2011-09-06 21:43:51 +00006749 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6750 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006751 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006752 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006753 if ((LHSIsNull && LHSType->isIntegerType()) ||
6754 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006755 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006756 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006757 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006758 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006759 else if (getLangOptions().CPlusPlus) {
6760 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6761 isError = true;
6762 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006763 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006764
Chris Lattnerd99bd522009-08-23 00:03:44 +00006765 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006766 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006767 << LHSType << RHSType << LHS.get()->getSourceRange()
6768 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006769 if (isError)
6770 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006771 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006772
Richard Trieub80728f2011-09-06 21:43:51 +00006773 if (LHSType->isIntegerType())
6774 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006775 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006776 else
Richard Trieub80728f2011-09-06 21:43:51 +00006777 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006778 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006779 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006780 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006781
Steve Naroff4b191572008-09-04 16:56:14 +00006782 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006783 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006784 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6785 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006786 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006787 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006788 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006789 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6790 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006791 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006792 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006793
Richard Trieub80728f2011-09-06 21:43:51 +00006794 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006795}
6796
Nate Begeman191a6b12008-07-14 18:02:46 +00006797/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006798/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006799/// like a scalar comparison, a vector comparison produces a vector of integer
6800/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006801QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006802 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006803 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006804 // Check to make sure we're operating on vectors of the same type and width,
6805 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006806 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006807 if (vType.isNull())
6808 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006809
Richard Trieubcce2f72011-09-07 01:19:57 +00006810 QualType LHSType = LHS.get()->getType();
6811 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006812
Anton Yartsev530deb92011-03-27 15:36:07 +00006813 // If AltiVec, the comparison results in a numeric type, i.e.
6814 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006815 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006816 return Context.getLogicalOperationType();
6817
Nate Begeman191a6b12008-07-14 18:02:46 +00006818 // For non-floating point types, check for self-comparisons of the form
6819 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6820 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006821 if (!LHSType->hasFloatingRepresentation()) {
6822 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6823 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006824 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006825 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006826 PDiag(diag::warn_comparison_always)
6827 << 0 // self-
6828 << 2 // "a constant"
6829 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006830 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006831
Nate Begeman191a6b12008-07-14 18:02:46 +00006832 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006833 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006834 assert (RHSType->hasFloatingRepresentation());
6835 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006836 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006837
Nate Begeman191a6b12008-07-14 18:02:46 +00006838 // Return the type for the comparison, which is the same as vector type for
6839 // integer vectors, or an integer type of identical size and number of
6840 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006841 if (LHSType->hasIntegerRepresentation())
6842 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006843
Richard Trieubcce2f72011-09-07 01:19:57 +00006844 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006845 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006846 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006847 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006848 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006849 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6850
Mike Stump4e1f26a2009-02-19 03:04:26 +00006851 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006852 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006853 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6854}
6855
Steve Naroff218bc2b2007-05-04 21:54:46 +00006856inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006857 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006858 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6859
Richard Trieubcce2f72011-09-07 01:19:57 +00006860 if (LHS.get()->getType()->isVectorType() ||
6861 RHS.get()->getType()->isVectorType()) {
6862 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6863 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006864 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006865
Richard Trieubcce2f72011-09-07 01:19:57 +00006866 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006867 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006868
Richard Trieubcce2f72011-09-07 01:19:57 +00006869 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6870 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006871 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006872 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006873 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006874 LHS = LHSResult.take();
6875 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006876
Richard Trieubcce2f72011-09-07 01:19:57 +00006877 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6878 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006879 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006880 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006881}
6882
Steve Naroff218bc2b2007-05-04 21:54:46 +00006883inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006884 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006885
6886 // Diagnose cases where the user write a logical and/or but probably meant a
6887 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6888 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006889 if (LHS.get()->getType()->isIntegerType() &&
6890 !LHS.get()->getType()->isBooleanType() &&
6891 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006892 // Don't warn in macros or template instantiations.
6893 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006894 // If the RHS can be constant folded, and if it constant folds to something
6895 // that isn't 0 or 1 (which indicate a potential logical operation that
6896 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006897 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006898 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006899 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6900 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006901 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6902 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006903 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006904 << (Opc == BO_LAnd ? "&&" : "||");
6905 // Suggest replacing the logical operator with the bitwise version
6906 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6907 << (Opc == BO_LAnd ? "&" : "|")
6908 << FixItHint::CreateReplacement(SourceRange(
6909 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6910 getLangOptions())),
6911 Opc == BO_LAnd ? "&" : "|");
6912 if (Opc == BO_LAnd)
6913 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6914 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6915 << FixItHint::CreateRemoval(
6916 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006917 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006918 0, getSourceManager(),
6919 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006920 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006921 }
Chris Lattner938533d2010-07-24 01:10:11 +00006922 }
Chris Lattner8406c512010-07-13 19:41:32 +00006923
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006924 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006925 LHS = UsualUnaryConversions(LHS.take());
6926 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006927 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006928
Richard Trieubcce2f72011-09-07 01:19:57 +00006929 RHS = UsualUnaryConversions(RHS.take());
6930 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006931 return QualType();
6932
Richard Trieubcce2f72011-09-07 01:19:57 +00006933 if (!LHS.get()->getType()->isScalarType() ||
6934 !RHS.get()->getType()->isScalarType())
6935 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006936
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006937 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006938 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006939
John McCall4a2429a2010-06-04 00:29:51 +00006940 // The following is safe because we only use this method for
6941 // non-overloadable operands.
6942
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006943 // C++ [expr.log.and]p1
6944 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006945 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006946 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6947 if (LHSRes.isInvalid())
6948 return InvalidOperands(Loc, LHS, RHS);
6949 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006950
Richard Trieubcce2f72011-09-07 01:19:57 +00006951 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6952 if (RHSRes.isInvalid())
6953 return InvalidOperands(Loc, LHS, RHS);
6954 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006955
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006956 // C++ [expr.log.and]p2
6957 // C++ [expr.log.or]p2
6958 // The result is a bool.
6959 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006960}
6961
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006962/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6963/// is a read-only property; return true if so. A readonly property expression
6964/// depends on various declarations and thus must be treated specially.
6965///
Mike Stump11289f42009-09-09 15:08:12 +00006966static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006967 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6968 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006969 if (PropExpr->isImplicitProperty()) return false;
6970
6971 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6972 QualType BaseType = PropExpr->isSuperReceiver() ?
6973 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006974 PropExpr->getBase()->getType();
6975
John McCallb7bd14f2010-12-02 01:19:52 +00006976 if (const ObjCObjectPointerType *OPT =
6977 BaseType->getAsObjCInterfacePointerType())
6978 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6979 if (S.isPropertyReadonly(PDecl, IFace))
6980 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006981 }
6982 return false;
6983}
6984
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006985static bool IsConstProperty(Expr *E, Sema &S) {
6986 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6987 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6988 if (PropExpr->isImplicitProperty()) return false;
6989
6990 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6991 QualType T = PDecl->getType();
6992 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006993 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006994 CanQualType CT = S.Context.getCanonicalType(T);
6995 return CT.isConstQualified();
6996 }
6997 return false;
6998}
6999
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007000static bool IsReadonlyMessage(Expr *E, Sema &S) {
7001 if (E->getStmtClass() != Expr::MemberExprClass)
7002 return false;
7003 const MemberExpr *ME = cast<MemberExpr>(E);
7004 NamedDecl *Member = ME->getMemberDecl();
7005 if (isa<FieldDecl>(Member)) {
7006 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7007 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7008 return false;
7009 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7010 }
7011 return false;
7012}
7013
Chris Lattner30bd3272008-11-18 01:22:49 +00007014/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7015/// emit an error and return true. If so, return false.
7016static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007017 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007018 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007019 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007020 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7021 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007022 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7023 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007024 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7025 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007026 if (IsLV == Expr::MLV_Valid)
7027 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007028
Chris Lattner30bd3272008-11-18 01:22:49 +00007029 unsigned Diag = 0;
7030 bool NeedType = false;
7031 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007032 case Expr::MLV_ConstQualified:
7033 Diag = diag::err_typecheck_assign_const;
7034
John McCalld4631322011-06-17 06:42:21 +00007035 // In ARC, use some specialized diagnostics for occasions where we
7036 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007037 if (S.getLangOptions().ObjCAutoRefCount) {
7038 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7039 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7040 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7041
John McCalld4631322011-06-17 06:42:21 +00007042 // Use the normal diagnostic if it's pseudo-__strong but the
7043 // user actually wrote 'const'.
7044 if (var->isARCPseudoStrong() &&
7045 (!var->getTypeSourceInfo() ||
7046 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7047 // There are two pseudo-strong cases:
7048 // - self
John McCall31168b02011-06-15 23:02:42 +00007049 ObjCMethodDecl *method = S.getCurMethodDecl();
7050 if (method && var == method->getSelfDecl())
7051 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007052
7053 // - fast enumeration variables
7054 else
John McCall31168b02011-06-15 23:02:42 +00007055 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007056
John McCall31168b02011-06-15 23:02:42 +00007057 SourceRange Assign;
7058 if (Loc != OrigLoc)
7059 Assign = SourceRange(OrigLoc, OrigLoc);
7060 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7061 // We need to preserve the AST regardless, so migration tool
7062 // can do its job.
7063 return false;
7064 }
7065 }
7066 }
7067
7068 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007069 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007070 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7071 NeedType = true;
7072 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007073 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007074 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7075 NeedType = true;
7076 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007077 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007078 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7079 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007080 case Expr::MLV_Valid:
7081 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007082 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007083 case Expr::MLV_MemberFunction:
7084 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007085 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7086 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007087 case Expr::MLV_IncompleteType:
7088 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007089 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007090 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007091 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007092 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007093 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7094 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007095 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007096 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7097 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007098 case Expr::MLV_ReadonlyProperty:
7099 Diag = diag::error_readonly_property_assignment;
7100 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007101 case Expr::MLV_NoSetterProperty:
7102 Diag = diag::error_nosetter_property_assignment;
7103 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007104 case Expr::MLV_InvalidMessageExpression:
7105 Diag = diag::error_readonly_message_assignment;
7106 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007107 case Expr::MLV_SubObjCPropertySetting:
7108 Diag = diag::error_no_subobject_property_setting;
7109 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007110 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007111
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007112 SourceRange Assign;
7113 if (Loc != OrigLoc)
7114 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007115 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007116 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007117 else
Mike Stump11289f42009-09-09 15:08:12 +00007118 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007119 return true;
7120}
7121
7122
7123
7124// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007125QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007126 SourceLocation Loc,
7127 QualType CompoundType) {
7128 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007129 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007130 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007131
Richard Trieuda4f43a62011-09-07 01:33:52 +00007132 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007133 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7134 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007135 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007136 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007137 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007138 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007139 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7140 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007141 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7142 if (LHSResult.isInvalid())
7143 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007144 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007145 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007146 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007147 if (RHS.isInvalid())
7148 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007149 // Special case of NSObject attributes on c-style pointer types.
7150 if (ConvTy == IncompatiblePointer &&
7151 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007152 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007153 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007154 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007155 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007156
John McCall7decc9e2010-11-18 06:31:45 +00007157 if (ConvTy == Compatible &&
7158 getLangOptions().ObjCNonFragileABI &&
7159 LHSType->isObjCObjectType())
7160 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7161 << LHSType;
7162
Chris Lattnerea714382008-08-21 18:04:13 +00007163 // If the RHS is a unary plus or minus, check to see if they = and + are
7164 // right next to each other. If so, the user may have typo'd "x =+ 4"
7165 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007166 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007167 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7168 RHSCheck = ICE->getSubExpr();
7169 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007170 if ((UO->getOpcode() == UO_Plus ||
7171 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007172 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007173 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007174 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007175 // And there is a space or other character before the subexpr of the
7176 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007177 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007178 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007179 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007180 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007181 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007182 }
Chris Lattnerea714382008-08-21 18:04:13 +00007183 }
John McCall31168b02011-06-15 23:02:42 +00007184
7185 if (ConvTy == Compatible) {
7186 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007187 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007188 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007189 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007190 }
Chris Lattnerea714382008-08-21 18:04:13 +00007191 } else {
7192 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007193 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007194 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007195
Chris Lattner326f7572008-11-18 01:30:42 +00007196 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007197 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007198 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007199
Richard Trieuda4f43a62011-09-07 01:33:52 +00007200 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007201
Steve Naroff98cf3e92007-06-06 18:38:38 +00007202 // C99 6.5.16p3: The type of an assignment expression is the type of the
7203 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007204 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007205 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7206 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007207 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007208 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007209 return (getLangOptions().CPlusPlus
7210 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007211}
7212
Chris Lattner326f7572008-11-18 01:30:42 +00007213// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007214static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007215 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007216 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007217
John McCall3aef3d82011-04-10 19:13:55 +00007218 LHS = S.CheckPlaceholderExpr(LHS.take());
7219 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007220 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007221 return QualType();
7222
John McCall73d36182010-10-12 07:14:40 +00007223 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7224 // operands, but not unary promotions.
7225 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007226
John McCall34376a62010-12-04 03:47:34 +00007227 // So we treat the LHS as a ignored value, and in C++ we allow the
7228 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007229 LHS = S.IgnoredValueConversions(LHS.take());
7230 if (LHS.isInvalid())
7231 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007232
7233 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007234 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7235 if (RHS.isInvalid())
7236 return QualType();
7237 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007238 S.RequireCompleteType(Loc, RHS.get()->getType(),
7239 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007240 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007241
John Wiegley01296292011-04-08 18:41:53 +00007242 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007243}
7244
Steve Naroff7a5af782007-07-13 16:58:59 +00007245/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7246/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007247static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7248 ExprValueKind &VK,
7249 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007250 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007251 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007252 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007253
Chris Lattner6b0cf142008-11-21 07:05:48 +00007254 QualType ResType = Op->getType();
7255 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007256
John McCall4bc41ae2010-11-18 19:01:18 +00007257 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007258 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007259 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007260 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007261 return QualType();
7262 }
7263 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007264 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007265 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007266 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007267 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007268 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007269 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007270 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007271
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007272 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007273 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007274 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007275 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007276 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007277 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007278 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007279 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007280 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007281 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007282 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007283 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007284 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7285 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007286 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007287 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007288 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007289 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007290 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007291 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007292 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007293 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007294 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007295 // In C++, a prefix increment is the same type as the operand. Otherwise
7296 // (in C or with postfix), the increment is the unqualified type of the
7297 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007298 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007299 VK = VK_LValue;
7300 return ResType;
7301 } else {
7302 VK = VK_RValue;
7303 return ResType.getUnqualifiedType();
7304 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007305}
7306
John Wiegley01296292011-04-08 18:41:53 +00007307ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007308 assert(E->getValueKind() == VK_LValue &&
7309 E->getObjectKind() == OK_ObjCProperty);
7310 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7311
Douglas Gregor33823722011-06-11 01:09:30 +00007312 QualType T = E->getType();
7313 QualType ReceiverType;
7314 if (PRE->isObjectReceiver())
7315 ReceiverType = PRE->getBase()->getType();
7316 else if (PRE->isSuperReceiver())
7317 ReceiverType = PRE->getSuperReceiverType();
7318 else
7319 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7320
John McCall34376a62010-12-04 03:47:34 +00007321 ExprValueKind VK = VK_RValue;
7322 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007323 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007324 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007325 T = getMessageSendResultType(ReceiverType, GetterMethod,
7326 PRE->isClassReceiver(),
7327 PRE->isSuperReceiver());
7328 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007329 }
7330 else {
7331 Diag(PRE->getLocation(), diag::err_getter_not_found)
7332 << PRE->getBase()->getType();
7333 }
John McCall34376a62010-12-04 03:47:34 +00007334 }
Douglas Gregor33823722011-06-11 01:09:30 +00007335
7336 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007337 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007338
7339 ExprResult Result = MaybeBindToTemporary(E);
7340 if (!Result.isInvalid())
7341 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007342
7343 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007344}
7345
Richard Trieucfc491d2011-08-02 04:35:43 +00007346void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7347 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007348 assert(LHS.get()->getValueKind() == VK_LValue &&
7349 LHS.get()->getObjectKind() == OK_ObjCProperty);
7350 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007351
John McCall31168b02011-06-15 23:02:42 +00007352 bool Consumed = false;
7353
John Wiegley01296292011-04-08 18:41:53 +00007354 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007355 // If using property-dot syntax notation for assignment, and there is a
7356 // setter, RHS expression is being passed to the setter argument. So,
7357 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007358 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007359 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7360 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007361 Consumed = (getLangOptions().ObjCAutoRefCount &&
7362 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007363
7364 // Otherwise, if the getter returns an l-value, just call that.
7365 } else {
John Wiegley01296292011-04-08 18:41:53 +00007366 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007367 ExprValueKind VK = Expr::getValueKindForType(Result);
7368 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007369 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7370 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007371 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007372 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007373 }
John McCall31168b02011-06-15 23:02:42 +00007374 } else if (getLangOptions().ObjCAutoRefCount) {
7375 const ObjCMethodDecl *setter
7376 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7377 if (setter) {
7378 ObjCMethodDecl::param_iterator P = setter->param_begin();
7379 LHSTy = (*P)->getType();
7380 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7381 }
John McCall34376a62010-12-04 03:47:34 +00007382 }
7383
John McCall31168b02011-06-15 23:02:42 +00007384 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7385 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007386 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007387 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007388 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007389 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007390 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007391 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7392 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7393 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007394 }
7395}
7396
7397
Anders Carlsson806700f2008-02-01 07:15:58 +00007398/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007399/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007400/// where the declaration is needed for type checking. We only need to
7401/// handle cases when the expression references a function designator
7402/// or is an lvalue. Here are some examples:
7403/// - &(x) => x
7404/// - &*****f => f for f a function designator.
7405/// - &s.xx => s
7406/// - &s.zz[1].yy -> s, if zz is an array
7407/// - *(x + 1) -> x, if x is an array
7408/// - &"123"[2] -> 0
7409/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007410static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007411 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007412 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007413 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007414 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007415 // If this is an arrow operator, the address is an offset from
7416 // the base's value, so the object the base refers to is
7417 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007418 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007419 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007420 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007421 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007422 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007423 // FIXME: This code shouldn't be necessary! We should catch the implicit
7424 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007425 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7426 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7427 if (ICE->getSubExpr()->getType()->isArrayType())
7428 return getPrimaryDecl(ICE->getSubExpr());
7429 }
7430 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007431 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007432 case Stmt::UnaryOperatorClass: {
7433 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007434
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007435 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007436 case UO_Real:
7437 case UO_Imag:
7438 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007439 return getPrimaryDecl(UO->getSubExpr());
7440 default:
7441 return 0;
7442 }
7443 }
Steve Naroff47500512007-04-19 23:00:49 +00007444 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007445 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007446 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007447 // If the result of an implicit cast is an l-value, we care about
7448 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007449 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007450 default:
7451 return 0;
7452 }
7453}
7454
Richard Trieu5f376f62011-09-07 21:46:33 +00007455namespace {
7456 enum {
7457 AO_Bit_Field = 0,
7458 AO_Vector_Element = 1,
7459 AO_Property_Expansion = 2,
7460 AO_Register_Variable = 3,
7461 AO_No_Error = 4
7462 };
7463}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007464/// \brief Diagnose invalid operand for address of operations.
7465///
7466/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007467static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7468 Expr *E, unsigned Type) {
7469 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7470}
7471
Steve Naroff47500512007-04-19 23:00:49 +00007472/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007473/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007474/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007475/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007476/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007477/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007478/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007479static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7480 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007481 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007482 return S.Context.DependentTy;
7483 if (OrigOp->getType() == S.Context.OverloadTy)
7484 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007485 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7486 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007487 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7488 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7489 << OrigOp->getSourceRange();
7490 return QualType();
7491 }
John McCall8d08b9b2010-08-27 09:08:28 +00007492
John McCall2979fe02011-04-12 00:42:48 +00007493 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007494
John McCall8d08b9b2010-08-27 09:08:28 +00007495 // Make sure to ignore parentheses in subsequent checks
7496 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007497
John McCall4bc41ae2010-11-18 19:01:18 +00007498 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007499 // Implement C99-only parts of addressof rules.
7500 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007501 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007502 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7503 // (assuming the deref expression is valid).
7504 return uOp->getSubExpr()->getType();
7505 }
7506 // Technically, there should be a check for array subscript
7507 // expressions here, but the result of one is always an lvalue anyway.
7508 }
John McCallf3a88602011-02-03 08:15:49 +00007509 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007510 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007511 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007512
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007513 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007514 bool sfinae = S.isSFINAEContext();
7515 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7516 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007517 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007518 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007519 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007520 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007521 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007522 } else if (lval == Expr::LV_MemberFunction) {
7523 // If it's an instance method, make a member pointer.
7524 // The expression must have exactly the form &A::foo.
7525
7526 // If the underlying expression isn't a decl ref, give up.
7527 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007528 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007529 << OrigOp->getSourceRange();
7530 return QualType();
7531 }
7532 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7533 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7534
7535 // The id-expression was parenthesized.
7536 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007537 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007538 << OrigOp->getSourceRange();
7539
7540 // The method was named without a qualifier.
7541 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007542 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007543 << op->getSourceRange();
7544 }
7545
John McCall4bc41ae2010-11-18 19:01:18 +00007546 return S.Context.getMemberPointerType(op->getType(),
7547 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007548 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007549 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007550 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007551 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007552 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007553 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007554 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007555 return QualType();
7556 }
John McCall086a4642010-11-24 05:12:34 +00007557 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007558 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007559 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007560 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007561 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007562 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007563 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007564 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007565 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007566 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007567 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007568 // with the register storage-class specifier.
7569 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007570 // in C++ it is not error to take address of a register
7571 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007572 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007573 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007574 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007575 }
John McCalld14a8642009-11-21 08:51:07 +00007576 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007577 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007578 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007579 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007580 // Could be a pointer to member, though, if there is an explicit
7581 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007582 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007583 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007584 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007585 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007586 S.Diag(OpLoc,
7587 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007588 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007589 return QualType();
7590 }
Mike Stump11289f42009-09-09 15:08:12 +00007591
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007592 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7593 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007594 return S.Context.getMemberPointerType(op->getType(),
7595 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007596 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007597 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007598 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007599 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007600 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007601
Richard Trieu5f376f62011-09-07 21:46:33 +00007602 if (AddressOfError != AO_No_Error) {
7603 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7604 return QualType();
7605 }
7606
Eli Friedmance7f9002009-05-16 23:27:50 +00007607 if (lval == Expr::LV_IncompleteVoidType) {
7608 // Taking the address of a void variable is technically illegal, but we
7609 // allow it in cases which are otherwise valid.
7610 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007611 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007612 }
7613
Steve Naroff47500512007-04-19 23:00:49 +00007614 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007615 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007616 return S.Context.getObjCObjectPointerType(op->getType());
7617 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007618}
7619
Chris Lattner9156f1b2010-07-05 19:17:26 +00007620/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007621static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7622 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007623 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007624 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007625
John Wiegley01296292011-04-08 18:41:53 +00007626 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7627 if (ConvResult.isInvalid())
7628 return QualType();
7629 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007630 QualType OpTy = Op->getType();
7631 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007632
7633 if (isa<CXXReinterpretCastExpr>(Op)) {
7634 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7635 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7636 Op->getSourceRange());
7637 }
7638
Chris Lattner9156f1b2010-07-05 19:17:26 +00007639 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7640 // is an incomplete type or void. It would be possible to warn about
7641 // dereferencing a void pointer, but it's completely well-defined, and such a
7642 // warning is unlikely to catch any mistakes.
7643 if (const PointerType *PT = OpTy->getAs<PointerType>())
7644 Result = PT->getPointeeType();
7645 else if (const ObjCObjectPointerType *OPT =
7646 OpTy->getAs<ObjCObjectPointerType>())
7647 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007648 else {
John McCall3aef3d82011-04-10 19:13:55 +00007649 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007650 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007651 if (PR.take() != Op)
7652 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007653 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007654
Chris Lattner9156f1b2010-07-05 19:17:26 +00007655 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007656 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007657 << OpTy << Op->getSourceRange();
7658 return QualType();
7659 }
John McCall4bc41ae2010-11-18 19:01:18 +00007660
7661 // Dereferences are usually l-values...
7662 VK = VK_LValue;
7663
7664 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007665 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007666 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007667
7668 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007669}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007670
John McCalle3027922010-08-25 11:45:40 +00007671static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007672 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007673 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007674 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007675 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007676 case tok::periodstar: Opc = BO_PtrMemD; break;
7677 case tok::arrowstar: Opc = BO_PtrMemI; break;
7678 case tok::star: Opc = BO_Mul; break;
7679 case tok::slash: Opc = BO_Div; break;
7680 case tok::percent: Opc = BO_Rem; break;
7681 case tok::plus: Opc = BO_Add; break;
7682 case tok::minus: Opc = BO_Sub; break;
7683 case tok::lessless: Opc = BO_Shl; break;
7684 case tok::greatergreater: Opc = BO_Shr; break;
7685 case tok::lessequal: Opc = BO_LE; break;
7686 case tok::less: Opc = BO_LT; break;
7687 case tok::greaterequal: Opc = BO_GE; break;
7688 case tok::greater: Opc = BO_GT; break;
7689 case tok::exclaimequal: Opc = BO_NE; break;
7690 case tok::equalequal: Opc = BO_EQ; break;
7691 case tok::amp: Opc = BO_And; break;
7692 case tok::caret: Opc = BO_Xor; break;
7693 case tok::pipe: Opc = BO_Or; break;
7694 case tok::ampamp: Opc = BO_LAnd; break;
7695 case tok::pipepipe: Opc = BO_LOr; break;
7696 case tok::equal: Opc = BO_Assign; break;
7697 case tok::starequal: Opc = BO_MulAssign; break;
7698 case tok::slashequal: Opc = BO_DivAssign; break;
7699 case tok::percentequal: Opc = BO_RemAssign; break;
7700 case tok::plusequal: Opc = BO_AddAssign; break;
7701 case tok::minusequal: Opc = BO_SubAssign; break;
7702 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7703 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7704 case tok::ampequal: Opc = BO_AndAssign; break;
7705 case tok::caretequal: Opc = BO_XorAssign; break;
7706 case tok::pipeequal: Opc = BO_OrAssign; break;
7707 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007708 }
7709 return Opc;
7710}
7711
John McCalle3027922010-08-25 11:45:40 +00007712static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007713 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007714 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007715 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007716 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007717 case tok::plusplus: Opc = UO_PreInc; break;
7718 case tok::minusminus: Opc = UO_PreDec; break;
7719 case tok::amp: Opc = UO_AddrOf; break;
7720 case tok::star: Opc = UO_Deref; break;
7721 case tok::plus: Opc = UO_Plus; break;
7722 case tok::minus: Opc = UO_Minus; break;
7723 case tok::tilde: Opc = UO_Not; break;
7724 case tok::exclaim: Opc = UO_LNot; break;
7725 case tok::kw___real: Opc = UO_Real; break;
7726 case tok::kw___imag: Opc = UO_Imag; break;
7727 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007728 }
7729 return Opc;
7730}
7731
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007732/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7733/// This warning is only emitted for builtin assignment operations. It is also
7734/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007735static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007736 SourceLocation OpLoc) {
7737 if (!S.ActiveTemplateInstantiations.empty())
7738 return;
7739 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7740 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007741 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7742 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7743 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7744 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7745 if (!LHSDeclRef || !RHSDeclRef ||
7746 LHSDeclRef->getLocation().isMacroID() ||
7747 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007748 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007749 const ValueDecl *LHSDecl =
7750 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7751 const ValueDecl *RHSDecl =
7752 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7753 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007754 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007755 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007756 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007757 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007758 if (RefTy->getPointeeType().isVolatileQualified())
7759 return;
7760
7761 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007762 << LHSDeclRef->getType()
7763 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007764}
7765
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007766/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7767/// operator @p Opc at location @c TokLoc. This routine only supports
7768/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007769ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007770 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007771 Expr *LHSExpr, Expr *RHSExpr) {
7772 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007773 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007774 // The following two variables are used for compound assignment operators
7775 QualType CompLHSTy; // Type of LHS after promotions for computation
7776 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007777 ExprValueKind VK = VK_RValue;
7778 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007779
Douglas Gregor1beec452011-03-12 01:48:56 +00007780 // Check if a 'foo<int>' involved in a binary op, identifies a single
7781 // function unambiguously (i.e. an lvalue ala 13.4)
7782 // But since an assignment can trigger target based overload, exclude it in
7783 // our blind search. i.e:
7784 // template<class T> void f(); template<class T, class U> void f(U);
7785 // f<int> == 0; // resolve f<int> blindly
7786 // void (*p)(int); p = f<int>; // resolve f<int> using target
7787 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007788 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007789 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007790 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007791
Richard Trieu4a287fb2011-09-07 01:49:20 +00007792 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007793 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007794 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007795 }
7796
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007797 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007798 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007799 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007800 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007801 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7802 VK = LHS.get()->getValueKind();
7803 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007804 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007805 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007806 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007807 break;
John McCalle3027922010-08-25 11:45:40 +00007808 case BO_PtrMemD:
7809 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007810 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007811 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007812 break;
John McCalle3027922010-08-25 11:45:40 +00007813 case BO_Mul:
7814 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007815 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007816 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007817 break;
John McCalle3027922010-08-25 11:45:40 +00007818 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007819 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007820 break;
John McCalle3027922010-08-25 11:45:40 +00007821 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007822 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007823 break;
John McCalle3027922010-08-25 11:45:40 +00007824 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007825 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007826 break;
John McCalle3027922010-08-25 11:45:40 +00007827 case BO_Shl:
7828 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007829 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007830 break;
John McCalle3027922010-08-25 11:45:40 +00007831 case BO_LE:
7832 case BO_LT:
7833 case BO_GE:
7834 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007835 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007836 break;
John McCalle3027922010-08-25 11:45:40 +00007837 case BO_EQ:
7838 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007839 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007840 break;
John McCalle3027922010-08-25 11:45:40 +00007841 case BO_And:
7842 case BO_Xor:
7843 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007844 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007845 break;
John McCalle3027922010-08-25 11:45:40 +00007846 case BO_LAnd:
7847 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007848 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007849 break;
John McCalle3027922010-08-25 11:45:40 +00007850 case BO_MulAssign:
7851 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007852 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007853 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007854 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007855 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7856 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007857 break;
John McCalle3027922010-08-25 11:45:40 +00007858 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007859 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007860 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007861 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7862 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007863 break;
John McCalle3027922010-08-25 11:45:40 +00007864 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007865 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7866 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7867 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007868 break;
John McCalle3027922010-08-25 11:45:40 +00007869 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007870 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7871 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7872 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007873 break;
John McCalle3027922010-08-25 11:45:40 +00007874 case BO_ShlAssign:
7875 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007876 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007877 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007878 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7879 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007880 break;
John McCalle3027922010-08-25 11:45:40 +00007881 case BO_AndAssign:
7882 case BO_XorAssign:
7883 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007884 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007885 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007886 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7887 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007888 break;
John McCalle3027922010-08-25 11:45:40 +00007889 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7891 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7892 VK = RHS.get()->getValueKind();
7893 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007894 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007895 break;
7896 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007897 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007898 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007899
7900 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007901 CheckArrayAccess(LHS.get());
7902 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007903
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007904 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007905 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007906 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007907 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007908 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007909 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007910 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007911 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007913 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007914 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007915}
7916
Sebastian Redl44615072009-10-27 12:10:02 +00007917/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7918/// operators are mixed in a way that suggests that the programmer forgot that
7919/// comparison operators have higher precedence. The most typical example of
7920/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007921static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007922 SourceLocation OpLoc, Expr *LHSExpr,
7923 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007924 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007925 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7926 RHSopc = static_cast<BinOp::Opcode>(-1);
7927 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7928 LHSopc = BO->getOpcode();
7929 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7930 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007931
7932 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007933 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007934 return;
7935
7936 // Bitwise operations are sometimes used as eager logical ops.
7937 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007938 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7939 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007940 return;
7941
Richard Trieu4a287fb2011-09-07 01:49:20 +00007942 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7943 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007944 if (!isLeftComp && !isRightComp) return;
7945
Richard Trieu4a287fb2011-09-07 01:49:20 +00007946 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7947 OpLoc)
7948 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7949 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7950 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007951 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007952 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7953 RHSExpr->getLocEnd())
7954 : SourceRange(LHSExpr->getLocStart(),
7955 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007956
7957 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7958 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7959 SuggestParentheses(Self, OpLoc,
7960 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007961 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007962 SuggestParentheses(Self, OpLoc,
7963 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7964 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007965}
7966
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007967/// \brief It accepts a '&' expr that is inside a '|' one.
7968/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7969/// in parentheses.
7970static void
7971EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7972 BinaryOperator *Bop) {
7973 assert(Bop->getOpcode() == BO_And);
7974 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7975 << Bop->getSourceRange() << OpLoc;
7976 SuggestParentheses(Self, Bop->getOperatorLoc(),
7977 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7978 Bop->getSourceRange());
7979}
7980
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007981/// \brief It accepts a '&&' expr that is inside a '||' one.
7982/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7983/// in parentheses.
7984static void
7985EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007986 BinaryOperator *Bop) {
7987 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007988 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7989 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007990 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007991 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007992 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007993}
7994
7995/// \brief Returns true if the given expression can be evaluated as a constant
7996/// 'true'.
7997static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7998 bool Res;
7999 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8000}
8001
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008002/// \brief Returns true if the given expression can be evaluated as a constant
8003/// 'false'.
8004static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8005 bool Res;
8006 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8007}
8008
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008009/// \brief Look for '&&' in the left hand of a '||' expr.
8010static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008011 Expr *LHSExpr, Expr *RHSExpr) {
8012 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008013 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008014 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008015 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008016 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008017 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8018 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8019 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8020 } else if (Bop->getOpcode() == BO_LOr) {
8021 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8022 // If it's "a || b && 1 || c" we didn't warn earlier for
8023 // "a || b && 1", but warn now.
8024 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8025 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8026 }
8027 }
8028 }
8029}
8030
8031/// \brief Look for '&&' in the right hand of a '||' expr.
8032static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008033 Expr *LHSExpr, Expr *RHSExpr) {
8034 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008035 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008036 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008037 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008038 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008039 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8040 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8041 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008042 }
8043 }
8044}
8045
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008046/// \brief Look for '&' in the left or right hand of a '|' expr.
8047static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8048 Expr *OrArg) {
8049 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8050 if (Bop->getOpcode() == BO_And)
8051 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8052 }
8053}
8054
Sebastian Redl43028242009-10-26 15:24:15 +00008055/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008056/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008057static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008058 SourceLocation OpLoc, Expr *LHSExpr,
8059 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008060 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008061 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008062 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008063
8064 // Diagnose "arg1 & arg2 | arg3"
8065 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008066 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8067 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008068 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008069
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008070 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8071 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008072 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008073 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8074 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008075 }
Sebastian Redl43028242009-10-26 15:24:15 +00008076}
8077
Steve Naroff218bc2b2007-05-04 21:54:46 +00008078// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008079ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008080 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008081 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008082 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008083 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8084 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008085
Sebastian Redl43028242009-10-26 15:24:15 +00008086 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008087 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008088
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008089 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008090}
8091
John McCalldadc5752010-08-24 06:29:42 +00008092ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008093 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008094 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008095 if (getLangOptions().CPlusPlus) {
8096 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008097
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008098 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008099 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008100 } else if (Opc == BO_Assign &&
8101 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008102 UseBuiltinOperator = true;
8103 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008104 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8105 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008106 }
8107
8108 if (!UseBuiltinOperator) {
8109 // Find all of the overloaded operators visible from this
8110 // point. We perform both an operator-name lookup from the local
8111 // scope and an argument-dependent lookup based on the types of
8112 // the arguments.
8113 UnresolvedSet<16> Functions;
8114 OverloadedOperatorKind OverOp
8115 = BinaryOperator::getOverloadedOperator(Opc);
8116 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008117 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8118 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008119
8120 // Build the (potentially-overloaded, potentially-dependent)
8121 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008122 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008123 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008124 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008125
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008126 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008127 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008128}
8129
John McCalldadc5752010-08-24 06:29:42 +00008130ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008131 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008132 Expr *InputExpr) {
8133 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008134 ExprValueKind VK = VK_RValue;
8135 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008136 QualType resultType;
8137 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008138 case UO_PreInc:
8139 case UO_PreDec:
8140 case UO_PostInc:
8141 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008142 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008143 Opc == UO_PreInc ||
8144 Opc == UO_PostInc,
8145 Opc == UO_PreInc ||
8146 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008147 break;
John McCalle3027922010-08-25 11:45:40 +00008148 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008149 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008150 break;
John McCall31996342011-04-07 08:22:57 +00008151 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008152 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008153 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008154 Input = move(resolved);
8155 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8156 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008157 break;
John McCall31996342011-04-07 08:22:57 +00008158 }
John McCalle3027922010-08-25 11:45:40 +00008159 case UO_Plus:
8160 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008161 Input = UsualUnaryConversions(Input.take());
8162 if (Input.isInvalid()) return ExprError();
8163 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008164 if (resultType->isDependentType())
8165 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008166 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8167 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008168 break;
8169 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8170 resultType->isEnumeralType())
8171 break;
8172 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008173 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008174 resultType->isPointerType())
8175 break;
John McCall36226622010-10-12 02:09:17 +00008176 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008177 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008178 if (Input.isInvalid()) return ExprError();
8179 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008180 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008181
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008182 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008183 << resultType << Input.get()->getSourceRange());
8184
John McCalle3027922010-08-25 11:45:40 +00008185 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008186 Input = UsualUnaryConversions(Input.take());
8187 if (Input.isInvalid()) return ExprError();
8188 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008189 if (resultType->isDependentType())
8190 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008191 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8192 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8193 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008194 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008195 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008196 else if (resultType->hasIntegerRepresentation())
8197 break;
8198 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008199 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008200 if (Input.isInvalid()) return ExprError();
8201 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008202 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008203 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008204 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008205 }
Steve Naroff35d85152007-05-07 00:24:15 +00008206 break;
John Wiegley01296292011-04-08 18:41:53 +00008207
John McCalle3027922010-08-25 11:45:40 +00008208 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008209 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008210 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8211 if (Input.isInvalid()) return ExprError();
8212 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008213 if (resultType->isDependentType())
8214 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008215 if (resultType->isScalarType()) {
8216 // C99 6.5.3.3p1: ok, fallthrough;
8217 if (Context.getLangOptions().CPlusPlus) {
8218 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8219 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008220 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8221 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008222 }
John McCall36226622010-10-12 02:09:17 +00008223 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008224 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008225 if (Input.isInvalid()) return ExprError();
8226 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008227 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008228 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008229 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008230 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008231
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008232 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008233 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008234 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008235 break;
John McCalle3027922010-08-25 11:45:40 +00008236 case UO_Real:
8237 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008238 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008239 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008240 if (Input.isInvalid()) return ExprError();
8241 if (Input.get()->getValueKind() != VK_RValue &&
8242 Input.get()->getObjectKind() == OK_Ordinary)
8243 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008244 break;
John McCalle3027922010-08-25 11:45:40 +00008245 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008246 resultType = Input.get()->getType();
8247 VK = Input.get()->getValueKind();
8248 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008249 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008250 }
John Wiegley01296292011-04-08 18:41:53 +00008251 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008252 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008253
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008254 // Check for array bounds violations in the operand of the UnaryOperator,
8255 // except for the '*' and '&' operators that have to be handled specially
8256 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8257 // that are explicitly defined as valid by the standard).
8258 if (Opc != UO_AddrOf && Opc != UO_Deref)
8259 CheckArrayAccess(Input.get());
8260
John Wiegley01296292011-04-08 18:41:53 +00008261 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008262 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008263}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008264
John McCalldadc5752010-08-24 06:29:42 +00008265ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008266 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008267 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008268 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008269 // Find all of the overloaded operators visible from this
8270 // point. We perform both an operator-name lookup from the local
8271 // scope and an argument-dependent lookup based on the types of
8272 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008273 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008274 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008275 if (S && OverOp != OO_None)
8276 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8277 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008278
John McCallb268a282010-08-23 23:25:46 +00008279 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008280 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008281
John McCallb268a282010-08-23 23:25:46 +00008282 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008283}
8284
Douglas Gregor5287f092009-11-05 00:51:44 +00008285// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008286ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008287 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008288 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008289}
8290
Steve Naroff66356bd2007-09-16 14:56:35 +00008291/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008292ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008293 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008294 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008295 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008296 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008297 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008298}
8299
John McCall31168b02011-06-15 23:02:42 +00008300/// Given the last statement in a statement-expression, check whether
8301/// the result is a producing expression (like a call to an
8302/// ns_returns_retained function) and, if so, rebuild it to hoist the
8303/// release out of the full-expression. Otherwise, return null.
8304/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008305static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008306 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008307 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008308 if (!cleanups) return 0;
8309
8310 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008311 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008312 return 0;
8313
8314 // Splice out the cast. This shouldn't modify any interesting
8315 // features of the statement.
8316 Expr *producer = cast->getSubExpr();
8317 assert(producer->getType() == cast->getType());
8318 assert(producer->getValueKind() == cast->getValueKind());
8319 cleanups->setSubExpr(producer);
8320 return cleanups;
8321}
8322
John McCalldadc5752010-08-24 06:29:42 +00008323ExprResult
John McCallb268a282010-08-23 23:25:46 +00008324Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008325 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008326 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8327 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8328
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008329 bool isFileScope
8330 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008331 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008332 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008333
Chris Lattner366727f2007-07-24 16:58:17 +00008334 // FIXME: there are a variety of strange constraints to enforce here, for
8335 // example, it is not possible to goto into a stmt expression apparently.
8336 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008337
Chris Lattner366727f2007-07-24 16:58:17 +00008338 // If there are sub stmts in the compound stmt, take the type of the last one
8339 // as the type of the stmtexpr.
8340 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008341 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008342 if (!Compound->body_empty()) {
8343 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008344 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008345 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008346 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8347 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008348 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008349 }
John McCall31168b02011-06-15 23:02:42 +00008350
John Wiegley01296292011-04-08 18:41:53 +00008351 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008352 // Do function/array conversion on the last expression, but not
8353 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008354 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8355 if (LastExpr.isInvalid())
8356 return ExprError();
8357 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008358
John Wiegley01296292011-04-08 18:41:53 +00008359 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008360 // In ARC, if the final expression ends in a consume, splice
8361 // the consume out and bind it later. In the alternate case
8362 // (when dealing with a retainable type), the result
8363 // initialization will create a produce. In both cases the
8364 // result will be +1, and we'll need to balance that out with
8365 // a bind.
8366 if (Expr *rebuiltLastStmt
8367 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8368 LastExpr = rebuiltLastStmt;
8369 } else {
8370 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008371 InitializedEntity::InitializeResult(LPLoc,
8372 Ty,
8373 false),
8374 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008375 LastExpr);
8376 }
8377
John Wiegley01296292011-04-08 18:41:53 +00008378 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008379 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008380 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008381 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008382 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008383 else
John Wiegley01296292011-04-08 18:41:53 +00008384 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008385 StmtExprMayBindToTemp = true;
8386 }
8387 }
8388 }
Chris Lattner944d3062008-07-26 19:51:01 +00008389 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008390
Eli Friedmanba961a92009-03-23 00:24:07 +00008391 // FIXME: Check that expression type is complete/non-abstract; statement
8392 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008393 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8394 if (StmtExprMayBindToTemp)
8395 return MaybeBindToTemporary(ResStmtExpr);
8396 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008397}
Steve Naroff78864672007-08-01 22:05:33 +00008398
John McCalldadc5752010-08-24 06:29:42 +00008399ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008400 TypeSourceInfo *TInfo,
8401 OffsetOfComponent *CompPtr,
8402 unsigned NumComponents,
8403 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008404 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008405 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008406 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008407
Chris Lattnerf17bd422007-08-30 17:45:32 +00008408 // We must have at least one component that refers to the type, and the first
8409 // one is known to be a field designator. Verify that the ArgTy represents
8410 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008411 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008412 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8413 << ArgTy << TypeRange);
8414
8415 // Type must be complete per C99 7.17p3 because a declaring a variable
8416 // with an incomplete type would be ill-formed.
8417 if (!Dependent
8418 && RequireCompleteType(BuiltinLoc, ArgTy,
8419 PDiag(diag::err_offsetof_incomplete_type)
8420 << TypeRange))
8421 return ExprError();
8422
Chris Lattner78502cf2007-08-31 21:49:13 +00008423 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8424 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008425 // FIXME: This diagnostic isn't actually visible because the location is in
8426 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008427 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008428 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8429 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008430
8431 bool DidWarnAboutNonPOD = false;
8432 QualType CurrentType = ArgTy;
8433 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008434 SmallVector<OffsetOfNode, 4> Comps;
8435 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008436 for (unsigned i = 0; i != NumComponents; ++i) {
8437 const OffsetOfComponent &OC = CompPtr[i];
8438 if (OC.isBrackets) {
8439 // Offset of an array sub-field. TODO: Should we allow vector elements?
8440 if (!CurrentType->isDependentType()) {
8441 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8442 if(!AT)
8443 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8444 << CurrentType);
8445 CurrentType = AT->getElementType();
8446 } else
8447 CurrentType = Context.DependentTy;
8448
8449 // The expression must be an integral expression.
8450 // FIXME: An integral constant expression?
8451 Expr *Idx = static_cast<Expr*>(OC.U.E);
8452 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8453 !Idx->getType()->isIntegerType())
8454 return ExprError(Diag(Idx->getLocStart(),
8455 diag::err_typecheck_subscript_not_integer)
8456 << Idx->getSourceRange());
8457
8458 // Record this array index.
8459 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8460 Exprs.push_back(Idx);
8461 continue;
8462 }
8463
8464 // Offset of a field.
8465 if (CurrentType->isDependentType()) {
8466 // We have the offset of a field, but we can't look into the dependent
8467 // type. Just record the identifier of the field.
8468 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8469 CurrentType = Context.DependentTy;
8470 continue;
8471 }
8472
8473 // We need to have a complete type to look into.
8474 if (RequireCompleteType(OC.LocStart, CurrentType,
8475 diag::err_offsetof_incomplete_type))
8476 return ExprError();
8477
8478 // Look for the designated field.
8479 const RecordType *RC = CurrentType->getAs<RecordType>();
8480 if (!RC)
8481 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8482 << CurrentType);
8483 RecordDecl *RD = RC->getDecl();
8484
8485 // C++ [lib.support.types]p5:
8486 // The macro offsetof accepts a restricted set of type arguments in this
8487 // International Standard. type shall be a POD structure or a POD union
8488 // (clause 9).
8489 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8490 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008491 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008492 PDiag(diag::warn_offsetof_non_pod_type)
8493 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8494 << CurrentType))
8495 DidWarnAboutNonPOD = true;
8496 }
8497
8498 // Look for the field.
8499 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8500 LookupQualifiedName(R, RD);
8501 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008502 IndirectFieldDecl *IndirectMemberDecl = 0;
8503 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008504 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008505 MemberDecl = IndirectMemberDecl->getAnonField();
8506 }
8507
Douglas Gregor882211c2010-04-28 22:16:22 +00008508 if (!MemberDecl)
8509 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8510 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8511 OC.LocEnd));
8512
Douglas Gregor10982ea2010-04-28 22:36:06 +00008513 // C99 7.17p3:
8514 // (If the specified member is a bit-field, the behavior is undefined.)
8515 //
8516 // We diagnose this as an error.
8517 if (MemberDecl->getBitWidth()) {
8518 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8519 << MemberDecl->getDeclName()
8520 << SourceRange(BuiltinLoc, RParenLoc);
8521 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8522 return ExprError();
8523 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008524
8525 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008526 if (IndirectMemberDecl)
8527 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008528
Douglas Gregord1702062010-04-29 00:18:15 +00008529 // If the member was found in a base class, introduce OffsetOfNodes for
8530 // the base class indirections.
8531 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8532 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008533 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008534 CXXBasePath &Path = Paths.front();
8535 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8536 B != BEnd; ++B)
8537 Comps.push_back(OffsetOfNode(B->Base));
8538 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008539
Francois Pichet783dd6e2010-11-21 06:08:52 +00008540 if (IndirectMemberDecl) {
8541 for (IndirectFieldDecl::chain_iterator FI =
8542 IndirectMemberDecl->chain_begin(),
8543 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8544 assert(isa<FieldDecl>(*FI));
8545 Comps.push_back(OffsetOfNode(OC.LocStart,
8546 cast<FieldDecl>(*FI), OC.LocEnd));
8547 }
8548 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008549 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008550
Douglas Gregor882211c2010-04-28 22:16:22 +00008551 CurrentType = MemberDecl->getType().getNonReferenceType();
8552 }
8553
8554 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8555 TInfo, Comps.data(), Comps.size(),
8556 Exprs.data(), Exprs.size(), RParenLoc));
8557}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008558
John McCalldadc5752010-08-24 06:29:42 +00008559ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008560 SourceLocation BuiltinLoc,
8561 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008562 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008563 OffsetOfComponent *CompPtr,
8564 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008565 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008566
Douglas Gregor882211c2010-04-28 22:16:22 +00008567 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008568 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008569 if (ArgTy.isNull())
8570 return ExprError();
8571
Eli Friedman06dcfd92010-08-05 10:15:45 +00008572 if (!ArgTInfo)
8573 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8574
8575 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008576 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008577}
8578
8579
John McCalldadc5752010-08-24 06:29:42 +00008580ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008581 Expr *CondExpr,
8582 Expr *LHSExpr, Expr *RHSExpr,
8583 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008584 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8585
John McCall7decc9e2010-11-18 06:31:45 +00008586 ExprValueKind VK = VK_RValue;
8587 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008588 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008589 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008590 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008591 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008592 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008593 } else {
8594 // The conditional expression is required to be a constant expression.
8595 llvm::APSInt condEval(32);
8596 SourceLocation ExpLoc;
8597 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008598 return ExprError(Diag(ExpLoc,
8599 diag::err_typecheck_choose_expr_requires_constant)
8600 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008601
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008602 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008603 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8604
8605 resType = ActiveExpr->getType();
8606 ValueDependent = ActiveExpr->isValueDependent();
8607 VK = ActiveExpr->getValueKind();
8608 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008609 }
8610
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008611 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008612 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008613 resType->isDependentType(),
8614 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008615}
8616
Steve Naroffc540d662008-09-03 18:15:37 +00008617//===----------------------------------------------------------------------===//
8618// Clang Extensions.
8619//===----------------------------------------------------------------------===//
8620
8621/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008622void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008623 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008624 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008625 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008626 if (CurScope)
8627 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008628 else
8629 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008630}
8631
Mike Stump82f071f2009-02-04 22:31:32 +00008632void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008633 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008634 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008635 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008636
John McCall8cb7bdf2010-06-04 23:28:52 +00008637 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008638 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008639
John McCall3882ace2011-01-05 12:14:39 +00008640 // GetTypeForDeclarator always produces a function type for a block
8641 // literal signature. Furthermore, it is always a FunctionProtoType
8642 // unless the function was written with a typedef.
8643 assert(T->isFunctionType() &&
8644 "GetTypeForDeclarator made a non-function block signature");
8645
8646 // Look for an explicit signature in that function type.
8647 FunctionProtoTypeLoc ExplicitSignature;
8648
8649 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8650 if (isa<FunctionProtoTypeLoc>(tmp)) {
8651 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8652
8653 // Check whether that explicit signature was synthesized by
8654 // GetTypeForDeclarator. If so, don't save that as part of the
8655 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008656 if (ExplicitSignature.getLocalRangeBegin() ==
8657 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008658 // This would be much cheaper if we stored TypeLocs instead of
8659 // TypeSourceInfos.
8660 TypeLoc Result = ExplicitSignature.getResultLoc();
8661 unsigned Size = Result.getFullDataSize();
8662 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8663 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8664
8665 ExplicitSignature = FunctionProtoTypeLoc();
8666 }
John McCalla3ccba02010-06-04 11:21:44 +00008667 }
Mike Stump11289f42009-09-09 15:08:12 +00008668
John McCall3882ace2011-01-05 12:14:39 +00008669 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8670 CurBlock->FunctionType = T;
8671
8672 const FunctionType *Fn = T->getAs<FunctionType>();
8673 QualType RetTy = Fn->getResultType();
8674 bool isVariadic =
8675 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8676
John McCall8e346702010-06-04 19:02:56 +00008677 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008678
John McCalla3ccba02010-06-04 11:21:44 +00008679 // Don't allow returning a objc interface by value.
8680 if (RetTy->isObjCObjectType()) {
8681 Diag(ParamInfo.getSourceRange().getBegin(),
8682 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8683 return;
8684 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008685
John McCalla3ccba02010-06-04 11:21:44 +00008686 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008687 // return type. TODO: what should we do with declarators like:
8688 // ^ * { ... }
8689 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008690 if (RetTy != Context.DependentTy)
8691 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008692
John McCalla3ccba02010-06-04 11:21:44 +00008693 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008694 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008695 if (ExplicitSignature) {
8696 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8697 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008698 if (Param->getIdentifier() == 0 &&
8699 !Param->isImplicit() &&
8700 !Param->isInvalidDecl() &&
8701 !getLangOptions().CPlusPlus)
8702 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008703 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008704 }
John McCalla3ccba02010-06-04 11:21:44 +00008705
8706 // Fake up parameter variables if we have a typedef, like
8707 // ^ fntype { ... }
8708 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8709 for (FunctionProtoType::arg_type_iterator
8710 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8711 ParmVarDecl *Param =
8712 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8713 ParamInfo.getSourceRange().getBegin(),
8714 *I);
John McCall8e346702010-06-04 19:02:56 +00008715 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008716 }
Steve Naroffc540d662008-09-03 18:15:37 +00008717 }
John McCalla3ccba02010-06-04 11:21:44 +00008718
John McCall8e346702010-06-04 19:02:56 +00008719 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008720 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008721 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008722 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8723 CurBlock->TheDecl->param_end(),
8724 /*CheckParameterNames=*/false);
8725 }
8726
John McCalla3ccba02010-06-04 11:21:44 +00008727 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008728 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008729
John McCall8e346702010-06-04 19:02:56 +00008730 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008731 Diag(ParamInfo.getAttributes()->getLoc(),
8732 diag::warn_attribute_sentinel_not_variadic) << 1;
8733 // FIXME: remove the attribute.
8734 }
8735
8736 // Put the parameter variables in scope. We can bail out immediately
8737 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008738 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008739 return;
8740
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008741 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008742 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8743 (*AI)->setOwningFunction(CurBlock->TheDecl);
8744
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008745 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008746 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008747 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008748
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008749 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008750 }
John McCallf7b2fb52010-01-22 00:28:27 +00008751 }
Steve Naroffc540d662008-09-03 18:15:37 +00008752}
8753
8754/// ActOnBlockError - If there is an error parsing a block, this callback
8755/// is invoked to pop the information about the block from the action impl.
8756void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008757 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008758 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008759 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008760}
8761
8762/// ActOnBlockStmtExpr - This is called when the body of a block statement
8763/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008764ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008765 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008766 // If blocks are disabled, emit an error.
8767 if (!LangOpts.Blocks)
8768 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008769
Douglas Gregor9a28e842010-03-01 23:15:13 +00008770 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008771
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008772 PopDeclContext();
8773
Steve Naroffc540d662008-09-03 18:15:37 +00008774 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008775 if (!BSI->ReturnType.isNull())
8776 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008777
Mike Stump3bf1ab42009-07-28 22:04:01 +00008778 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008779 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008780
John McCallc63de662011-02-02 13:00:07 +00008781 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008782 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8783 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008784
John McCall8e346702010-06-04 19:02:56 +00008785 // If the user wrote a function type in some form, try to use that.
8786 if (!BSI->FunctionType.isNull()) {
8787 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8788
8789 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8790 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8791
8792 // Turn protoless block types into nullary block types.
8793 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008794 FunctionProtoType::ExtProtoInfo EPI;
8795 EPI.ExtInfo = Ext;
8796 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008797
8798 // Otherwise, if we don't need to change anything about the function type,
8799 // preserve its sugar structure.
8800 } else if (FTy->getResultType() == RetTy &&
8801 (!NoReturn || FTy->getNoReturnAttr())) {
8802 BlockTy = BSI->FunctionType;
8803
8804 // Otherwise, make the minimal modifications to the function type.
8805 } else {
8806 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008807 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8808 EPI.TypeQuals = 0; // FIXME: silently?
8809 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008810 BlockTy = Context.getFunctionType(RetTy,
8811 FPT->arg_type_begin(),
8812 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008813 EPI);
John McCall8e346702010-06-04 19:02:56 +00008814 }
8815
8816 // If we don't have a function type, just build one from nothing.
8817 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008818 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008819 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008820 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008821 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008822
John McCall8e346702010-06-04 19:02:56 +00008823 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8824 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008825 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008826
Chris Lattner45542ea2009-04-19 05:28:12 +00008827 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008828 if (getCurFunction()->NeedsScopeChecking() &&
8829 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008830 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008831
Chris Lattner60f84492011-02-17 23:58:47 +00008832 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008833
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008834 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8835 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8836 const VarDecl *variable = ci->getVariable();
8837 QualType T = variable->getType();
8838 QualType::DestructionKind destructKind = T.isDestructedType();
8839 if (destructKind != QualType::DK_none)
8840 getCurFunction()->setHasBranchProtectedScope();
8841 }
8842
Douglas Gregor49695f02011-09-06 20:46:03 +00008843 computeNRVO(Body, getCurBlock());
8844
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008845 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8846 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8847 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8848
Douglas Gregor9a28e842010-03-01 23:15:13 +00008849 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008850}
8851
John McCalldadc5752010-08-24 06:29:42 +00008852ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008853 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008854 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008855 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008856 GetTypeFromParser(Ty, &TInfo);
8857 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008858}
8859
John McCalldadc5752010-08-24 06:29:42 +00008860ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008861 Expr *E, TypeSourceInfo *TInfo,
8862 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008863 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008864
Eli Friedman121ba0c2008-08-09 23:32:40 +00008865 // Get the va_list type
8866 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008867 if (VaListType->isArrayType()) {
8868 // Deal with implicit array decay; for example, on x86-64,
8869 // va_list is an array, but it's supposed to decay to
8870 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008871 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008872 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008873 ExprResult Result = UsualUnaryConversions(E);
8874 if (Result.isInvalid())
8875 return ExprError();
8876 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008877 } else {
8878 // Otherwise, the va_list argument must be an l-value because
8879 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008880 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008881 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008882 return ExprError();
8883 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008884
Douglas Gregorad3150c2009-05-19 23:10:31 +00008885 if (!E->isTypeDependent() &&
8886 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008887 return ExprError(Diag(E->getLocStart(),
8888 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008889 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008890 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008891
David Majnemerc75d1a12011-06-14 05:17:32 +00008892 if (!TInfo->getType()->isDependentType()) {
8893 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8894 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8895 << TInfo->getTypeLoc().getSourceRange()))
8896 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008897
David Majnemerc75d1a12011-06-14 05:17:32 +00008898 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8899 TInfo->getType(),
8900 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8901 << TInfo->getTypeLoc().getSourceRange()))
8902 return ExprError();
8903
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008904 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008905 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008906 TInfo->getType()->isObjCLifetimeType()
8907 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8908 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008909 << TInfo->getType()
8910 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008911 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008912
8913 // Check for va_arg where arguments of the given type will be promoted
8914 // (i.e. this va_arg is guaranteed to have undefined behavior).
8915 QualType PromoteType;
8916 if (TInfo->getType()->isPromotableIntegerType()) {
8917 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8918 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8919 PromoteType = QualType();
8920 }
8921 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8922 PromoteType = Context.DoubleTy;
8923 if (!PromoteType.isNull())
8924 Diag(TInfo->getTypeLoc().getBeginLoc(),
8925 diag::warn_second_parameter_to_va_arg_never_compatible)
8926 << TInfo->getType()
8927 << PromoteType
8928 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008929 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008930
Abramo Bagnara27db2392010-08-10 10:06:15 +00008931 QualType T = TInfo->getType().getNonLValueExprType(Context);
8932 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008933}
8934
John McCalldadc5752010-08-24 06:29:42 +00008935ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008936 // The type of __null will be int or long, depending on the size of
8937 // pointers on the target.
8938 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008939 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8940 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008941 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008942 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008943 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008944 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008945 Ty = Context.LongLongTy;
8946 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008947 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008948 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008949
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008950 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008951}
8952
Alexis Huntc46382e2010-04-28 23:02:27 +00008953static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008954 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008955 if (!SemaRef.getLangOptions().ObjC1)
8956 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008957
Anders Carlssonace5d072009-11-10 04:46:30 +00008958 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8959 if (!PT)
8960 return;
8961
8962 // Check if the destination is of type 'id'.
8963 if (!PT->isObjCIdType()) {
8964 // Check if the destination is the 'NSString' interface.
8965 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8966 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8967 return;
8968 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008969
Anders Carlssonace5d072009-11-10 04:46:30 +00008970 // Strip off any parens and casts.
8971 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008972 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008973 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008974
Douglas Gregora771f462010-03-31 17:46:05 +00008975 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008976}
8977
Chris Lattner9bad62c2008-01-04 18:04:52 +00008978bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8979 SourceLocation Loc,
8980 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008981 Expr *SrcExpr, AssignmentAction Action,
8982 bool *Complained) {
8983 if (Complained)
8984 *Complained = false;
8985
Chris Lattner9bad62c2008-01-04 18:04:52 +00008986 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008987 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008988 bool isInvalid = false;
8989 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008990 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008991 ConversionFixItGenerator ConvHints;
8992 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008993
Chris Lattner9bad62c2008-01-04 18:04:52 +00008994 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00008995 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008996 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008997 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008998 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008999 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9000 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009001 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009002 case IntToPointer:
9003 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009004 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9005 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009006 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009007 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009008 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009009 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009010 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9011 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009012 if (Hint.isNull() && !CheckInferredResultType) {
9013 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9014 }
9015 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009016 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009017 case IncompatiblePointerSign:
9018 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9019 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009020 case FunctionVoidPointer:
9021 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9022 break;
John McCall4fff8f62011-02-01 00:10:29 +00009023 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009024 // Perform array-to-pointer decay if necessary.
9025 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9026
John McCall4fff8f62011-02-01 00:10:29 +00009027 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9028 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9029 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9030 DiagKind = diag::err_typecheck_incompatible_address_space;
9031 break;
John McCall31168b02011-06-15 23:02:42 +00009032
9033
9034 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009035 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009036 break;
John McCall4fff8f62011-02-01 00:10:29 +00009037 }
9038
9039 llvm_unreachable("unknown error case for discarding qualifiers!");
9040 // fallthrough
9041 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009042 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009043 // If the qualifiers lost were because we were applying the
9044 // (deprecated) C++ conversion from a string literal to a char*
9045 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9046 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009047 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009048 // bit of refactoring (so that the second argument is an
9049 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009050 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009051 // C++ semantics.
9052 if (getLangOptions().CPlusPlus &&
9053 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9054 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009055 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9056 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009057 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009058 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009059 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009060 case IntToBlockPointer:
9061 DiagKind = diag::err_int_to_block_pointer;
9062 break;
9063 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009064 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009065 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009066 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009067 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009068 // it can give a more specific diagnostic.
9069 DiagKind = diag::warn_incompatible_qualified_id;
9070 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009071 case IncompatibleVectors:
9072 DiagKind = diag::warn_incompatible_vectors;
9073 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009074 case IncompatibleObjCWeakRef:
9075 DiagKind = diag::err_arc_weak_unavailable_assign;
9076 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009077 case Incompatible:
9078 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009079 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9080 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009081 isInvalid = true;
9082 break;
9083 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009084
Douglas Gregorc68e1402010-04-09 00:35:39 +00009085 QualType FirstType, SecondType;
9086 switch (Action) {
9087 case AA_Assigning:
9088 case AA_Initializing:
9089 // The destination type comes first.
9090 FirstType = DstType;
9091 SecondType = SrcType;
9092 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009093
Douglas Gregorc68e1402010-04-09 00:35:39 +00009094 case AA_Returning:
9095 case AA_Passing:
9096 case AA_Converting:
9097 case AA_Sending:
9098 case AA_Casting:
9099 // The source type comes first.
9100 FirstType = SrcType;
9101 SecondType = DstType;
9102 break;
9103 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009104
Anna Zaks3b402712011-07-28 19:51:27 +00009105 PartialDiagnostic FDiag = PDiag(DiagKind);
9106 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9107
9108 // If we can fix the conversion, suggest the FixIts.
9109 assert(ConvHints.isNull() || Hint.isNull());
9110 if (!ConvHints.isNull()) {
9111 for (llvm::SmallVector<FixItHint, 1>::iterator
9112 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9113 HI != HE; ++HI)
9114 FDiag << *HI;
9115 } else {
9116 FDiag << Hint;
9117 }
9118 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9119
9120 Diag(Loc, FDiag);
9121
Douglas Gregor33823722011-06-11 01:09:30 +00009122 if (CheckInferredResultType)
9123 EmitRelatedResultTypeNote(SrcExpr);
9124
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009125 if (Complained)
9126 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009127 return isInvalid;
9128}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009129
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009130bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009131 llvm::APSInt ICEResult;
9132 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9133 if (Result)
9134 *Result = ICEResult;
9135 return false;
9136 }
9137
Anders Carlssone54e8a12008-11-30 19:50:32 +00009138 Expr::EvalResult EvalResult;
9139
Mike Stump4e1f26a2009-02-19 03:04:26 +00009140 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009141 EvalResult.HasSideEffects) {
9142 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9143
9144 if (EvalResult.Diag) {
9145 // We only show the note if it's not the usual "invalid subexpression"
9146 // or if it's actually in a subexpression.
9147 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9148 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9149 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9150 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009151
Anders Carlssone54e8a12008-11-30 19:50:32 +00009152 return true;
9153 }
9154
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009155 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9156 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009157
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009158 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009159 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9160 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009161 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009162
Anders Carlssone54e8a12008-11-30 19:50:32 +00009163 if (Result)
9164 *Result = EvalResult.Val.getInt();
9165 return false;
9166}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009167
Douglas Gregorff790f12009-11-26 00:44:06 +00009168void
Mike Stump11289f42009-09-09 15:08:12 +00009169Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009170 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009171 ExpressionEvaluationContextRecord(NewContext,
9172 ExprTemporaries.size(),
9173 ExprNeedsCleanups));
9174 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009175}
9176
Richard Trieucfc491d2011-08-02 04:35:43 +00009177void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009178 // Pop the current expression evaluation context off the stack.
9179 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9180 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009181
Douglas Gregorfab31f42009-12-12 07:57:52 +00009182 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9183 if (Rec.PotentiallyReferenced) {
9184 // Mark any remaining declarations in the current position of the stack
9185 // as "referenced". If they were not meant to be referenced, semantic
9186 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009187 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009188 I = Rec.PotentiallyReferenced->begin(),
9189 IEnd = Rec.PotentiallyReferenced->end();
9190 I != IEnd; ++I)
9191 MarkDeclarationReferenced(I->first, I->second);
9192 }
9193
9194 if (Rec.PotentiallyDiagnosed) {
9195 // Emit any pending diagnostics.
9196 for (PotentiallyEmittedDiagnostics::iterator
9197 I = Rec.PotentiallyDiagnosed->begin(),
9198 IEnd = Rec.PotentiallyDiagnosed->end();
9199 I != IEnd; ++I)
9200 Diag(I->first, I->second);
9201 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009202 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009203
9204 // When are coming out of an unevaluated context, clear out any
9205 // temporaries that we may have created as part of the evaluation of
9206 // the expression in that context: they aren't relevant because they
9207 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009208 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009209 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9210 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009211 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9212
9213 // Otherwise, merge the contexts together.
9214 } else {
9215 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9216 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009217
9218 // Destroy the popped expression evaluation record.
9219 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009220}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009221
John McCall31168b02011-06-15 23:02:42 +00009222void Sema::DiscardCleanupsInEvaluationContext() {
9223 ExprTemporaries.erase(
9224 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9225 ExprTemporaries.end());
9226 ExprNeedsCleanups = false;
9227}
9228
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009229/// \brief Note that the given declaration was referenced in the source code.
9230///
9231/// This routine should be invoke whenever a given declaration is referenced
9232/// in the source code, and where that reference occurred. If this declaration
9233/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9234/// C99 6.9p3), then the declaration will be marked as used.
9235///
9236/// \param Loc the location where the declaration was referenced.
9237///
9238/// \param D the declaration that has been referenced by the source code.
9239void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9240 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009241
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009242 D->setReferenced();
9243
Douglas Gregorebada0772010-06-17 23:14:26 +00009244 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009245 return;
Mike Stump11289f42009-09-09 15:08:12 +00009246
Richard Trieucfc491d2011-08-02 04:35:43 +00009247 // Mark a parameter or variable declaration "used", regardless of whether
9248 // we're in a template or not. The reason for this is that unevaluated
9249 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9250 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009251 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009252 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009253 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009254 return;
9255 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009256
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009257 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9258 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009259
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009260 // Do not mark anything as "used" within a dependent context; wait for
9261 // an instantiation.
9262 if (CurContext->isDependentContext())
9263 return;
Mike Stump11289f42009-09-09 15:08:12 +00009264
Douglas Gregorff790f12009-11-26 00:44:06 +00009265 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009266 case Unevaluated:
9267 // We are in an expression that is not potentially evaluated; do nothing.
9268 return;
Mike Stump11289f42009-09-09 15:08:12 +00009269
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009270 case PotentiallyEvaluated:
9271 // We are in a potentially-evaluated expression, so this declaration is
9272 // "used"; handle this below.
9273 break;
Mike Stump11289f42009-09-09 15:08:12 +00009274
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009275 case PotentiallyPotentiallyEvaluated:
9276 // We are in an expression that may be potentially evaluated; queue this
9277 // declaration reference until we know whether the expression is
9278 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009279 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009280 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009281
9282 case PotentiallyEvaluatedIfUsed:
9283 // Referenced declarations will only be used if the construct in the
9284 // containing expression is used.
9285 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009286 }
Mike Stump11289f42009-09-09 15:08:12 +00009287
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009288 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009290 if (Constructor->isDefaulted()) {
9291 if (Constructor->isDefaultConstructor()) {
9292 if (Constructor->isTrivial())
9293 return;
9294 if (!Constructor->isUsed(false))
9295 DefineImplicitDefaultConstructor(Loc, Constructor);
9296 } else if (Constructor->isCopyConstructor()) {
9297 if (!Constructor->isUsed(false))
9298 DefineImplicitCopyConstructor(Loc, Constructor);
9299 } else if (Constructor->isMoveConstructor()) {
9300 if (!Constructor->isUsed(false))
9301 DefineImplicitMoveConstructor(Loc, Constructor);
9302 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009303 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009304
Douglas Gregor88d292c2010-05-13 16:44:06 +00009305 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009306 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009307 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009308 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009309 if (Destructor->isVirtual())
9310 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009311 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009312 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009313 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009314 if (!MethodDecl->isUsed(false)) {
9315 if (MethodDecl->isCopyAssignmentOperator())
9316 DefineImplicitCopyAssignment(Loc, MethodDecl);
9317 else
9318 DefineImplicitMoveAssignment(Loc, MethodDecl);
9319 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009320 } else if (MethodDecl->isVirtual())
9321 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009322 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009323 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009324 // Recursive functions should be marked when used from another function.
9325 if (CurContext == Function) return;
9326
Mike Stump11289f42009-09-09 15:08:12 +00009327 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009328 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009329 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009330 bool AlreadyInstantiated = false;
9331 if (FunctionTemplateSpecializationInfo *SpecInfo
9332 = Function->getTemplateSpecializationInfo()) {
9333 if (SpecInfo->getPointOfInstantiation().isInvalid())
9334 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009335 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009336 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009337 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009338 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009339 = Function->getMemberSpecializationInfo()) {
9340 if (MSInfo->getPointOfInstantiation().isInvalid())
9341 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009342 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009343 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009344 AlreadyInstantiated = true;
9345 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009346
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009347 if (!AlreadyInstantiated) {
9348 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9349 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9350 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9351 Loc));
9352 else
Chandler Carruth54080172010-08-25 08:44:16 +00009353 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009354 }
John McCall83779672011-02-19 02:53:41 +00009355 } else {
9356 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009357 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9358 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009359 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009360 MarkDeclarationReferenced(Loc, *i);
9361 }
John McCall83779672011-02-19 02:53:41 +00009362 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009363
John McCall83779672011-02-19 02:53:41 +00009364 // Keep track of used but undefined functions.
9365 if (!Function->isPure() && !Function->hasBody() &&
9366 Function->getLinkage() != ExternalLinkage) {
9367 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9368 if (old.isInvalid()) old = Loc;
9369 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009370
John McCall83779672011-02-19 02:53:41 +00009371 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009372 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009373 }
Mike Stump11289f42009-09-09 15:08:12 +00009374
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009375 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009376 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009377 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009378 Var->getInstantiatedFromStaticDataMember()) {
9379 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9380 assert(MSInfo && "Missing member specialization information?");
9381 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9382 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9383 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009384 // This is a modification of an existing AST node. Notify listeners.
9385 if (ASTMutationListener *L = getASTMutationListener())
9386 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009387 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009388 }
9389 }
Mike Stump11289f42009-09-09 15:08:12 +00009390
John McCall15dd4042011-02-21 19:25:48 +00009391 // Keep track of used but undefined variables. We make a hole in
9392 // the warning for static const data members with in-line
9393 // initializers.
John McCall83779672011-02-19 02:53:41 +00009394 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009395 && Var->getLinkage() != ExternalLinkage
9396 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009397 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9398 if (old.isInvalid()) old = Loc;
9399 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009400
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009401 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009402 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009403 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009404}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009405
Douglas Gregor5597ab42010-05-07 23:12:07 +00009406namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009407 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009408 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009409 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009410 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9411 Sema &S;
9412 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009413
Douglas Gregor5597ab42010-05-07 23:12:07 +00009414 public:
9415 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009416
Douglas Gregor5597ab42010-05-07 23:12:07 +00009417 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009418
9419 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9420 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009421 };
9422}
9423
Chandler Carruthaf80f662010-06-09 08:17:30 +00009424bool MarkReferencedDecls::TraverseTemplateArgument(
9425 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009426 if (Arg.getKind() == TemplateArgument::Declaration) {
9427 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9428 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009429
9430 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009431}
9432
Chandler Carruthaf80f662010-06-09 08:17:30 +00009433bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009434 if (ClassTemplateSpecializationDecl *Spec
9435 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9436 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009437 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009438 }
9439
Chandler Carruthc65667c2010-06-10 10:31:57 +00009440 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009441}
9442
9443void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9444 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009445 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009446}
9447
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009448namespace {
9449 /// \brief Helper class that marks all of the declarations referenced by
9450 /// potentially-evaluated subexpressions as "referenced".
9451 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9452 Sema &S;
9453
9454 public:
9455 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9456
9457 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9458
9459 void VisitDeclRefExpr(DeclRefExpr *E) {
9460 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9461 }
9462
9463 void VisitMemberExpr(MemberExpr *E) {
9464 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009465 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009466 }
9467
9468 void VisitCXXNewExpr(CXXNewExpr *E) {
9469 if (E->getConstructor())
9470 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9471 if (E->getOperatorNew())
9472 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9473 if (E->getOperatorDelete())
9474 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009475 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009476 }
9477
9478 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9479 if (E->getOperatorDelete())
9480 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009481 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9482 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9483 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9484 S.MarkDeclarationReferenced(E->getLocStart(),
9485 S.LookupDestructor(Record));
9486 }
9487
Douglas Gregor32b3de52010-09-11 23:32:50 +00009488 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009489 }
9490
9491 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9492 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009493 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009494 }
9495
9496 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9497 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9498 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009499
9500 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9501 Visit(E->getExpr());
9502 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009503 };
9504}
9505
9506/// \brief Mark any declarations that appear within this expression or any
9507/// potentially-evaluated subexpressions as "referenced".
9508void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9509 EvaluatedExprMarker(*this).Visit(E);
9510}
9511
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009512/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9513/// of the program being compiled.
9514///
9515/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009516/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009517/// possibility that the code will actually be executable. Code in sizeof()
9518/// expressions, code used only during overload resolution, etc., are not
9519/// potentially evaluated. This routine will suppress such diagnostics or,
9520/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009521/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009522/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009523///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009524/// This routine should be used for all diagnostics that describe the run-time
9525/// behavior of a program, such as passing a non-POD value through an ellipsis.
9526/// Failure to do so will likely result in spurious diagnostics or failures
9527/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009528bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009529 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009530 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009531 case Unevaluated:
9532 // The argument will never be evaluated, so don't complain.
9533 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009534
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009535 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009536 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009537 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009538 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009539 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009540 }
9541 else
9542 Diag(Loc, PD);
9543
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009544 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009545
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009546 case PotentiallyPotentiallyEvaluated:
9547 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9548 break;
9549 }
9550
9551 return false;
9552}
9553
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009554bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9555 CallExpr *CE, FunctionDecl *FD) {
9556 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9557 return false;
9558
9559 PartialDiagnostic Note =
9560 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9561 << FD->getDeclName() : PDiag();
9562 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009563
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009564 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009565 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009566 PDiag(diag::err_call_function_incomplete_return)
9567 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009568 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009569 << CE->getSourceRange(),
9570 std::make_pair(NoteLoc, Note)))
9571 return true;
9572
9573 return false;
9574}
9575
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009576// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009577// will prevent this condition from triggering, which is what we want.
9578void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9579 SourceLocation Loc;
9580
John McCall0506e4a2009-11-11 02:41:58 +00009581 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009582 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009583
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009584 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009585 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009586 return;
9587
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009588 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9589
John McCallb0e419e2009-11-12 00:06:05 +00009590 // Greylist some idioms by putting them into a warning subcategory.
9591 if (ObjCMessageExpr *ME
9592 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9593 Selector Sel = ME->getSelector();
9594
John McCallb0e419e2009-11-12 00:06:05 +00009595 // self = [<foo> init...]
Fariborz Jahaniandb8015c2011-09-17 19:23:40 +00009596 if (GetMethodIfSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009597 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9598
9599 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009600 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009601 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9602 }
John McCall0506e4a2009-11-11 02:41:58 +00009603
John McCalld5707ab2009-10-12 21:59:07 +00009604 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009605 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009606 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009607 return;
9608
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009609 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009610 Loc = Op->getOperatorLoc();
9611 } else {
9612 // Not an assignment.
9613 return;
9614 }
9615
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009616 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009617
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009618 SourceLocation Open = E->getSourceRange().getBegin();
9619 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9620 Diag(Loc, diag::note_condition_assign_silence)
9621 << FixItHint::CreateInsertion(Open, "(")
9622 << FixItHint::CreateInsertion(Close, ")");
9623
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009624 if (IsOrAssign)
9625 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9626 << FixItHint::CreateReplacement(Loc, "!=");
9627 else
9628 Diag(Loc, diag::note_condition_assign_to_comparison)
9629 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009630}
9631
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009632/// \brief Redundant parentheses over an equality comparison can indicate
9633/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009634void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009635 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009636 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009637 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9638 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009639 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009640 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009641 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009642
Richard Trieuba63ce62011-09-09 01:45:06 +00009643 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009644
9645 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009646 if (opE->getOpcode() == BO_EQ &&
9647 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9648 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009649 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009650
Ted Kremenekae022092011-02-02 02:20:30 +00009651 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009652 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009653 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9654 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009655 Diag(Loc, diag::note_equality_comparison_to_assign)
9656 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009657 }
9658}
9659
John Wiegley01296292011-04-08 18:41:53 +00009660ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009661 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009662 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9663 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009664
John McCall0009fcc2011-04-26 20:42:42 +00009665 ExprResult result = CheckPlaceholderExpr(E);
9666 if (result.isInvalid()) return ExprError();
9667 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009668
John McCall0009fcc2011-04-26 20:42:42 +00009669 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009670 if (getLangOptions().CPlusPlus)
9671 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9672
John Wiegley01296292011-04-08 18:41:53 +00009673 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9674 if (ERes.isInvalid())
9675 return ExprError();
9676 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009677
9678 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009679 if (!T->isScalarType()) { // C99 6.8.4.1p1
9680 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9681 << T << E->getSourceRange();
9682 return ExprError();
9683 }
John McCalld5707ab2009-10-12 21:59:07 +00009684 }
9685
John Wiegley01296292011-04-08 18:41:53 +00009686 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009687}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009688
John McCalldadc5752010-08-24 06:29:42 +00009689ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009690 Expr *SubExpr) {
9691 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009692 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009693
Richard Trieuba63ce62011-09-09 01:45:06 +00009694 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009695}
John McCall36e7fe32010-10-12 00:20:44 +00009696
John McCall31996342011-04-07 08:22:57 +00009697namespace {
John McCall2979fe02011-04-12 00:42:48 +00009698 /// A visitor for rebuilding a call to an __unknown_any expression
9699 /// to have an appropriate type.
9700 struct RebuildUnknownAnyFunction
9701 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9702
9703 Sema &S;
9704
9705 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9706
9707 ExprResult VisitStmt(Stmt *S) {
9708 llvm_unreachable("unexpected statement!");
9709 return ExprError();
9710 }
9711
Richard Trieu10162ab2011-09-09 03:59:41 +00009712 ExprResult VisitExpr(Expr *E) {
9713 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9714 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009715 return ExprError();
9716 }
9717
9718 /// Rebuild an expression which simply semantically wraps another
9719 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009720 template <class T> ExprResult rebuildSugarExpr(T *E) {
9721 ExprResult SubResult = Visit(E->getSubExpr());
9722 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009723
Richard Trieu10162ab2011-09-09 03:59:41 +00009724 Expr *SubExpr = SubResult.take();
9725 E->setSubExpr(SubExpr);
9726 E->setType(SubExpr->getType());
9727 E->setValueKind(SubExpr->getValueKind());
9728 assert(E->getObjectKind() == OK_Ordinary);
9729 return E;
John McCall2979fe02011-04-12 00:42:48 +00009730 }
9731
Richard Trieu10162ab2011-09-09 03:59:41 +00009732 ExprResult VisitParenExpr(ParenExpr *E) {
9733 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009734 }
9735
Richard Trieu10162ab2011-09-09 03:59:41 +00009736 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9737 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009738 }
9739
Richard Trieu10162ab2011-09-09 03:59:41 +00009740 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9741 ExprResult SubResult = Visit(E->getSubExpr());
9742 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009743
Richard Trieu10162ab2011-09-09 03:59:41 +00009744 Expr *SubExpr = SubResult.take();
9745 E->setSubExpr(SubExpr);
9746 E->setType(S.Context.getPointerType(SubExpr->getType()));
9747 assert(E->getValueKind() == VK_RValue);
9748 assert(E->getObjectKind() == OK_Ordinary);
9749 return E;
John McCall2979fe02011-04-12 00:42:48 +00009750 }
9751
Richard Trieu10162ab2011-09-09 03:59:41 +00009752 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9753 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009754
Richard Trieu10162ab2011-09-09 03:59:41 +00009755 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009756
Richard Trieu10162ab2011-09-09 03:59:41 +00009757 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009758 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009759 !(isa<CXXMethodDecl>(VD) &&
9760 cast<CXXMethodDecl>(VD)->isInstance()))
9761 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009762
Richard Trieu10162ab2011-09-09 03:59:41 +00009763 return E;
John McCall2979fe02011-04-12 00:42:48 +00009764 }
9765
Richard Trieu10162ab2011-09-09 03:59:41 +00009766 ExprResult VisitMemberExpr(MemberExpr *E) {
9767 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009768 }
9769
Richard Trieu10162ab2011-09-09 03:59:41 +00009770 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9771 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009772 }
9773 };
9774}
9775
9776/// Given a function expression of unknown-any type, try to rebuild it
9777/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009778static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9779 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9780 if (Result.isInvalid()) return ExprError();
9781 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009782}
9783
9784namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009785 /// A visitor for rebuilding an expression of type __unknown_anytype
9786 /// into one which resolves the type directly on the referring
9787 /// expression. Strict preservation of the original source
9788 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009789 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009790 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009791
9792 Sema &S;
9793
9794 /// The current destination type.
9795 QualType DestType;
9796
Richard Trieu10162ab2011-09-09 03:59:41 +00009797 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9798 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009799
John McCall39439732011-04-09 22:50:59 +00009800 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009801 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009802 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009803 }
9804
Richard Trieu10162ab2011-09-09 03:59:41 +00009805 ExprResult VisitExpr(Expr *E) {
9806 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9807 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009808 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009809 }
9810
Richard Trieu10162ab2011-09-09 03:59:41 +00009811 ExprResult VisitCallExpr(CallExpr *E);
9812 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009813
John McCall39439732011-04-09 22:50:59 +00009814 /// Rebuild an expression which simply semantically wraps another
9815 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009816 template <class T> ExprResult rebuildSugarExpr(T *E) {
9817 ExprResult SubResult = Visit(E->getSubExpr());
9818 if (SubResult.isInvalid()) return ExprError();
9819 Expr *SubExpr = SubResult.take();
9820 E->setSubExpr(SubExpr);
9821 E->setType(SubExpr->getType());
9822 E->setValueKind(SubExpr->getValueKind());
9823 assert(E->getObjectKind() == OK_Ordinary);
9824 return E;
John McCall39439732011-04-09 22:50:59 +00009825 }
John McCall31996342011-04-07 08:22:57 +00009826
Richard Trieu10162ab2011-09-09 03:59:41 +00009827 ExprResult VisitParenExpr(ParenExpr *E) {
9828 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009829 }
9830
Richard Trieu10162ab2011-09-09 03:59:41 +00009831 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9832 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009833 }
9834
Richard Trieu10162ab2011-09-09 03:59:41 +00009835 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9836 const PointerType *Ptr = DestType->getAs<PointerType>();
9837 if (!Ptr) {
9838 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9839 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009840 return ExprError();
9841 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009842 assert(E->getValueKind() == VK_RValue);
9843 assert(E->getObjectKind() == OK_Ordinary);
9844 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009845
9846 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 DestType = Ptr->getPointeeType();
9848 ExprResult SubResult = Visit(E->getSubExpr());
9849 if (SubResult.isInvalid()) return ExprError();
9850 E->setSubExpr(SubResult.take());
9851 return E;
John McCall2979fe02011-04-12 00:42:48 +00009852 }
9853
Richard Trieu10162ab2011-09-09 03:59:41 +00009854 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009855
Richard Trieu10162ab2011-09-09 03:59:41 +00009856 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009857
Richard Trieu10162ab2011-09-09 03:59:41 +00009858 ExprResult VisitMemberExpr(MemberExpr *E) {
9859 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009860 }
John McCall39439732011-04-09 22:50:59 +00009861
Richard Trieu10162ab2011-09-09 03:59:41 +00009862 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9863 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009864 }
9865 };
9866}
9867
John McCall2d2e8702011-04-11 07:02:50 +00009868/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009869ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9870 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009871
9872 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009873 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009874 FK_FunctionPointer,
9875 FK_BlockPointer
9876 };
9877
Richard Trieu10162ab2011-09-09 03:59:41 +00009878 FnKind Kind;
9879 QualType CalleeType = CalleeExpr->getType();
9880 if (CalleeType == S.Context.BoundMemberTy) {
9881 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9882 Kind = FK_MemberFunction;
9883 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9884 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9885 CalleeType = Ptr->getPointeeType();
9886 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009887 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009888 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9889 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009890 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009891 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009892
9893 // Verify that this is a legal result type of a function.
9894 if (DestType->isArrayType() || DestType->isFunctionType()) {
9895 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009896 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009897 diagID = diag::err_block_returning_array_function;
9898
Richard Trieu10162ab2011-09-09 03:59:41 +00009899 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009900 << DestType->isFunctionType() << DestType;
9901 return ExprError();
9902 }
9903
9904 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009905 E->setType(DestType.getNonLValueExprType(S.Context));
9906 E->setValueKind(Expr::getValueKindForType(DestType));
9907 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009908
9909 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009910 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009911 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009912 Proto->arg_type_begin(),
9913 Proto->getNumArgs(),
9914 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009915 else
9916 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009917 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009918
9919 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009920 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009921 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009922 // Nothing to do.
9923 break;
9924
9925 case FK_FunctionPointer:
9926 DestType = S.Context.getPointerType(DestType);
9927 break;
9928
9929 case FK_BlockPointer:
9930 DestType = S.Context.getBlockPointerType(DestType);
9931 break;
9932 }
9933
9934 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009935 ExprResult CalleeResult = Visit(CalleeExpr);
9936 if (!CalleeResult.isUsable()) return ExprError();
9937 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009938
9939 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009940 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009941}
9942
Richard Trieu10162ab2011-09-09 03:59:41 +00009943ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009944 // Verify that this is a legal result type of a call.
9945 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009946 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009947 << DestType->isFunctionType() << DestType;
9948 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009949 }
9950
John McCall3f4138c2011-07-13 17:56:40 +00009951 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009952 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9953 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9954 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009955 }
John McCall2979fe02011-04-12 00:42:48 +00009956
John McCall2d2e8702011-04-11 07:02:50 +00009957 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009958 E->setType(DestType.getNonReferenceType());
9959 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009960
Richard Trieu10162ab2011-09-09 03:59:41 +00009961 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009962}
9963
Richard Trieu10162ab2011-09-09 03:59:41 +00009964ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009965 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +00009966 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9967 assert(E->getValueKind() == VK_RValue);
9968 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009969
Richard Trieu10162ab2011-09-09 03:59:41 +00009970 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009971
John McCall2d2e8702011-04-11 07:02:50 +00009972 // Rebuild the sub-expression as the pointee (function) type.
9973 DestType = DestType->castAs<PointerType>()->getPointeeType();
9974
Richard Trieu10162ab2011-09-09 03:59:41 +00009975 ExprResult Result = Visit(E->getSubExpr());
9976 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009977
Richard Trieu10162ab2011-09-09 03:59:41 +00009978 E->setSubExpr(Result.take());
9979 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +00009980}
9981
Richard Trieu10162ab2011-09-09 03:59:41 +00009982ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9983 ExprValueKind ValueKind = VK_LValue;
9984 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +00009985
9986 // We know how to make this work for certain kinds of decls:
9987
9988 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +00009989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9990 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9991 DestType = Ptr->getPointeeType();
9992 ExprResult Result = resolveDecl(E, VD);
9993 if (Result.isInvalid()) return ExprError();
9994 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +00009995 CK_FunctionToPointerDecay, VK_RValue);
9996 }
9997
Richard Trieu10162ab2011-09-09 03:59:41 +00009998 if (!Type->isFunctionType()) {
9999 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10000 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010001 return ExprError();
10002 }
John McCall2d2e8702011-04-11 07:02:50 +000010003
Richard Trieu10162ab2011-09-09 03:59:41 +000010004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10005 if (MD->isInstance()) {
10006 ValueKind = VK_RValue;
10007 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010008 }
10009
John McCall2d2e8702011-04-11 07:02:50 +000010010 // Function references aren't l-values in C.
10011 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010012 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010013
10014 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010015 } else if (isa<VarDecl>(VD)) {
10016 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10017 Type = RefTy->getPointeeType();
10018 } else if (Type->isFunctionType()) {
10019 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10020 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010021 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010022 }
10023
10024 // - nothing else
10025 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010026 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10027 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010028 return ExprError();
10029 }
10030
Richard Trieu10162ab2011-09-09 03:59:41 +000010031 VD->setType(DestType);
10032 E->setType(Type);
10033 E->setValueKind(ValueKind);
10034 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010035}
10036
John McCall31996342011-04-07 08:22:57 +000010037/// Check a cast of an unknown-any type. We intentionally only
10038/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010039ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10040 Expr *CastExpr, CastKind &CastKind,
10041 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010042 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010043 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010044 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010045
Richard Trieuba63ce62011-09-09 01:45:06 +000010046 CastExpr = result.take();
10047 VK = CastExpr->getValueKind();
10048 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010049
Richard Trieuba63ce62011-09-09 01:45:06 +000010050 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010051}
10052
Richard Trieuba63ce62011-09-09 01:45:06 +000010053static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10054 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010055 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010056 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010057 E = E->IgnoreParenImpCasts();
10058 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10059 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010060 diagID = diag::err_uncasted_call_of_unknown_any;
10061 } else {
John McCall31996342011-04-07 08:22:57 +000010062 break;
John McCall2d2e8702011-04-11 07:02:50 +000010063 }
John McCall31996342011-04-07 08:22:57 +000010064 }
10065
John McCall2d2e8702011-04-11 07:02:50 +000010066 SourceLocation loc;
10067 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010068 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010069 loc = ref->getLocation();
10070 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010071 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010072 loc = mem->getMemberLoc();
10073 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010074 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010075 diagID = diag::err_uncasted_call_of_unknown_any;
10076 loc = msg->getSelectorLoc();
10077 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010078 if (!d) {
10079 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10080 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10081 << orig->getSourceRange();
10082 return ExprError();
10083 }
John McCall2d2e8702011-04-11 07:02:50 +000010084 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010085 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10086 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010087 return ExprError();
10088 }
10089
10090 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010091
10092 // Never recoverable.
10093 return ExprError();
10094}
10095
John McCall36e7fe32010-10-12 00:20:44 +000010096/// Check for operands with placeholder types and complain if found.
10097/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010098ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010099 // Placeholder types are always *exactly* the appropriate builtin type.
10100 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010101
John McCall31996342011-04-07 08:22:57 +000010102 // Overloaded expressions.
10103 if (type == Context.OverloadTy)
10104 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010105 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010106 QualType(),
10107 diag::err_ovl_unresolvable);
10108
John McCall0009fcc2011-04-26 20:42:42 +000010109 // Bound member functions.
10110 if (type == Context.BoundMemberTy) {
10111 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10112 << E->getSourceRange();
10113 return ExprError();
10114 }
10115
John McCall31996342011-04-07 08:22:57 +000010116 // Expressions of unknown type.
10117 if (type == Context.UnknownAnyTy)
10118 return diagnoseUnknownAnyExpr(*this, E);
10119
10120 assert(!type->isPlaceholderType());
10121 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010122}
Richard Trieu2c850c02011-04-21 21:44:26 +000010123
Richard Trieuba63ce62011-09-09 01:45:06 +000010124bool Sema::CheckCaseExpression(Expr *E) {
10125 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010126 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010127 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10128 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010129 return false;
10130}