blob: 56abdfbcd32b7a5bceca1d36bcb3604dc07d3133 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000042
David Chisnall9f57c292009-08-17 16:35:33 +000043
Douglas Gregor171c45a2009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor171c45a2009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000058///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith30482bc2011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000084 }
85
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
90 Diag(D->getLocation(), diag::note_unavailable_here) << true;
91 return true;
92 }
Douglas Gregorde681d42009-02-24 04:26:15 +000093 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000094
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
107 if (Message.empty()) {
108 if (!UnknownObjCClass)
109 Diag(Loc, diag::err_unavailable) << D->getDeclName();
110 else
111 Diag(Loc, diag::warn_unavailable_fwdclass_message)
112 << D->getDeclName();
113 }
114 else
115 Diag(Loc, diag::err_unavailable_message)
116 << D->getDeclName() << Message;
117 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
118 break;
119 }
120
Anders Carlsson73067a02010-10-22 23:37:08 +0000121 // Warn if this is used but marked unused.
122 if (D->hasAttr<UnusedAttr>())
123 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
124
Douglas Gregor171c45a2009-02-18 21:56:37 +0000125 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000126}
127
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000128/// \brief Retrieve the message suffix that should be added to a
129/// diagnostic complaining about the given function being deleted or
130/// unavailable.
131std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
132 // FIXME: C++0x implicitly-deleted special member functions could be
133 // detected here so that we could improve diagnostics to say, e.g.,
134 // "base class 'A' had a deleted copy constructor".
135 if (FD->isDeleted())
136 return std::string();
137
138 std::string Message;
139 if (FD->getAvailability(&Message))
140 return ": " + Message;
141
142 return std::string();
143}
144
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000145/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000146/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000147/// attribute. It warns if call does not have the sentinel argument.
148///
149void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000150 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000151 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000152 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000153 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000154
155 // FIXME: In C++0x, if any of the arguments are parameter pack
156 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 int sentinelPos = attr->getSentinel();
158 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Mike Stump87c57ac2009-05-16 07:39:55 +0000160 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
161 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
246 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
247 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000248}
249
Douglas Gregor87f95b02009-02-26 21:00:50 +0000250SourceRange Sema::getExprRange(ExprTy *E) const {
251 Expr *Ex = (Expr *)E;
252 return Ex? Ex->getSourceRange() : SourceRange();
253}
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);
John McCall34376a62010-12-04 03:47:34 +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();
353
Ted Kremenekdf26df72011-03-01 18:41:00 +0000354 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000355
John Wiegley01296292011-04-08 18:41:53 +0000356 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
357 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000358}
359
John Wiegley01296292011-04-08 18:41:53 +0000360ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
361 ExprResult Res = DefaultFunctionArrayConversion(E);
362 if (Res.isInvalid())
363 return ExprError();
364 Res = DefaultLvalueConversion(Res.take());
365 if (Res.isInvalid())
366 return ExprError();
367 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000368}
369
370
Chris Lattner513165e2008-07-25 21:10:04 +0000371/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000372/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000373/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000374/// apply if the array is an argument to the sizeof or address (&) operators.
375/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000376ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000377 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000378 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
379 if (Res.isInvalid())
380 return Owned(E);
381 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000382
383 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000384 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000385
386 // Try to perform integral promotions if the object has a theoretically
387 // promotable type.
388 if (Ty->isIntegralOrUnscopedEnumerationType()) {
389 // C99 6.3.1.1p2:
390 //
391 // The following may be used in an expression wherever an int or
392 // unsigned int may be used:
393 // - an object or expression with an integer type whose integer
394 // conversion rank is less than or equal to the rank of int
395 // and unsigned int.
396 // - A bit-field of type _Bool, int, signed int, or unsigned int.
397 //
398 // If an int can represent all values of the original type, the
399 // value is converted to an int; otherwise, it is converted to an
400 // unsigned int. These are called the integer promotions. All
401 // other types are unchanged by the integer promotions.
402
403 QualType PTy = Context.isPromotableBitField(E);
404 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000405 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
406 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000407 }
408 if (Ty->isPromotableIntegerType()) {
409 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
411 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000412 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000413 }
John Wiegley01296292011-04-08 18:41:53 +0000414 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000415}
416
Chris Lattner2ce500f2008-07-25 22:25:12 +0000417/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000418/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000419/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000420ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
421 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000422 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000423
John Wiegley01296292011-04-08 18:41:53 +0000424 ExprResult Res = UsualUnaryConversions(E);
425 if (Res.isInvalid())
426 return Owned(E);
427 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000428
Chris Lattner2ce500f2008-07-25 22:25:12 +0000429 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000430 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
432
433 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000434}
435
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000436/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
437/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000438/// interfaces passed by value.
439ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000440 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000441 ExprResult ExprRes = DefaultArgumentPromotion(E);
442 if (ExprRes.isInvalid())
443 return ExprError();
444 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000445
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000446 // __builtin_va_start takes the second argument as a "varargs" argument, but
447 // it doesn't actually do anything with it. It doesn't need to be non-pod
448 // etc.
449 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000450 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000451
John Wiegley01296292011-04-08 18:41:53 +0000452 if (E->getType()->isObjCObjectType() &&
453 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000454 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000455 << E->getType() << CT))
456 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000457
John Wiegley01296292011-04-08 18:41:53 +0000458 if (!E->getType()->isPODType() &&
459 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000460 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000461 << E->getType() << CT))
462 return ExprError();
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000463
John Wiegley01296292011-04-08 18:41:53 +0000464 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000465}
466
Chris Lattner513165e2008-07-25 21:10:04 +0000467/// UsualArithmeticConversions - Performs various conversions that are common to
468/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000469/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000470/// responsible for emitting appropriate error diagnostics.
471/// FIXME: verify the conversion rules for "complex int" are consistent with
472/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000473QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000474 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000475 if (!isCompAssign) {
476 lhsExpr = UsualUnaryConversions(lhsExpr.take());
477 if (lhsExpr.isInvalid())
478 return QualType();
479 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000480
John Wiegley01296292011-04-08 18:41:53 +0000481 rhsExpr = UsualUnaryConversions(rhsExpr.take());
482 if (rhsExpr.isInvalid())
483 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000484
Mike Stump11289f42009-09-09 15:08:12 +0000485 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000486 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000487 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000488 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000489 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000490 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000491
492 // If both types are identical, no conversion is needed.
493 if (lhs == rhs)
494 return lhs;
495
496 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
497 // The caller can deal with this (e.g. pointer + int).
498 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
499 return lhs;
500
John McCalld005ac92010-11-13 08:17:45 +0000501 // Apply unary and bitfield promotions to the LHS's type.
502 QualType lhs_unpromoted = lhs;
503 if (lhs->isPromotableIntegerType())
504 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000505 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000506 if (!LHSBitfieldPromoteTy.isNull())
507 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000508 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000509 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000510
John McCalld005ac92010-11-13 08:17:45 +0000511 // If both types are identical, no conversion is needed.
512 if (lhs == rhs)
513 return lhs;
514
515 // At this point, we have two different arithmetic types.
516
517 // Handle complex types first (C99 6.3.1.8p1).
518 bool LHSComplexFloat = lhs->isComplexType();
519 bool RHSComplexFloat = rhs->isComplexType();
520 if (LHSComplexFloat || RHSComplexFloat) {
521 // if we have an integer operand, the result is the complex type.
522
John McCallc5e62b42010-11-13 09:02:35 +0000523 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
524 if (rhs->isIntegerType()) {
525 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000526 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
527 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000528 } else {
529 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000530 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000531 }
John McCalld005ac92010-11-13 08:17:45 +0000532 return lhs;
533 }
534
John McCallc5e62b42010-11-13 09:02:35 +0000535 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
536 if (!isCompAssign) {
537 // int -> float -> _Complex float
538 if (lhs->isIntegerType()) {
539 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000540 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
541 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000542 } else {
543 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000544 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000545 }
546 }
John McCalld005ac92010-11-13 08:17:45 +0000547 return rhs;
548 }
549
550 // This handles complex/complex, complex/float, or float/complex.
551 // When both operands are complex, the shorter operand is converted to the
552 // type of the longer, and that is the type of the result. This corresponds
553 // to what is done when combining two real floating-point operands.
554 // The fun begins when size promotion occur across type domains.
555 // From H&S 6.3.4: When one operand is complex and the other is a real
556 // floating-point type, the less precise type is converted, within it's
557 // real or complex domain, to the precision of the other type. For example,
558 // when combining a "long double" with a "double _Complex", the
559 // "double _Complex" is promoted to "long double _Complex".
560 int order = Context.getFloatingTypeOrder(lhs, rhs);
561
562 // If both are complex, just cast to the more precise type.
563 if (LHSComplexFloat && RHSComplexFloat) {
564 if (order > 0) {
565 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000566 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000567 return lhs;
568
569 } else if (order < 0) {
570 // _Complex float -> _Complex double
571 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000572 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000573 return rhs;
574 }
575 return lhs;
576 }
577
578 // If just the LHS is complex, the RHS needs to be converted,
579 // and the LHS might need to be promoted.
580 if (LHSComplexFloat) {
581 if (order > 0) { // LHS is wider
582 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000583 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000584 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
585 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000586 return lhs;
587 }
588
589 // RHS is at least as wide. Find its corresponding complex type.
590 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
591
592 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000593 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000594
595 // _Complex float -> _Complex double
596 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000597 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000598
599 return result;
600 }
601
602 // Just the RHS is complex, so the LHS needs to be converted
603 // and the RHS might need to be promoted.
604 assert(RHSComplexFloat);
605
606 if (order < 0) { // RHS is wider
607 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000608 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000609 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000610 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
611 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000612 }
John McCalld005ac92010-11-13 08:17:45 +0000613 return rhs;
614 }
615
616 // LHS is at least as wide. Find its corresponding complex type.
617 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
618
619 // double -> _Complex double
620 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000621 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000622
623 // _Complex float -> _Complex double
624 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000625 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000626
627 return result;
628 }
629
630 // Now handle "real" floating types (i.e. float, double, long double).
631 bool LHSFloat = lhs->isRealFloatingType();
632 bool RHSFloat = rhs->isRealFloatingType();
633 if (LHSFloat || RHSFloat) {
634 // If we have two real floating types, convert the smaller operand
635 // to the bigger result.
636 if (LHSFloat && RHSFloat) {
637 int order = Context.getFloatingTypeOrder(lhs, rhs);
638 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000639 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000640 return lhs;
641 }
642
643 assert(order < 0 && "illegal float comparison");
644 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000645 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000646 return rhs;
647 }
648
649 // If we have an integer operand, the result is the real floating type.
650 if (LHSFloat) {
651 if (rhs->isIntegerType()) {
652 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000653 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000654 return lhs;
655 }
656
657 // Convert both sides to the appropriate complex float.
658 assert(rhs->isComplexIntegerType());
659 QualType result = Context.getComplexType(lhs);
660
661 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000662 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000663
664 // float -> _Complex float
665 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000666 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000667
668 return result;
669 }
670
671 assert(RHSFloat);
672 if (lhs->isIntegerType()) {
673 // Convert lhs to the rhs floating point type.
674 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000675 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000676 return rhs;
677 }
678
679 // Convert both sides to the appropriate complex float.
680 assert(lhs->isComplexIntegerType());
681 QualType result = Context.getComplexType(rhs);
682
683 // _Complex int -> _Complex float
684 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000686
687 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000688 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000689
690 return result;
691 }
692
693 // Handle GCC complex int extension.
694 // FIXME: if the operands are (int, _Complex long), we currently
695 // don't promote the complex. Also, signedness?
696 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
697 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
698 if (lhsComplexInt && rhsComplexInt) {
699 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
700 rhsComplexInt->getElementType());
701 assert(order && "inequal types with equal element ordering");
702 if (order > 0) {
703 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000704 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000705 return lhs;
706 }
707
708 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000709 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000710 return rhs;
711 } else if (lhsComplexInt) {
712 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000713 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000714 return lhs;
715 } else if (rhsComplexInt) {
716 // int -> _Complex int
717 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000719 return rhs;
720 }
721
722 // Finally, we have two differing integer types.
723 // The rules for this case are in C99 6.3.1.8
724 int compare = Context.getIntegerTypeOrder(lhs, rhs);
725 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
726 rhsSigned = rhs->hasSignedIntegerRepresentation();
727 if (lhsSigned == rhsSigned) {
728 // Same signedness; use the higher-ranked type
729 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000730 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000731 return lhs;
732 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000733 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000734 return rhs;
735 } else if (compare != (lhsSigned ? 1 : -1)) {
736 // The unsigned type has greater than or equal rank to the
737 // signed type, so use the unsigned type
738 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000740 return lhs;
741 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000742 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000743 return rhs;
744 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
745 // The two types are different widths; if we are here, that
746 // means the signed type is larger than the unsigned type, so
747 // use the signed type.
748 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000749 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000750 return lhs;
751 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000752 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000753 return rhs;
754 } else {
755 // The signed type is higher-ranked than the unsigned type,
756 // but isn't actually any bigger (like unsigned int and long
757 // on most 32-bit systems). Use the unsigned type corresponding
758 // to the signed type.
759 QualType result =
760 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000761 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000762 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000763 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000764 return result;
765 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000766}
767
Chris Lattner513165e2008-07-25 21:10:04 +0000768//===----------------------------------------------------------------------===//
769// Semantic Analysis for various Expression Types
770//===----------------------------------------------------------------------===//
771
772
Peter Collingbourne91147592011-04-15 00:35:48 +0000773ExprResult
774Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
775 SourceLocation DefaultLoc,
776 SourceLocation RParenLoc,
777 Expr *ControllingExpr,
778 MultiTypeArg types,
779 MultiExprArg exprs) {
780 unsigned NumAssocs = types.size();
781 assert(NumAssocs == exprs.size());
782
783 ParsedType *ParsedTypes = types.release();
784 Expr **Exprs = exprs.release();
785
786 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
787 for (unsigned i = 0; i < NumAssocs; ++i) {
788 if (ParsedTypes[i])
789 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
790 else
791 Types[i] = 0;
792 }
793
794 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
795 ControllingExpr, Types, Exprs,
796 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000797 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000798 return ER;
799}
800
801ExprResult
802Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
803 SourceLocation DefaultLoc,
804 SourceLocation RParenLoc,
805 Expr *ControllingExpr,
806 TypeSourceInfo **Types,
807 Expr **Exprs,
808 unsigned NumAssocs) {
809 bool TypeErrorFound = false,
810 IsResultDependent = ControllingExpr->isTypeDependent(),
811 ContainsUnexpandedParameterPack
812 = ControllingExpr->containsUnexpandedParameterPack();
813
814 for (unsigned i = 0; i < NumAssocs; ++i) {
815 if (Exprs[i]->containsUnexpandedParameterPack())
816 ContainsUnexpandedParameterPack = true;
817
818 if (Types[i]) {
819 if (Types[i]->getType()->containsUnexpandedParameterPack())
820 ContainsUnexpandedParameterPack = true;
821
822 if (Types[i]->getType()->isDependentType()) {
823 IsResultDependent = true;
824 } else {
825 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
826 // complete object type other than a variably modified type."
827 unsigned D = 0;
828 if (Types[i]->getType()->isIncompleteType())
829 D = diag::err_assoc_type_incomplete;
830 else if (!Types[i]->getType()->isObjectType())
831 D = diag::err_assoc_type_nonobject;
832 else if (Types[i]->getType()->isVariablyModifiedType())
833 D = diag::err_assoc_type_variably_modified;
834
835 if (D != 0) {
836 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
837 << Types[i]->getTypeLoc().getSourceRange()
838 << Types[i]->getType();
839 TypeErrorFound = true;
840 }
841
842 // C1X 6.5.1.1p2 "No two generic associations in the same generic
843 // selection shall specify compatible types."
844 for (unsigned j = i+1; j < NumAssocs; ++j)
845 if (Types[j] && !Types[j]->getType()->isDependentType() &&
846 Context.typesAreCompatible(Types[i]->getType(),
847 Types[j]->getType())) {
848 Diag(Types[j]->getTypeLoc().getBeginLoc(),
849 diag::err_assoc_compatible_types)
850 << Types[j]->getTypeLoc().getSourceRange()
851 << Types[j]->getType()
852 << Types[i]->getType();
853 Diag(Types[i]->getTypeLoc().getBeginLoc(),
854 diag::note_compat_assoc)
855 << Types[i]->getTypeLoc().getSourceRange()
856 << Types[i]->getType();
857 TypeErrorFound = true;
858 }
859 }
860 }
861 }
862 if (TypeErrorFound)
863 return ExprError();
864
865 // If we determined that the generic selection is result-dependent, don't
866 // try to compute the result expression.
867 if (IsResultDependent)
868 return Owned(new (Context) GenericSelectionExpr(
869 Context, KeyLoc, ControllingExpr,
870 Types, Exprs, NumAssocs, DefaultLoc,
871 RParenLoc, ContainsUnexpandedParameterPack));
872
873 llvm::SmallVector<unsigned, 1> CompatIndices;
874 unsigned DefaultIndex = -1U;
875 for (unsigned i = 0; i < NumAssocs; ++i) {
876 if (!Types[i])
877 DefaultIndex = i;
878 else if (Context.typesAreCompatible(ControllingExpr->getType(),
879 Types[i]->getType()))
880 CompatIndices.push_back(i);
881 }
882
883 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
884 // type compatible with at most one of the types named in its generic
885 // association list."
886 if (CompatIndices.size() > 1) {
887 // We strip parens here because the controlling expression is typically
888 // parenthesized in macro definitions.
889 ControllingExpr = ControllingExpr->IgnoreParens();
890 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
891 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
892 << (unsigned) CompatIndices.size();
893 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
894 E = CompatIndices.end(); I != E; ++I) {
895 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
896 diag::note_compat_assoc)
897 << Types[*I]->getTypeLoc().getSourceRange()
898 << Types[*I]->getType();
899 }
900 return ExprError();
901 }
902
903 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
904 // its controlling expression shall have type compatible with exactly one of
905 // the types named in its generic association list."
906 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
907 // We strip parens here because the controlling expression is typically
908 // parenthesized in macro definitions.
909 ControllingExpr = ControllingExpr->IgnoreParens();
910 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
911 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
912 return ExprError();
913 }
914
915 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
916 // type name that is compatible with the type of the controlling expression,
917 // then the result expression of the generic selection is the expression
918 // in that generic association. Otherwise, the result expression of the
919 // generic selection is the expression in the default generic association."
920 unsigned ResultIndex =
921 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
922
923 return Owned(new (Context) GenericSelectionExpr(
924 Context, KeyLoc, ControllingExpr,
925 Types, Exprs, NumAssocs, DefaultLoc,
926 RParenLoc, ContainsUnexpandedParameterPack,
927 ResultIndex));
928}
929
Steve Naroff83895f72007-09-16 03:34:24 +0000930/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000931/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
932/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
933/// multiple tokens. However, the common case is that StringToks points to one
934/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000935///
John McCalldadc5752010-08-24 06:29:42 +0000936ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000937Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000938 assert(NumStringToks && "Must have at least one string!");
939
Chris Lattner8a24e582009-01-16 18:51:42 +0000940 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000941 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000942 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000943
Chris Lattner23b7eb62007-06-15 23:05:46 +0000944 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000945 for (unsigned i = 0; i != NumStringToks; ++i)
946 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000947
Chris Lattner36fc8792008-02-11 00:02:17 +0000948 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000949 if (Literal.AnyWide)
950 StrTy = Context.getWCharType();
951 else if (Literal.Pascal)
952 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000953
954 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000955 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000956 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000957
Chris Lattner36fc8792008-02-11 00:02:17 +0000958 // Get an array type for the string, according to C99 6.4.5. This includes
959 // the nul terminator character as well as the string length for pascal
960 // strings.
961 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000962 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000963 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattner5b183d82006-11-10 05:03:26 +0000965 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000966 return Owned(StringLiteral::Create(Context, Literal.GetString(),
967 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +0000968 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +0000969 &StringTokLocs[0],
970 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000971}
972
John McCallc63de662011-02-02 13:00:07 +0000973enum CaptureResult {
974 /// No capture is required.
975 CR_NoCapture,
976
977 /// A capture is required.
978 CR_Capture,
979
John McCall351762c2011-02-07 10:33:21 +0000980 /// A by-ref capture is required.
981 CR_CaptureByRef,
982
John McCallc63de662011-02-02 13:00:07 +0000983 /// An error occurred when trying to capture the given variable.
984 CR_Error
985};
986
987/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000988///
John McCallc63de662011-02-02 13:00:07 +0000989/// \param var - the variable referenced
990/// \param DC - the context which we couldn't capture through
991static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000992diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000993 VarDecl *var, DeclContext *DC) {
994 switch (S.ExprEvalContexts.back().Context) {
995 case Sema::Unevaluated:
996 // The argument will never be evaluated, so don't complain.
997 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000998
John McCallc63de662011-02-02 13:00:07 +0000999 case Sema::PotentiallyEvaluated:
1000 case Sema::PotentiallyEvaluatedIfUsed:
1001 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001002
John McCallc63de662011-02-02 13:00:07 +00001003 case Sema::PotentiallyPotentiallyEvaluated:
1004 // FIXME: delay these!
1005 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
John McCallc63de662011-02-02 13:00:07 +00001008 // Don't diagnose about capture if we're not actually in code right
1009 // now; in general, there are more appropriate places that will
1010 // diagnose this.
1011 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1012
John McCall92d627e2011-03-22 23:15:50 +00001013 // Certain madnesses can happen with parameter declarations, which
1014 // we want to ignore.
1015 if (isa<ParmVarDecl>(var)) {
1016 // - If the parameter still belongs to the translation unit, then
1017 // we're actually just using one parameter in the declaration of
1018 // the next. This is useful in e.g. VLAs.
1019 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1020 return CR_NoCapture;
1021
1022 // - This particular madness can happen in ill-formed default
1023 // arguments; claim it's okay and let downstream code handle it.
1024 if (S.CurContext == var->getDeclContext()->getParent())
1025 return CR_NoCapture;
1026 }
John McCallc63de662011-02-02 13:00:07 +00001027
1028 DeclarationName functionName;
1029 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1030 functionName = fn->getDeclName();
1031 // FIXME: variable from enclosing block that we couldn't capture from!
1032
1033 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1034 << var->getIdentifier() << functionName;
1035 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1036 << var->getIdentifier();
1037
1038 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001039}
1040
John McCall351762c2011-02-07 10:33:21 +00001041/// There is a well-formed capture at a particular scope level;
1042/// propagate it through all the nested blocks.
1043static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1044 const BlockDecl::Capture &capture) {
1045 VarDecl *var = capture.getVariable();
1046
1047 // Update all the inner blocks with the capture information.
1048 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1049 i != e; ++i) {
1050 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1051 innerBlock->Captures.push_back(
1052 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1053 /*nested*/ true, capture.getCopyExpr()));
1054 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1055 }
1056
1057 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1058}
1059
1060/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001061/// given value in the current context requires a variable capture.
1062///
1063/// This also keeps the captures set in the BlockScopeInfo records
1064/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001065static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001066 ValueDecl *value) {
1067 // Only variables ever require capture.
1068 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001069 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001070
1071 // Fast path: variables from the current context never require capture.
1072 DeclContext *DC = S.CurContext;
1073 if (var->getDeclContext() == DC) return CR_NoCapture;
1074
1075 // Only variables with local storage require capture.
1076 // FIXME: What about 'const' variables in C++?
1077 if (!var->hasLocalStorage()) return CR_NoCapture;
1078
1079 // Otherwise, we need to capture.
1080
1081 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001082 do {
1083 // Only blocks (and eventually C++0x closures) can capture; other
1084 // scopes don't work.
1085 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001086 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001087
1088 BlockScopeInfo *blockScope =
1089 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1090 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1091
John McCall351762c2011-02-07 10:33:21 +00001092 // Check whether we've already captured it in this block. If so,
1093 // we're done.
1094 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1095 return propagateCapture(S, functionScopesIndex,
1096 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001097
1098 functionScopesIndex--;
1099 DC = cast<BlockDecl>(DC)->getDeclContext();
1100 } while (var->getDeclContext() != DC);
1101
John McCall351762c2011-02-07 10:33:21 +00001102 // Okay, we descended all the way to the block that defines the variable.
1103 // Actually try to capture it.
1104 QualType type = var->getType();
1105
1106 // Prohibit variably-modified types.
1107 if (type->isVariablyModifiedType()) {
1108 S.Diag(loc, diag::err_ref_vm_type);
1109 S.Diag(var->getLocation(), diag::note_declared_at);
1110 return CR_Error;
1111 }
1112
1113 // Prohibit arrays, even in __block variables, but not references to
1114 // them.
1115 if (type->isArrayType()) {
1116 S.Diag(loc, diag::err_ref_array_type);
1117 S.Diag(var->getLocation(), diag::note_declared_at);
1118 return CR_Error;
1119 }
1120
1121 S.MarkDeclarationReferenced(loc, var);
1122
1123 // The BlocksAttr indicates the variable is bound by-reference.
1124 bool byRef = var->hasAttr<BlocksAttr>();
1125
1126 // Build a copy expression.
1127 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001128 const RecordType *rtype;
1129 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1130 (rtype = type->getAs<RecordType>())) {
1131
1132 // The capture logic needs the destructor, so make sure we mark it.
1133 // Usually this is unnecessary because most local variables have
1134 // their destructors marked at declaration time, but parameters are
1135 // an exception because it's technically only the call site that
1136 // actually requires the destructor.
1137 if (isa<ParmVarDecl>(var))
1138 S.FinalizeVarWithDestructor(var, rtype);
1139
John McCall351762c2011-02-07 10:33:21 +00001140 // According to the blocks spec, the capture of a variable from
1141 // the stack requires a const copy constructor. This is not true
1142 // of the copy/move done to move a __block variable to the heap.
1143 type.addConst();
1144
1145 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1146 ExprResult result =
1147 S.PerformCopyInitialization(
1148 InitializedEntity::InitializeBlock(var->getLocation(),
1149 type, false),
1150 loc, S.Owned(declRef));
1151
1152 // Build a full-expression copy expression if initialization
1153 // succeeded and used a non-trivial constructor. Recover from
1154 // errors by pretending that the copy isn't necessary.
1155 if (!result.isInvalid() &&
1156 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1157 result = S.MaybeCreateExprWithCleanups(result);
1158 copyExpr = result.take();
1159 }
1160 }
1161
1162 // We're currently at the declarer; go back to the closure.
1163 functionScopesIndex++;
1164 BlockScopeInfo *blockScope =
1165 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1166
1167 // Build a valid capture in this scope.
1168 blockScope->Captures.push_back(
1169 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1170 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1171
1172 // Propagate that to inner captures if necessary.
1173 return propagateCapture(S, functionScopesIndex,
1174 blockScope->Captures.back());
1175}
1176
1177static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1178 const DeclarationNameInfo &NameInfo,
1179 bool byRef) {
1180 assert(isa<VarDecl>(vd) && "capturing non-variable");
1181
1182 VarDecl *var = cast<VarDecl>(vd);
1183 assert(var->hasLocalStorage() && "capturing non-local");
1184 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1185
1186 QualType exprType = var->getType().getNonReferenceType();
1187
1188 BlockDeclRefExpr *BDRE;
1189 if (!byRef) {
1190 // The variable will be bound by copy; make it const within the
1191 // closure, but record that this was done in the expression.
1192 bool constAdded = !exprType.isConstQualified();
1193 exprType.addConst();
1194
1195 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1196 NameInfo.getLoc(), false,
1197 constAdded);
1198 } else {
1199 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1200 NameInfo.getLoc(), true);
1201 }
1202
1203 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001204}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001205
John McCalldadc5752010-08-24 06:29:42 +00001206ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001207Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001208 SourceLocation Loc,
1209 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001210 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001211 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001212}
1213
John McCallf4cd4f92011-02-09 01:13:10 +00001214/// BuildDeclRefExpr - Build an expression that references a
1215/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001216ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001217Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001218 const DeclarationNameInfo &NameInfo,
1219 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001220 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001221
John McCall086a4642010-11-24 05:12:34 +00001222 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001223 SS? SS->getWithLocInContext(Context)
1224 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001225 D, NameInfo, Ty, VK);
1226
1227 // Just in case we're building an illegal pointer-to-member.
1228 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1229 E->setObjectKind(OK_BitField);
1230
1231 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001232}
1233
John McCallfeb624a2010-11-23 20:48:44 +00001234static ExprResult
1235BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1236 const CXXScopeSpec &SS, FieldDecl *Field,
1237 DeclAccessPair FoundDecl,
1238 const DeclarationNameInfo &MemberNameInfo);
1239
John McCalldadc5752010-08-24 06:29:42 +00001240ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001241Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1242 SourceLocation loc,
1243 IndirectFieldDecl *indirectField,
1244 Expr *baseObjectExpr,
1245 SourceLocation opLoc) {
1246 // First, build the expression that refers to the base object.
1247
1248 bool baseObjectIsPointer = false;
1249 Qualifiers baseQuals;
1250
1251 // Case 1: the base of the indirect field is not a field.
1252 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001253 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001254 if (baseVariable) {
1255 assert(baseVariable->getType()->isRecordType());
1256
1257 // In principle we could have a member access expression that
1258 // accesses an anonymous struct/union that's a static member of
1259 // the base object's class. However, under the current standard,
1260 // static data members cannot be anonymous structs or unions.
1261 // Supporting this is as easy as building a MemberExpr here.
1262 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1263
1264 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1265
1266 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001267 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001268 if (result.isInvalid()) return ExprError();
1269
1270 baseObjectExpr = result.take();
1271 baseObjectIsPointer = false;
1272 baseQuals = baseObjectExpr->getType().getQualifiers();
1273
1274 // Case 2: the base of the indirect field is a field and the user
1275 // wrote a member expression.
1276 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001277 // The caller provided the base object expression. Determine
1278 // whether its a pointer and whether it adds any qualifiers to the
1279 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001280 QualType objectType = baseObjectExpr->getType();
1281
1282 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1283 baseObjectIsPointer = true;
1284 objectType = ptr->getPointeeType();
1285 } else {
1286 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001287 }
John McCallf3a88602011-02-03 08:15:49 +00001288 baseQuals = objectType.getQualifiers();
1289
1290 // Case 3: the base of the indirect field is a field and we should
1291 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001292 } else {
1293 // We've found a member of an anonymous struct/union that is
1294 // inside a non-anonymous struct/union, so in a well-formed
1295 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001296 CXXMethodDecl *method = tryCaptureCXXThis();
1297 if (!method) {
1298 Diag(loc, diag::err_invalid_member_use_in_static_method)
1299 << indirectField->getDeclName();
1300 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001301 }
1302
John McCallf3a88602011-02-03 08:15:49 +00001303 // Our base object expression is "this".
1304 baseObjectExpr =
1305 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1306 /*isImplicit=*/ true);
1307 baseObjectIsPointer = true;
1308 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001309 }
1310
1311 // Build the implicit member references to the field of the
1312 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001313 Expr *result = baseObjectExpr;
1314 IndirectFieldDecl::chain_iterator
1315 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001316
John McCallf3a88602011-02-03 08:15:49 +00001317 // Build the first member access in the chain with full information.
1318 if (!baseVariable) {
1319 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001320
John McCallf3a88602011-02-03 08:15:49 +00001321 // FIXME: use the real found-decl info!
1322 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001323
John McCallf3a88602011-02-03 08:15:49 +00001324 // Make a nameInfo that properly uses the anonymous name.
1325 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001326
John McCallf3a88602011-02-03 08:15:49 +00001327 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001328 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001329 memberNameInfo).take();
1330 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001331
John McCallf3a88602011-02-03 08:15:49 +00001332 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001333 }
1334
John McCallf3a88602011-02-03 08:15:49 +00001335 // In all cases, we should now skip the first declaration in the chain.
1336 ++FI;
1337
Douglas Gregore10f36d2011-02-18 02:44:58 +00001338 while (FI != FEnd) {
1339 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001340
1341 // FIXME: these are somewhat meaningless
1342 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1343 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001344
1345 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001346 (FI == FEnd? SS : EmptySS), field,
1347 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001348 .take();
1349 }
1350
1351 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001352}
1353
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001354/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001355/// possibly a list of template arguments.
1356///
1357/// If this produces template arguments, it is permitted to call
1358/// DecomposeTemplateName.
1359///
1360/// This actually loses a lot of source location information for
1361/// non-standard name kinds; we should consider preserving that in
1362/// some way.
1363static void DecomposeUnqualifiedId(Sema &SemaRef,
1364 const UnqualifiedId &Id,
1365 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001366 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001367 const TemplateArgumentListInfo *&TemplateArgs) {
1368 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1369 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1370 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1371
1372 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1373 Id.TemplateId->getTemplateArgs(),
1374 Id.TemplateId->NumArgs);
1375 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1376 TemplateArgsPtr.release();
1377
John McCall3e56fd42010-08-23 07:28:44 +00001378 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001379 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1380 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001381 TemplateArgs = &Buffer;
1382 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001383 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001384 TemplateArgs = 0;
1385 }
1386}
1387
John McCall2d74de92009-12-01 22:10:20 +00001388/// Determines if the given class is provably not derived from all of
1389/// the prospective base classes.
1390static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1391 CXXRecordDecl *Record,
1392 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001393 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001394 return false;
1395
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001396 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001397 if (!RD) return false;
1398 Record = cast<CXXRecordDecl>(RD);
1399
John McCall2d74de92009-12-01 22:10:20 +00001400 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1401 E = Record->bases_end(); I != E; ++I) {
1402 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1403 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1404 if (!BaseRT) return false;
1405
1406 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001407 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1408 return false;
1409 }
1410
1411 return true;
1412}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001413
John McCall2d74de92009-12-01 22:10:20 +00001414enum IMAKind {
1415 /// The reference is definitely not an instance member access.
1416 IMA_Static,
1417
1418 /// The reference may be an implicit instance member access.
1419 IMA_Mixed,
1420
1421 /// The reference may be to an instance member, but it is invalid if
1422 /// so, because the context is not an instance method.
1423 IMA_Mixed_StaticContext,
1424
1425 /// The reference may be to an instance member, but it is invalid if
1426 /// so, because the context is from an unrelated class.
1427 IMA_Mixed_Unrelated,
1428
1429 /// The reference is definitely an implicit instance member access.
1430 IMA_Instance,
1431
1432 /// The reference may be to an unresolved using declaration.
1433 IMA_Unresolved,
1434
1435 /// The reference may be to an unresolved using declaration and the
1436 /// context is not an instance method.
1437 IMA_Unresolved_StaticContext,
1438
John McCall2d74de92009-12-01 22:10:20 +00001439 /// All possible referrents are instance members and the current
1440 /// context is not an instance method.
1441 IMA_Error_StaticContext,
1442
1443 /// All possible referrents are instance members of an unrelated
1444 /// class.
1445 IMA_Error_Unrelated
1446};
1447
1448/// The given lookup names class member(s) and is not being used for
1449/// an address-of-member expression. Classify the type of access
1450/// according to whether it's possible that this reference names an
1451/// instance member. This is best-effort; it is okay to
1452/// conservatively answer "yes", in which case some errors will simply
1453/// not be caught until template-instantiation.
1454static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1455 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001456 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001457
John McCall87fe5d52010-05-20 01:18:31 +00001458 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001459 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001460 (!isa<CXXMethodDecl>(DC) ||
1461 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001462
1463 if (R.isUnresolvableResult())
1464 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1465
1466 // Collect all the declaring classes of instance members we find.
1467 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001468 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001469 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1470 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001471 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001472
John McCalla8ae2222010-04-06 21:38:20 +00001473 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001474 if (dyn_cast<FieldDecl>(D))
1475 hasField = true;
1476
John McCall2d74de92009-12-01 22:10:20 +00001477 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001478 Classes.insert(R->getCanonicalDecl());
1479 }
1480 else
1481 hasNonInstance = true;
1482 }
1483
1484 // If we didn't find any instance members, it can't be an implicit
1485 // member reference.
1486 if (Classes.empty())
1487 return IMA_Static;
1488
1489 // If the current context is not an instance method, it can't be
1490 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001491 if (isStaticContext) {
1492 if (hasNonInstance)
1493 return IMA_Mixed_StaticContext;
1494
1495 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1496 // C++0x [expr.prim.general]p10:
1497 // An id-expression that denotes a non-static data member or non-static
1498 // member function of a class can only be used:
1499 // (...)
1500 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1501 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1502 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1503 if (isUnevaluatedExpression)
1504 return IMA_Mixed_StaticContext;
1505 }
1506
1507 return IMA_Error_StaticContext;
1508 }
John McCall2d74de92009-12-01 22:10:20 +00001509
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001510 CXXRecordDecl *
1511 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1512
1513 // [class.mfct.non-static]p3:
1514 // ...is used in the body of a non-static member function of class X,
1515 // if name lookup (3.4.1) resolves the name in the id-expression to a
1516 // non-static non-type member of some class C [...]
1517 // ...if C is not X or a base class of X, the class member access expression
1518 // is ill-formed.
1519 if (R.getNamingClass() &&
1520 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1521 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1522 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1523
John McCall2d74de92009-12-01 22:10:20 +00001524 // If we can prove that the current context is unrelated to all the
1525 // declaring classes, it can't be an implicit member reference (in
1526 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001527 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001528 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1529
1530 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1531}
1532
1533/// Diagnose a reference to a field with no object available.
1534static void DiagnoseInstanceReference(Sema &SemaRef,
1535 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001536 NamedDecl *rep,
1537 const DeclarationNameInfo &nameInfo) {
1538 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001539 SourceRange Range(Loc);
1540 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1541
John McCallf3a88602011-02-03 08:15:49 +00001542 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001543 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1544 if (MD->isStatic()) {
1545 // "invalid use of member 'x' in static member function"
1546 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001547 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001548 return;
1549 }
1550 }
1551
1552 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001553 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001554 return;
1555 }
1556
1557 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001558}
1559
John McCalld681c392009-12-16 08:11:27 +00001560/// Diagnose an empty lookup.
1561///
1562/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001563bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1564 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001565 DeclarationName Name = R.getLookupName();
1566
John McCalld681c392009-12-16 08:11:27 +00001567 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001568 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001569 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1570 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001571 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001572 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001573 diagnostic_suggest = diag::err_undeclared_use_suggest;
1574 }
John McCalld681c392009-12-16 08:11:27 +00001575
Douglas Gregor598b08f2009-12-31 05:20:13 +00001576 // If the original lookup was an unqualified lookup, fake an
1577 // unqualified lookup. This is useful when (for example) the
1578 // original lookup would not have found something because it was a
1579 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001580 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001581 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001582 if (isa<CXXRecordDecl>(DC)) {
1583 LookupQualifiedName(R, DC);
1584
1585 if (!R.empty()) {
1586 // Don't give errors about ambiguities in this lookup.
1587 R.suppressDiagnostics();
1588
1589 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1590 bool isInstance = CurMethod &&
1591 CurMethod->isInstance() &&
1592 DC == CurMethod->getParent();
1593
1594 // Give a code modification hint to insert 'this->'.
1595 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1596 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001597 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001598 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1599 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001600 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001601 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001602 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001603 Diag(R.getNameLoc(), diagnostic) << Name
1604 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1605 QualType DepThisType = DepMethod->getThisType(Context);
1606 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1607 R.getNameLoc(), DepThisType, false);
1608 TemplateArgumentListInfo TList;
1609 if (ULE->hasExplicitTemplateArgs())
1610 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001611
Douglas Gregore16af532011-02-28 18:50:33 +00001612 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001613 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001614 CXXDependentScopeMemberExpr *DepExpr =
1615 CXXDependentScopeMemberExpr::Create(
1616 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001617 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001618 R.getLookupNameInfo(), &TList);
1619 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001620 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001621 // FIXME: we should be able to handle this case too. It is correct
1622 // to add this-> here. This is a workaround for PR7947.
1623 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001624 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001625 } else {
John McCalld681c392009-12-16 08:11:27 +00001626 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001627 }
John McCalld681c392009-12-16 08:11:27 +00001628
1629 // Do we really want to note all of these?
1630 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1631 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1632
1633 // Tell the callee to try to recover.
1634 return false;
1635 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001636
1637 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001638 }
1639 }
1640
Douglas Gregor598b08f2009-12-31 05:20:13 +00001641 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001642 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001643 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001644 if (!R.empty()) {
1645 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1646 if (SS.isEmpty())
1647 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1648 << FixItHint::CreateReplacement(R.getNameLoc(),
1649 R.getLookupName().getAsString());
1650 else
1651 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1652 << Name << computeDeclContext(SS, false) << R.getLookupName()
1653 << SS.getRange()
1654 << FixItHint::CreateReplacement(R.getNameLoc(),
1655 R.getLookupName().getAsString());
1656 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1657 Diag(ND->getLocation(), diag::note_previous_decl)
1658 << ND->getDeclName();
1659
1660 // Tell the callee to try to recover.
1661 return false;
1662 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001663
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001664 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1665 // FIXME: If we ended up with a typo for a type name or
1666 // Objective-C class name, we're in trouble because the parser
1667 // is in the wrong place to recover. Suggest the typo
1668 // correction, but don't make it a fix-it since we're not going
1669 // to recover well anyway.
1670 if (SS.isEmpty())
1671 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1672 else
1673 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1674 << Name << computeDeclContext(SS, false) << R.getLookupName()
1675 << SS.getRange();
1676
1677 // Don't try to recover; it won't work.
1678 return true;
1679 }
1680 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001681 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001682 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001683 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001684 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001685 else
Douglas Gregor25363982010-01-01 00:15:04 +00001686 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001687 << Name << computeDeclContext(SS, false) << Corrected
1688 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001689 return true;
1690 }
Douglas Gregor25363982010-01-01 00:15:04 +00001691 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001692 }
1693
1694 // Emit a special diagnostic for failed member lookups.
1695 // FIXME: computing the declaration context might fail here (?)
1696 if (!SS.isEmpty()) {
1697 Diag(R.getNameLoc(), diag::err_no_member)
1698 << Name << computeDeclContext(SS, false)
1699 << SS.getRange();
1700 return true;
1701 }
1702
John McCalld681c392009-12-16 08:11:27 +00001703 // Give up, we can't recover.
1704 Diag(R.getNameLoc(), diagnostic) << Name;
1705 return true;
1706}
1707
Douglas Gregor05fcf842010-11-02 20:36:02 +00001708ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1709 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001710 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1711 if (!IDecl)
1712 return 0;
1713 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1714 if (!ClassImpDecl)
1715 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001716 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001717 if (!property)
1718 return 0;
1719 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001720 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1721 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001722 return 0;
1723 return property;
1724}
1725
Douglas Gregor05fcf842010-11-02 20:36:02 +00001726bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1727 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1728 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1729 if (!IDecl)
1730 return false;
1731 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1732 if (!ClassImpDecl)
1733 return false;
1734 if (ObjCPropertyImplDecl *PIDecl
1735 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1736 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1737 PIDecl->getPropertyIvarDecl())
1738 return false;
1739
1740 return true;
1741}
1742
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001743ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1744 IdentifierInfo *II,
1745 SourceLocation NameLoc) {
1746 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001747 bool LookForIvars;
1748 if (Lookup.empty())
1749 LookForIvars = true;
1750 else if (CurMeth->isClassMethod())
1751 LookForIvars = false;
1752 else
1753 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001754 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1755 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001756 if (!LookForIvars)
1757 return 0;
1758
Fariborz Jahanian18722982010-07-17 00:59:30 +00001759 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1760 if (!IDecl)
1761 return 0;
1762 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001763 if (!ClassImpDecl)
1764 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001765 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001766 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001767 if (!property)
1768 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001769 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001770 DynamicImplSeen =
1771 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001772 // property implementation has a designated ivar. No need to assume a new
1773 // one.
1774 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1775 return 0;
1776 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001777 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001778 QualType PropType = Context.getCanonicalType(property->getType());
1779 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001780 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001781 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001782 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001783 (Expr *)0, true);
1784 ClassImpDecl->addDecl(Ivar);
1785 IDecl->makeDeclVisibleInContext(Ivar, false);
1786 property->setPropertyIvarDecl(Ivar);
1787 return Ivar;
1788 }
1789 return 0;
1790}
1791
John McCalldadc5752010-08-24 06:29:42 +00001792ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001793 CXXScopeSpec &SS,
1794 UnqualifiedId &Id,
1795 bool HasTrailingLParen,
1796 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001797 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1798 "cannot be direct & operand and have a trailing lparen");
1799
1800 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001801 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001802
John McCall10eae182009-11-30 22:42:35 +00001803 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001804
1805 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001806 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001807 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001808 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001809
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001810 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001811 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001812 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001813
John McCalle66edc12009-11-24 19:00:30 +00001814 // C++ [temp.dep.expr]p3:
1815 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001816 // -- an identifier that was declared with a dependent type,
1817 // (note: handled after lookup)
1818 // -- a template-id that is dependent,
1819 // (note: handled in BuildTemplateIdExpr)
1820 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001821 // -- a nested-name-specifier that contains a class-name that
1822 // names a dependent type.
1823 // Determine whether this is a member of an unknown specialization;
1824 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001825 bool DependentID = false;
1826 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1827 Name.getCXXNameType()->isDependentType()) {
1828 DependentID = true;
1829 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001830 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001831 if (RequireCompleteDeclContext(SS, DC))
1832 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001833 } else {
1834 DependentID = true;
1835 }
1836 }
1837
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001838 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001839 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001840 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001841
Fariborz Jahanian86151342010-07-22 23:33:21 +00001842 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001843 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001844 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001845 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001846 // Lookup the template name again to correctly establish the context in
1847 // which it was found. This is really unfortunate as we already did the
1848 // lookup to determine that it was a template name in the first place. If
1849 // this becomes a performance hit, we can work harder to preserve those
1850 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001851 bool MemberOfUnknownSpecialization;
1852 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1853 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001854
1855 if (MemberOfUnknownSpecialization ||
1856 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1857 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1858 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001859 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001860 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001861 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Douglas Gregora5226932011-02-04 13:35:07 +00001863 // If the result might be in a dependent base class, this is a dependent
1864 // id-expression.
1865 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1866 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1867 TemplateArgs);
1868
John McCalle66edc12009-11-24 19:00:30 +00001869 // If this reference is in an Objective-C method, then we need to do
1870 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001871 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001872 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001873 if (E.isInvalid())
1874 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001875
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001876 if (Expr *Ex = E.takeAs<Expr>())
1877 return Owned(Ex);
1878
1879 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001880 if (getLangOptions().ObjCDefaultSynthProperties &&
1881 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001882 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001883 if (const ObjCPropertyDecl *Property =
1884 canSynthesizeProvisionalIvar(II)) {
1885 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1886 Diag(Property->getLocation(), diag::note_property_declare);
1887 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001888 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1889 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001890 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001891 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001892 // for further use, this must be set to false if in class method.
1893 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001894 }
Chris Lattner59a25942008-03-31 00:36:02 +00001895 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001896
John McCalle66edc12009-11-24 19:00:30 +00001897 if (R.isAmbiguous())
1898 return ExprError();
1899
Douglas Gregor171c45a2009-02-18 21:56:37 +00001900 // Determine whether this name might be a candidate for
1901 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001902 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001903
John McCalle66edc12009-11-24 19:00:30 +00001904 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001905 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001906 // in C90, extension in C99, forbidden in C++).
1907 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1908 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1909 if (D) R.addDecl(D);
1910 }
1911
1912 // If this name wasn't predeclared and if this is not a function
1913 // call, diagnose the problem.
1914 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001915 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001916 return ExprError();
1917
1918 assert(!R.empty() &&
1919 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001920
1921 // If we found an Objective-C instance variable, let
1922 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001923 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001924 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1925 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001926 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001927 assert(E.isInvalid() || E.get());
1928 return move(E);
1929 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001930 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
John McCalle66edc12009-11-24 19:00:30 +00001933 // This is guaranteed from this point on.
1934 assert(!R.empty() || ADL);
1935
John McCall2d74de92009-12-01 22:10:20 +00001936 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001937 // C++ [class.mfct.non-static]p3:
1938 // When an id-expression that is not part of a class member access
1939 // syntax and not used to form a pointer to member is used in the
1940 // body of a non-static member function of class X, if name lookup
1941 // resolves the name in the id-expression to a non-static non-type
1942 // member of some class C, the id-expression is transformed into a
1943 // class member access expression using (*this) as the
1944 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001945 //
1946 // But we don't actually need to do this for '&' operands if R
1947 // resolved to a function or overloaded function set, because the
1948 // expression is ill-formed if it actually works out to be a
1949 // non-static member function:
1950 //
1951 // C++ [expr.ref]p4:
1952 // Otherwise, if E1.E2 refers to a non-static member function. . .
1953 // [t]he expression can be used only as the left-hand operand of a
1954 // member function call.
1955 //
1956 // There are other safeguards against such uses, but it's important
1957 // to get this right here so that we don't end up making a
1958 // spuriously dependent expression if we're inside a dependent
1959 // instance method.
John McCall57500772009-12-16 12:17:52 +00001960 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001961 bool MightBeImplicitMember;
1962 if (!isAddressOfOperand)
1963 MightBeImplicitMember = true;
1964 else if (!SS.isEmpty())
1965 MightBeImplicitMember = false;
1966 else if (R.isOverloadedResult())
1967 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001968 else if (R.isUnresolvableResult())
1969 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001970 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001971 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1972 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001973
1974 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001975 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001976 }
1977
John McCalle66edc12009-11-24 19:00:30 +00001978 if (TemplateArgs)
1979 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001980
John McCalle66edc12009-11-24 19:00:30 +00001981 return BuildDeclarationNameExpr(SS, R, ADL);
1982}
1983
John McCall57500772009-12-16 12:17:52 +00001984/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001985ExprResult
John McCall57500772009-12-16 12:17:52 +00001986Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1987 LookupResult &R,
1988 const TemplateArgumentListInfo *TemplateArgs) {
1989 switch (ClassifyImplicitMemberAccess(*this, R)) {
1990 case IMA_Instance:
1991 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1992
John McCall57500772009-12-16 12:17:52 +00001993 case IMA_Mixed:
1994 case IMA_Mixed_Unrelated:
1995 case IMA_Unresolved:
1996 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1997
1998 case IMA_Static:
1999 case IMA_Mixed_StaticContext:
2000 case IMA_Unresolved_StaticContext:
2001 if (TemplateArgs)
2002 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2003 return BuildDeclarationNameExpr(SS, R, false);
2004
2005 case IMA_Error_StaticContext:
2006 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002007 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2008 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002009 return ExprError();
2010 }
2011
2012 llvm_unreachable("unexpected instance member access kind");
2013 return ExprError();
2014}
2015
John McCall10eae182009-11-30 22:42:35 +00002016/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2017/// declaration name, generally during template instantiation.
2018/// There's a large number of things which don't need to be done along
2019/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002020ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002021Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002022 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002023 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002024 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002025 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002026
John McCall0b66eb32010-05-01 00:40:08 +00002027 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002028 return ExprError();
2029
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002030 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002031 LookupQualifiedName(R, DC);
2032
2033 if (R.isAmbiguous())
2034 return ExprError();
2035
2036 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002037 Diag(NameInfo.getLoc(), diag::err_no_member)
2038 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002039 return ExprError();
2040 }
2041
2042 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2043}
2044
2045/// LookupInObjCMethod - The parser has read a name in, and Sema has
2046/// detected that we're currently inside an ObjC method. Perform some
2047/// additional lookup.
2048///
2049/// Ideally, most of this would be done by lookup, but there's
2050/// actually quite a lot of extra work involved.
2051///
2052/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002053ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002054Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002055 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002056 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002057 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002058
John McCalle66edc12009-11-24 19:00:30 +00002059 // There are two cases to handle here. 1) scoped lookup could have failed,
2060 // in which case we should look for an ivar. 2) scoped lookup could have
2061 // found a decl, but that decl is outside the current instance method (i.e.
2062 // a global variable). In these two cases, we do a lookup for an ivar with
2063 // this name, if the lookup sucedes, we replace it our current decl.
2064
2065 // If we're in a class method, we don't normally want to look for
2066 // ivars. But if we don't find anything else, and there's an
2067 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002068 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002069
2070 bool LookForIvars;
2071 if (Lookup.empty())
2072 LookForIvars = true;
2073 else if (IsClassMethod)
2074 LookForIvars = false;
2075 else
2076 LookForIvars = (Lookup.isSingleResult() &&
2077 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002078 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002079 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002080 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002081 ObjCInterfaceDecl *ClassDeclared;
2082 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2083 // Diagnose using an ivar in a class method.
2084 if (IsClassMethod)
2085 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2086 << IV->getDeclName());
2087
2088 // If we're referencing an invalid decl, just return this as a silent
2089 // error node. The error diagnostic was already emitted on the decl.
2090 if (IV->isInvalidDecl())
2091 return ExprError();
2092
2093 // Check if referencing a field with __attribute__((deprecated)).
2094 if (DiagnoseUseOfDecl(IV, Loc))
2095 return ExprError();
2096
2097 // Diagnose the use of an ivar outside of the declaring class.
2098 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2099 ClassDeclared != IFace)
2100 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2101
2102 // FIXME: This should use a new expr for a direct reference, don't
2103 // turn this into Self->ivar, just return a BareIVarExpr or something.
2104 IdentifierInfo &II = Context.Idents.get("self");
2105 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002106 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002107 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002108 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002109 SelfName, false, false);
2110 if (SelfExpr.isInvalid())
2111 return ExprError();
2112
John Wiegley01296292011-04-08 18:41:53 +00002113 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2114 if (SelfExpr.isInvalid())
2115 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002116
John McCalle66edc12009-11-24 19:00:30 +00002117 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002118 Expr *base = SelfExpr.take();
2119 base = base->IgnoreParenImpCasts();
2120 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2121 const NamedDecl *ND = DE->getDecl();
2122 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002123 // relax the rule such that it is allowed to have a shadow 'self'
2124 // where stand-alone ivar can be found in this 'self' object.
2125 // This is to match gcc's behavior.
2126 ObjCInterfaceDecl *selfIFace = 0;
2127 if (const ObjCObjectPointerType *OPT =
2128 base->getType()->getAsObjCInterfacePointerType())
2129 selfIFace = OPT->getInterfaceDecl();
2130 if (!selfIFace ||
2131 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002132 Diag(Loc, diag::error_implicit_ivar_access)
2133 << IV->getDeclName();
2134 Diag(ND->getLocation(), diag::note_declared_at);
2135 return ExprError();
2136 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002137 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002138 }
John McCalle66edc12009-11-24 19:00:30 +00002139 return Owned(new (Context)
2140 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002141 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002142 }
Chris Lattner87313662010-04-12 05:10:17 +00002143 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002144 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002145 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002146 ObjCInterfaceDecl *ClassDeclared;
2147 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2148 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2149 IFace == ClassDeclared)
2150 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2151 }
2152 }
2153
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002154 if (Lookup.empty() && II && AllowBuiltinCreation) {
2155 // FIXME. Consolidate this with similar code in LookupName.
2156 if (unsigned BuiltinID = II->getBuiltinID()) {
2157 if (!(getLangOptions().CPlusPlus &&
2158 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2159 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2160 S, Lookup.isForRedeclaration(),
2161 Lookup.getNameLoc());
2162 if (D) Lookup.addDecl(D);
2163 }
2164 }
2165 }
John McCalle66edc12009-11-24 19:00:30 +00002166 // Sentinel value saying that we didn't do anything special.
2167 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002168}
John McCalld14a8642009-11-21 08:51:07 +00002169
John McCall16df1e52010-03-30 21:47:33 +00002170/// \brief Cast a base object to a member's actual type.
2171///
2172/// Logically this happens in three phases:
2173///
2174/// * First we cast from the base type to the naming class.
2175/// The naming class is the class into which we were looking
2176/// when we found the member; it's the qualifier type if a
2177/// qualifier was provided, and otherwise it's the base type.
2178///
2179/// * Next we cast from the naming class to the declaring class.
2180/// If the member we found was brought into a class's scope by
2181/// a using declaration, this is that class; otherwise it's
2182/// the class declaring the member.
2183///
2184/// * Finally we cast from the declaring class to the "true"
2185/// declaring class of the member. This conversion does not
2186/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002187ExprResult
2188Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002189 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002190 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002191 NamedDecl *Member) {
2192 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2193 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002194 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002195
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002196 QualType DestRecordType;
2197 QualType DestType;
2198 QualType FromRecordType;
2199 QualType FromType = From->getType();
2200 bool PointerConversions = false;
2201 if (isa<FieldDecl>(Member)) {
2202 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002203
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002204 if (FromType->getAs<PointerType>()) {
2205 DestType = Context.getPointerType(DestRecordType);
2206 FromRecordType = FromType->getPointeeType();
2207 PointerConversions = true;
2208 } else {
2209 DestType = DestRecordType;
2210 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002211 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002212 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2213 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002214 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002215
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002216 DestType = Method->getThisType(Context);
2217 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002218
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002219 if (FromType->getAs<PointerType>()) {
2220 FromRecordType = FromType->getPointeeType();
2221 PointerConversions = true;
2222 } else {
2223 FromRecordType = FromType;
2224 DestType = DestRecordType;
2225 }
2226 } else {
2227 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002228 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002229 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002230
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002231 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002232 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002233
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002234 // If the unqualified types are the same, no conversion is necessary.
2235 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002236 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002237
John McCall16df1e52010-03-30 21:47:33 +00002238 SourceRange FromRange = From->getSourceRange();
2239 SourceLocation FromLoc = FromRange.getBegin();
2240
John McCall2536c6d2010-08-25 10:28:54 +00002241 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002242
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002243 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002244 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002245 // class name.
2246 //
2247 // If the member was a qualified name and the qualified referred to a
2248 // specific base subobject type, we'll cast to that intermediate type
2249 // first and then to the object in which the member is declared. That allows
2250 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2251 //
2252 // class Base { public: int x; };
2253 // class Derived1 : public Base { };
2254 // class Derived2 : public Base { };
2255 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2256 //
2257 // void VeryDerived::f() {
2258 // x = 17; // error: ambiguous base subobjects
2259 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2260 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002261 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002262 QualType QType = QualType(Qualifier->getAsType(), 0);
2263 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2264 assert(QType->isRecordType() && "lookup done with non-record type");
2265
2266 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2267
2268 // In C++98, the qualifier type doesn't actually have to be a base
2269 // type of the object type, in which case we just ignore it.
2270 // Otherwise build the appropriate casts.
2271 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002272 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002273 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002274 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002275 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002276
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002277 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002278 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002279 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2280 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002281
2282 FromType = QType;
2283 FromRecordType = QRecordType;
2284
2285 // If the qualifier type was the same as the destination type,
2286 // we're done.
2287 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002288 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002289 }
2290 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002291
John McCall16df1e52010-03-30 21:47:33 +00002292 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002293
John McCall16df1e52010-03-30 21:47:33 +00002294 // If we actually found the member through a using declaration, cast
2295 // down to the using declaration's type.
2296 //
2297 // Pointer equality is fine here because only one declaration of a
2298 // class ever has member declarations.
2299 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2300 assert(isa<UsingShadowDecl>(FoundDecl));
2301 QualType URecordType = Context.getTypeDeclType(
2302 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2303
2304 // We only need to do this if the naming-class to declaring-class
2305 // conversion is non-trivial.
2306 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2307 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002308 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002309 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002310 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002311 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002312
John McCall16df1e52010-03-30 21:47:33 +00002313 QualType UType = URecordType;
2314 if (PointerConversions)
2315 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002316 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2317 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002318 FromType = UType;
2319 FromRecordType = URecordType;
2320 }
2321
2322 // We don't do access control for the conversion from the
2323 // declaring class to the true declaring class.
2324 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002326
John McCallcf142162010-08-07 06:22:56 +00002327 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002328 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2329 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002330 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002331 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002332
John Wiegley01296292011-04-08 18:41:53 +00002333 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2334 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002335}
Douglas Gregor3256d042009-06-30 15:47:41 +00002336
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002337/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002338static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002339 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002340 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002341 const DeclarationNameInfo &MemberNameInfo,
2342 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002343 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002344 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002345 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002346 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002347 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002348}
2349
John McCallfeb624a2010-11-23 20:48:44 +00002350static ExprResult
2351BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2352 const CXXScopeSpec &SS, FieldDecl *Field,
2353 DeclAccessPair FoundDecl,
2354 const DeclarationNameInfo &MemberNameInfo) {
2355 // x.a is an l-value if 'a' has a reference type. Otherwise:
2356 // x.a is an l-value/x-value/pr-value if the base is (and note
2357 // that *x is always an l-value), except that if the base isn't
2358 // an ordinary object then we must have an rvalue.
2359 ExprValueKind VK = VK_LValue;
2360 ExprObjectKind OK = OK_Ordinary;
2361 if (!IsArrow) {
2362 if (BaseExpr->getObjectKind() == OK_Ordinary)
2363 VK = BaseExpr->getValueKind();
2364 else
2365 VK = VK_RValue;
2366 }
2367 if (VK != VK_RValue && Field->isBitField())
2368 OK = OK_BitField;
2369
2370 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2371 QualType MemberType = Field->getType();
2372 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2373 MemberType = Ref->getPointeeType();
2374 VK = VK_LValue;
2375 } else {
2376 QualType BaseType = BaseExpr->getType();
2377 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2378
2379 Qualifiers BaseQuals = BaseType.getQualifiers();
2380
2381 // GC attributes are never picked up by members.
2382 BaseQuals.removeObjCGCAttr();
2383
2384 // CVR attributes from the base are picked up by members,
2385 // except that 'mutable' members don't pick up 'const'.
2386 if (Field->isMutable()) BaseQuals.removeConst();
2387
2388 Qualifiers MemberQuals
2389 = S.Context.getCanonicalType(MemberType).getQualifiers();
2390
2391 // TR 18037 does not allow fields to be declared with address spaces.
2392 assert(!MemberQuals.hasAddressSpace());
2393
2394 Qualifiers Combined = BaseQuals + MemberQuals;
2395 if (Combined != MemberQuals)
2396 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2397 }
2398
2399 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002400 ExprResult Base =
2401 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2402 FoundDecl, Field);
2403 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002404 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002405 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002406 Field, FoundDecl, MemberNameInfo,
2407 MemberType, VK, OK));
2408}
2409
John McCall2d74de92009-12-01 22:10:20 +00002410/// Builds an implicit member access expression. The current context
2411/// is known to be an instance method, and the given unqualified lookup
2412/// set is known to contain only instance members, at least one of which
2413/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002414ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002415Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2416 LookupResult &R,
2417 const TemplateArgumentListInfo *TemplateArgs,
2418 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002419 assert(!R.empty() && !R.isAmbiguous());
2420
John McCallf3a88602011-02-03 08:15:49 +00002421 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002422
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002423 // We may have found a field within an anonymous union or struct
2424 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002425 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002426 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002427 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002428
John McCallf3a88602011-02-03 08:15:49 +00002429 // If this is known to be an instance access, go ahead and build an
2430 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002431 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002432 CXXMethodDecl *method = tryCaptureCXXThis();
2433 assert(method && "didn't correctly pre-flight capture of 'this'");
2434
2435 QualType thisType = method->getThisType(Context);
2436 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002437 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002438 SourceLocation Loc = R.getNameLoc();
2439 if (SS.getRange().isValid())
2440 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002441 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002442 }
2443
John McCallf3a88602011-02-03 08:15:49 +00002444 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002445 /*OpLoc*/ SourceLocation(),
2446 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002447 SS,
2448 /*FirstQualifierInScope*/ 0,
2449 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002450}
2451
John McCalle66edc12009-11-24 19:00:30 +00002452bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002453 const LookupResult &R,
2454 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002455 // Only when used directly as the postfix-expression of a call.
2456 if (!HasTrailingLParen)
2457 return false;
2458
2459 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002460 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002461 return false;
2462
2463 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002464 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002465 return false;
2466
2467 // Turn off ADL when we find certain kinds of declarations during
2468 // normal lookup:
2469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2470 NamedDecl *D = *I;
2471
2472 // C++0x [basic.lookup.argdep]p3:
2473 // -- a declaration of a class member
2474 // Since using decls preserve this property, we check this on the
2475 // original decl.
John McCall57500772009-12-16 12:17:52 +00002476 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002477 return false;
2478
2479 // C++0x [basic.lookup.argdep]p3:
2480 // -- a block-scope function declaration that is not a
2481 // using-declaration
2482 // NOTE: we also trigger this for function templates (in fact, we
2483 // don't check the decl type at all, since all other decl types
2484 // turn off ADL anyway).
2485 if (isa<UsingShadowDecl>(D))
2486 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2487 else if (D->getDeclContext()->isFunctionOrMethod())
2488 return false;
2489
2490 // C++0x [basic.lookup.argdep]p3:
2491 // -- a declaration that is neither a function or a function
2492 // template
2493 // And also for builtin functions.
2494 if (isa<FunctionDecl>(D)) {
2495 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2496
2497 // But also builtin functions.
2498 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2499 return false;
2500 } else if (!isa<FunctionTemplateDecl>(D))
2501 return false;
2502 }
2503
2504 return true;
2505}
2506
2507
John McCalld14a8642009-11-21 08:51:07 +00002508/// Diagnoses obvious problems with the use of the given declaration
2509/// as an expression. This is only actually called for lookups that
2510/// were not overloaded, and it doesn't promise that the declaration
2511/// will in fact be used.
2512static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002513 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002514 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2515 return true;
2516 }
2517
2518 if (isa<ObjCInterfaceDecl>(D)) {
2519 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2520 return true;
2521 }
2522
2523 if (isa<NamespaceDecl>(D)) {
2524 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2525 return true;
2526 }
2527
2528 return false;
2529}
2530
John McCalldadc5752010-08-24 06:29:42 +00002531ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002532Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002533 LookupResult &R,
2534 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002535 // If this is a single, fully-resolved result and we don't need ADL,
2536 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002537 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002538 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2539 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002540
2541 // We only need to check the declaration if there's exactly one
2542 // result, because in the overloaded case the results can only be
2543 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002544 if (R.isSingleResult() &&
2545 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002546 return ExprError();
2547
John McCall58cc69d2010-01-27 01:50:18 +00002548 // Otherwise, just build an unresolved lookup expression. Suppress
2549 // any lookup-related diagnostics; we'll hash these out later, when
2550 // we've picked a target.
2551 R.suppressDiagnostics();
2552
John McCalld14a8642009-11-21 08:51:07 +00002553 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002554 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002555 SS.getWithLocInContext(Context),
2556 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002557 NeedsADL, R.isOverloadedResult(),
2558 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002559
2560 return Owned(ULE);
2561}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002562
John McCalld14a8642009-11-21 08:51:07 +00002563/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002564ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002565Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002566 const DeclarationNameInfo &NameInfo,
2567 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002568 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002569 assert(!isa<FunctionTemplateDecl>(D) &&
2570 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002571
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002572 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002573 if (CheckDeclInExpr(*this, Loc, D))
2574 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002575
Douglas Gregore7488b92009-12-01 16:58:18 +00002576 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2577 // Specifically diagnose references to class templates that are missing
2578 // a template argument list.
2579 Diag(Loc, diag::err_template_decl_ref)
2580 << Template << SS.getRange();
2581 Diag(Template->getLocation(), diag::note_template_decl_here);
2582 return ExprError();
2583 }
2584
2585 // Make sure that we're referring to a value.
2586 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2587 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002588 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002589 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002590 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002591 return ExprError();
2592 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002593
Douglas Gregor171c45a2009-02-18 21:56:37 +00002594 // Check whether this declaration can be used. Note that we suppress
2595 // this check when we're going to perform argument-dependent lookup
2596 // on this function name, because this might not be the function
2597 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002598 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002599 return ExprError();
2600
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002601 // Only create DeclRefExpr's for valid Decl's.
2602 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002603 return ExprError();
2604
John McCallf3a88602011-02-03 08:15:49 +00002605 // Handle members of anonymous structs and unions. If we got here,
2606 // and the reference is to a class member indirect field, then this
2607 // must be the subject of a pointer-to-member expression.
2608 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2609 if (!indirectField->isCXXClassMember())
2610 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2611 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002612
Chris Lattner2a9d9892008-10-20 05:16:36 +00002613 // If the identifier reference is inside a block, and it refers to a value
2614 // that is outside the block, create a BlockDeclRefExpr instead of a
2615 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2616 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002617 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002618 // We do not do this for things like enum constants, global variables, etc,
2619 // as they do not get snapshotted.
2620 //
John McCall351762c2011-02-07 10:33:21 +00002621 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002622 case CR_Error:
2623 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002624
John McCallc63de662011-02-02 13:00:07 +00002625 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002626 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2627 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2628
2629 case CR_CaptureByRef:
2630 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2631 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002632
2633 case CR_NoCapture: {
2634 // If this reference is not in a block or if the referenced
2635 // variable is within the block, create a normal DeclRefExpr.
2636
2637 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002638 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002639
2640 switch (D->getKind()) {
2641 // Ignore all the non-ValueDecl kinds.
2642#define ABSTRACT_DECL(kind)
2643#define VALUE(type, base)
2644#define DECL(type, base) \
2645 case Decl::type:
2646#include "clang/AST/DeclNodes.inc"
2647 llvm_unreachable("invalid value decl kind");
2648 return ExprError();
2649
2650 // These shouldn't make it here.
2651 case Decl::ObjCAtDefsField:
2652 case Decl::ObjCIvar:
2653 llvm_unreachable("forming non-member reference to ivar?");
2654 return ExprError();
2655
2656 // Enum constants are always r-values and never references.
2657 // Unresolved using declarations are dependent.
2658 case Decl::EnumConstant:
2659 case Decl::UnresolvedUsingValue:
2660 valueKind = VK_RValue;
2661 break;
2662
2663 // Fields and indirect fields that got here must be for
2664 // pointer-to-member expressions; we just call them l-values for
2665 // internal consistency, because this subexpression doesn't really
2666 // exist in the high-level semantics.
2667 case Decl::Field:
2668 case Decl::IndirectField:
2669 assert(getLangOptions().CPlusPlus &&
2670 "building reference to field in C?");
2671
2672 // These can't have reference type in well-formed programs, but
2673 // for internal consistency we do this anyway.
2674 type = type.getNonReferenceType();
2675 valueKind = VK_LValue;
2676 break;
2677
2678 // Non-type template parameters are either l-values or r-values
2679 // depending on the type.
2680 case Decl::NonTypeTemplateParm: {
2681 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2682 type = reftype->getPointeeType();
2683 valueKind = VK_LValue; // even if the parameter is an r-value reference
2684 break;
2685 }
2686
2687 // For non-references, we need to strip qualifiers just in case
2688 // the template parameter was declared as 'const int' or whatever.
2689 valueKind = VK_RValue;
2690 type = type.getUnqualifiedType();
2691 break;
2692 }
2693
2694 case Decl::Var:
2695 // In C, "extern void blah;" is valid and is an r-value.
2696 if (!getLangOptions().CPlusPlus &&
2697 !type.hasQualifiers() &&
2698 type->isVoidType()) {
2699 valueKind = VK_RValue;
2700 break;
2701 }
2702 // fallthrough
2703
2704 case Decl::ImplicitParam:
2705 case Decl::ParmVar:
2706 // These are always l-values.
2707 valueKind = VK_LValue;
2708 type = type.getNonReferenceType();
2709 break;
2710
2711 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002712 const FunctionType *fty = type->castAs<FunctionType>();
2713
2714 // If we're referring to a function with an __unknown_anytype
2715 // result type, make the entire expression __unknown_anytype.
2716 if (fty->getResultType() == Context.UnknownAnyTy) {
2717 type = Context.UnknownAnyTy;
2718 valueKind = VK_RValue;
2719 break;
2720 }
2721
John McCallf4cd4f92011-02-09 01:13:10 +00002722 // Functions are l-values in C++.
2723 if (getLangOptions().CPlusPlus) {
2724 valueKind = VK_LValue;
2725 break;
2726 }
2727
2728 // C99 DR 316 says that, if a function type comes from a
2729 // function definition (without a prototype), that type is only
2730 // used for checking compatibility. Therefore, when referencing
2731 // the function, we pretend that we don't have the full function
2732 // type.
John McCall2979fe02011-04-12 00:42:48 +00002733 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2734 isa<FunctionProtoType>(fty))
2735 type = Context.getFunctionNoProtoType(fty->getResultType(),
2736 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002737
2738 // Functions are r-values in C.
2739 valueKind = VK_RValue;
2740 break;
2741 }
2742
2743 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002744 // If we're referring to a method with an __unknown_anytype
2745 // result type, make the entire expression __unknown_anytype.
2746 // This should only be possible with a type written directly.
2747 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2748 if (proto->getResultType() == Context.UnknownAnyTy) {
2749 type = Context.UnknownAnyTy;
2750 valueKind = VK_RValue;
2751 break;
2752 }
2753
John McCallf4cd4f92011-02-09 01:13:10 +00002754 // C++ methods are l-values if static, r-values if non-static.
2755 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2756 valueKind = VK_LValue;
2757 break;
2758 }
2759 // fallthrough
2760
2761 case Decl::CXXConversion:
2762 case Decl::CXXDestructor:
2763 case Decl::CXXConstructor:
2764 valueKind = VK_RValue;
2765 break;
2766 }
2767
2768 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2769 }
2770
John McCallc63de662011-02-02 13:00:07 +00002771 }
John McCall7decc9e2010-11-18 06:31:45 +00002772
John McCall351762c2011-02-07 10:33:21 +00002773 llvm_unreachable("unknown capture result");
2774 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002775}
Chris Lattnere168f762006-11-10 05:29:30 +00002776
John McCall2979fe02011-04-12 00:42:48 +00002777ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002778 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002779
Chris Lattnere168f762006-11-10 05:29:30 +00002780 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002781 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002782 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2783 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2784 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002785 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002786
Chris Lattnera81a0272008-01-12 08:14:25 +00002787 // Pre-defined identifiers are of type char[x], where x is the length of the
2788 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002789
Anders Carlsson2fb08242009-09-08 18:24:21 +00002790 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002791 if (!currentDecl && getCurBlock())
2792 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002793 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002794 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002795 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002796 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002797
Anders Carlsson0b209a82009-09-11 01:22:35 +00002798 QualType ResTy;
2799 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2800 ResTy = Context.DependentTy;
2801 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002802 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002803
Anders Carlsson0b209a82009-09-11 01:22:35 +00002804 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002805 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002806 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2807 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002808 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002809}
2810
John McCalldadc5752010-08-24 06:29:42 +00002811ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002812 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002813 bool Invalid = false;
2814 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2815 if (Invalid)
2816 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002817
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002818 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2819 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002820 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002821 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002822
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002823 QualType Ty;
2824 if (!getLangOptions().CPlusPlus)
2825 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2826 else if (Literal.isWide())
2827 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002828 else if (Literal.isMultiChar())
2829 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002830 else
2831 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002832
Sebastian Redl20614a72009-01-20 22:23:13 +00002833 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2834 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002835 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002836}
2837
John McCalldadc5752010-08-24 06:29:42 +00002838ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002839 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002840 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2841 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002842 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002843 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002844 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002845 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002846 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002847
Chris Lattner23b7eb62007-06-15 23:05:46 +00002848 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002849 // Add padding so that NumericLiteralParser can overread by one character.
2850 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002851 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002852
Chris Lattner67ca9252007-05-21 01:08:44 +00002853 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002854 bool Invalid = false;
2855 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2856 if (Invalid)
2857 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002858
Mike Stump11289f42009-09-09 15:08:12 +00002859 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002860 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002861 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002862 return ExprError();
2863
Chris Lattner1c20a172007-08-26 03:42:43 +00002864 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002865
Chris Lattner1c20a172007-08-26 03:42:43 +00002866 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002867 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002868 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002869 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002870 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002871 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002872 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002873 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002874
2875 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2876
John McCall53b93a02009-12-24 09:08:04 +00002877 using llvm::APFloat;
2878 APFloat Val(Format);
2879
2880 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002881
2882 // Overflow is always an error, but underflow is only an error if
2883 // we underflowed to zero (APFloat reports denormals as underflow).
2884 if ((result & APFloat::opOverflow) ||
2885 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002886 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002887 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002888 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002889 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002890 APFloat::getLargest(Format).toString(buffer);
2891 } else {
John McCall62abc942010-02-26 23:35:57 +00002892 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002893 APFloat::getSmallest(Format).toString(buffer);
2894 }
2895
2896 Diag(Tok.getLocation(), diagnostic)
2897 << Ty
2898 << llvm::StringRef(buffer.data(), buffer.size());
2899 }
2900
2901 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002902 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002903
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002904 if (Ty == Context.DoubleTy) {
2905 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002906 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002907 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2908 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002909 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002910 }
2911 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002912 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002913 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002914 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002915 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002916
Neil Boothac582c52007-08-29 22:00:19 +00002917 // long long is a C99 feature.
2918 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002919 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002920 Diag(Tok.getLocation(), diag::ext_longlong);
2921
Chris Lattner67ca9252007-05-21 01:08:44 +00002922 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002923 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002924
Chris Lattner67ca9252007-05-21 01:08:44 +00002925 if (Literal.GetIntegerValue(ResultVal)) {
2926 // If this value didn't fit into uintmax_t, warn and force to ull.
2927 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002928 Ty = Context.UnsignedLongLongTy;
2929 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002930 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002931 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002932 // If this value fits into a ULL, try to figure out what else it fits into
2933 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002934
Chris Lattner67ca9252007-05-21 01:08:44 +00002935 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2936 // be an unsigned int.
2937 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2938
2939 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002940 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002941 if (!Literal.isLong && !Literal.isLongLong) {
2942 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002943 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002944
Chris Lattner67ca9252007-05-21 01:08:44 +00002945 // Does it fit in a unsigned int?
2946 if (ResultVal.isIntN(IntSize)) {
2947 // Does it fit in a signed int?
2948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002949 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002950 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002951 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002952 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002953 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002954 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002955
Chris Lattner67ca9252007-05-21 01:08:44 +00002956 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002957 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002958 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002959
Chris Lattner67ca9252007-05-21 01:08:44 +00002960 // Does it fit in a unsigned long?
2961 if (ResultVal.isIntN(LongSize)) {
2962 // Does it fit in a signed long?
2963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002964 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002965 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002966 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002967 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002968 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002969 }
2970
Chris Lattner67ca9252007-05-21 01:08:44 +00002971 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002972 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002973 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002974
Chris Lattner67ca9252007-05-21 01:08:44 +00002975 // Does it fit in a unsigned long long?
2976 if (ResultVal.isIntN(LongLongSize)) {
2977 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002978 // To be compatible with MSVC, hex integer literals ending with the
2979 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002980 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2981 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002982 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002983 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002984 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002985 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002986 }
2987 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002988
Chris Lattner67ca9252007-05-21 01:08:44 +00002989 // If we still couldn't decide a type, we probably have something that
2990 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002991 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002992 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002993 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002994 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002995 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002996
Chris Lattner55258cf2008-05-09 05:59:00 +00002997 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002998 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002999 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003000 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003001 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003002
Chris Lattner1c20a172007-08-26 03:42:43 +00003003 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3004 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003005 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003006 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003007
3008 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003009}
3010
John McCalldadc5752010-08-24 06:29:42 +00003011ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003012 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003013 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003014 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003015}
3016
Steve Naroff71b59a92007-06-04 22:22:31 +00003017/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003018/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003019bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3020 SourceLocation OpLoc,
3021 SourceRange ExprRange,
3022 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003023 if (exprType->isDependentType())
3024 return false;
3025
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003026 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3027 // the result is the size of the referenced type."
3028 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3029 // result shall be the alignment of the referenced type."
3030 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3031 exprType = Ref->getPointeeType();
3032
Peter Collingbournee190dee2011-03-11 19:24:49 +00003033 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3034 // scalar or vector data type argument..."
3035 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3036 // type (C99 6.2.5p18) or void.
3037 if (ExprKind == UETT_VecStep) {
3038 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3039 exprType->isVectorType())) {
3040 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3041 << exprType << ExprRange;
3042 return true;
3043 }
3044 }
3045
Steve Naroff043d45d2007-05-15 02:32:35 +00003046 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00003047 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003048 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003049 if (ExprKind == UETT_SizeOf)
3050 Diag(OpLoc, diag::ext_sizeof_function_type)
3051 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003052 return false;
3053 }
Mike Stump11289f42009-09-09 15:08:12 +00003054
Peter Collingbournee190dee2011-03-11 19:24:49 +00003055 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3056 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00003057 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003058 if (ExprKind != UETT_VecStep)
3059 Diag(OpLoc, diag::ext_sizeof_void_type)
3060 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003061 return false;
3062 }
Mike Stump11289f42009-09-09 15:08:12 +00003063
Chris Lattner62975a72009-04-24 00:30:45 +00003064 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003065 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003066 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003067 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003068
Chris Lattner62975a72009-04-24 00:30:45 +00003069 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00003070 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003071 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003072 << exprType << (ExprKind == UETT_SizeOf)
3073 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003074 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00003075 }
Mike Stump11289f42009-09-09 15:08:12 +00003076
Chris Lattner62975a72009-04-24 00:30:45 +00003077 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003078}
3079
John McCall36e7fe32010-10-12 00:20:44 +00003080static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3081 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003082 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003083
Mike Stump11289f42009-09-09 15:08:12 +00003084 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003085 if (isa<DeclRefExpr>(E))
3086 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003087
3088 // Cannot know anything else if the expression is dependent.
3089 if (E->isTypeDependent())
3090 return false;
3091
Douglas Gregor71235ec2009-05-02 02:18:30 +00003092 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00003093 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00003094 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003095 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003096
3097 // Alignment of a field access is always okay, so long as it isn't a
3098 // bit-field.
3099 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003100 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003101 return false;
3102
Peter Collingbournee190dee2011-03-11 19:24:49 +00003103 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3104 UETT_AlignOf);
3105}
3106
3107bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3108 SourceRange ExprRange) {
3109 E = E->IgnoreParens();
3110
3111 // Cannot know anything else if the expression is dependent.
3112 if (E->isTypeDependent())
3113 return false;
3114
3115 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3116 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003117}
3118
Douglas Gregor0950e412009-03-13 21:01:28 +00003119/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003120ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003121Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3122 SourceLocation OpLoc,
3123 UnaryExprOrTypeTrait ExprKind,
3124 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003125 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003126 return ExprError();
3127
John McCallbcd03502009-12-07 02:54:59 +00003128 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003129
Douglas Gregor0950e412009-03-13 21:01:28 +00003130 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003131 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003132 return ExprError();
3133
3134 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003135 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3136 Context.getSizeType(),
3137 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003138}
3139
3140/// \brief Build a sizeof or alignof expression given an expression
3141/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003142ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003143Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3144 UnaryExprOrTypeTrait ExprKind,
3145 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003146 // Verify that the operand is valid.
3147 bool isInvalid = false;
3148 if (E->isTypeDependent()) {
3149 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003150 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00003151 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003152 } else if (ExprKind == UETT_VecStep) {
3153 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003154 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00003155 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3156 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003157 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003158 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003159 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00003160 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00003161 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003162 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3163 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003164 }
3165
3166 if (isInvalid)
3167 return ExprError();
3168
3169 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003170 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3171 Context.getSizeType(),
3172 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003173}
3174
Peter Collingbournee190dee2011-03-11 19:24:49 +00003175/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3176/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003177/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003178ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003179Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3180 UnaryExprOrTypeTrait ExprKind, bool isType,
3181 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003182 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003183 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003184
Sebastian Redl6f282892008-11-11 17:56:53 +00003185 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003186 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003187 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003188 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003189 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003190
Douglas Gregor0950e412009-03-13 21:01:28 +00003191 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00003192 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00003193 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3194 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00003195
Douglas Gregor0950e412009-03-13 21:01:28 +00003196 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003197}
3198
John Wiegley01296292011-04-08 18:41:53 +00003199static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003200 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003201 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003202 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003203
John McCall34376a62010-12-04 03:47:34 +00003204 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003205 if (V.get()->getObjectKind() != OK_Ordinary) {
3206 V = S.DefaultLvalueConversion(V.take());
3207 if (V.isInvalid())
3208 return QualType();
3209 }
John McCall34376a62010-12-04 03:47:34 +00003210
Chris Lattnere267f5d2007-08-26 05:39:26 +00003211 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003212 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003213 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003214
Chris Lattnere267f5d2007-08-26 05:39:26 +00003215 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003216 if (V.get()->getType()->isArithmeticType())
3217 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003218
John McCall36226622010-10-12 02:09:17 +00003219 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003220 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003221 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003222 if (PR.get() != V.get()) {
3223 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003224 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003225 }
3226
Chris Lattnere267f5d2007-08-26 05:39:26 +00003227 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003228 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003229 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003230 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003231}
3232
3233
Chris Lattnere168f762006-11-10 05:29:30 +00003234
John McCalldadc5752010-08-24 06:29:42 +00003235ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003236Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003237 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003238 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003239 switch (Kind) {
3240 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003241 case tok::plusplus: Opc = UO_PostInc; break;
3242 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003243 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003244
John McCallb268a282010-08-23 23:25:46 +00003245 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003246}
3247
John McCall4bc41ae2010-11-18 19:01:18 +00003248/// Expressions of certain arbitrary types are forbidden by C from
3249/// having l-value type. These are:
3250/// - 'void', but not qualified void
3251/// - function types
3252///
3253/// The exact rule here is C99 6.3.2.1:
3254/// An lvalue is an expression with an object type or an incomplete
3255/// type other than void.
3256static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3257 return ((T->isVoidType() && !T.hasQualifiers()) ||
3258 T->isFunctionType());
3259}
3260
John McCalldadc5752010-08-24 06:29:42 +00003261ExprResult
John McCallb268a282010-08-23 23:25:46 +00003262Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3263 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003264 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003265 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003266 if (Result.isInvalid()) return ExprError();
3267 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003268
John McCallb268a282010-08-23 23:25:46 +00003269 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003270
Douglas Gregor40412ac2008-11-19 17:17:41 +00003271 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003272 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003273 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003274 Context.DependentTy,
3275 VK_LValue, OK_Ordinary,
3276 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003277 }
3278
Mike Stump11289f42009-09-09 15:08:12 +00003279 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003280 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003281 LHSExp->getType()->isEnumeralType() ||
3282 RHSExp->getType()->isRecordType() ||
3283 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003284 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003285 }
3286
John McCallb268a282010-08-23 23:25:46 +00003287 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003288}
3289
3290
John McCalldadc5752010-08-24 06:29:42 +00003291ExprResult
John McCallb268a282010-08-23 23:25:46 +00003292Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3293 Expr *Idx, SourceLocation RLoc) {
3294 Expr *LHSExp = Base;
3295 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003296
Chris Lattner36d572b2007-07-16 00:14:47 +00003297 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003298 if (!LHSExp->getType()->getAs<VectorType>()) {
3299 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3300 if (Result.isInvalid())
3301 return ExprError();
3302 LHSExp = Result.take();
3303 }
3304 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3305 if (Result.isInvalid())
3306 return ExprError();
3307 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003308
Chris Lattner36d572b2007-07-16 00:14:47 +00003309 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003310 ExprValueKind VK = VK_LValue;
3311 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003312
Steve Naroffc1aadb12007-03-28 21:49:40 +00003313 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003314 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003315 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003316 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003317 Expr *BaseExpr, *IndexExpr;
3318 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003319 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3320 BaseExpr = LHSExp;
3321 IndexExpr = RHSExp;
3322 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003323 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003324 BaseExpr = LHSExp;
3325 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003326 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003327 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003328 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003329 BaseExpr = RHSExp;
3330 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003331 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003332 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003333 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003334 BaseExpr = LHSExp;
3335 IndexExpr = RHSExp;
3336 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003337 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003338 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003339 // Handle the uncommon case of "123[Ptr]".
3340 BaseExpr = RHSExp;
3341 IndexExpr = LHSExp;
3342 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003343 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003344 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003345 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003346 VK = LHSExp->getValueKind();
3347 if (VK != VK_RValue)
3348 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003349
Chris Lattner36d572b2007-07-16 00:14:47 +00003350 // FIXME: need to deal with const...
3351 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003352 } else if (LHSTy->isArrayType()) {
3353 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003354 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003355 // wasn't promoted because of the C90 rule that doesn't
3356 // allow promoting non-lvalue arrays. Warn, then
3357 // force the promotion here.
3358 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3359 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003360 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3361 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003362 LHSTy = LHSExp->getType();
3363
3364 BaseExpr = LHSExp;
3365 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003366 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003367 } else if (RHSTy->isArrayType()) {
3368 // Same as previous, except for 123[f().a] case
3369 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3370 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003371 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3372 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003373 RHSTy = RHSExp->getType();
3374
3375 BaseExpr = RHSExp;
3376 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003377 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003378 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003379 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3380 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003381 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003382 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003383 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003384 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3385 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003386
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003387 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003388 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3389 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003390 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3391
Douglas Gregorac1fb652009-03-24 19:52:54 +00003392 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003393 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3394 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003395 // incomplete types are not object types.
3396 if (ResultType->isFunctionType()) {
3397 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3398 << ResultType << BaseExpr->getSourceRange();
3399 return ExprError();
3400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003402 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3403 // GNU extension: subscripting on pointer to void
3404 Diag(LLoc, diag::ext_gnu_void_ptr)
3405 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003406
3407 // C forbids expressions of unqualified void type from being l-values.
3408 // See IsCForbiddenLValueType.
3409 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003410 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003411 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003412 PDiag(diag::err_subscript_incomplete_type)
3413 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003414 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003415
Chris Lattner62975a72009-04-24 00:30:45 +00003416 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003417 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003418 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3419 << ResultType << BaseExpr->getSourceRange();
3420 return ExprError();
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
John McCall4bc41ae2010-11-18 19:01:18 +00003423 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3424 !IsCForbiddenLValueType(Context, ResultType));
3425
Mike Stump4e1f26a2009-02-19 03:04:26 +00003426 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003427 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003428}
3429
John McCall4bc41ae2010-11-18 19:01:18 +00003430/// Check an ext-vector component access expression.
3431///
3432/// VK should be set in advance to the value kind of the base
3433/// expression.
3434static QualType
3435CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3436 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003437 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003438 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3439 // see FIXME there.
3440 //
3441 // FIXME: This logic can be greatly simplified by splitting it along
3442 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003443 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003444
Steve Narofff8fd09e2007-07-27 22:15:19 +00003445 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003446 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003447
Mike Stump4e1f26a2009-02-19 03:04:26 +00003448 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003449 // special names that indicate a subset of exactly half the elements are
3450 // to be selected.
3451 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003452
Nate Begemanbb70bf62009-01-18 01:47:54 +00003453 // This flag determines whether or not CompName has an 's' char prefix,
3454 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003455 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003456
John McCall4bc41ae2010-11-18 19:01:18 +00003457 bool HasRepeated = false;
3458 bool HasIndex[16] = {};
3459
3460 int Idx;
3461
Nate Begemanf322eab2008-05-09 06:41:27 +00003462 // Check that we've found one of the special components, or that the component
3463 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003464 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003465 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3466 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003467 } else if (!HexSwizzle &&
3468 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3469 do {
3470 if (HasIndex[Idx]) HasRepeated = true;
3471 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003472 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003473 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3474 } else {
3475 if (HexSwizzle) compStr++;
3476 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3477 if (HasIndex[Idx]) HasRepeated = true;
3478 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003479 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003480 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003481 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003482
Mike Stump4e1f26a2009-02-19 03:04:26 +00003483 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003484 // We didn't get to the end of the string. This means the component names
3485 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003486 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003487 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003488 return QualType();
3489 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003490
Nate Begemanbb70bf62009-01-18 01:47:54 +00003491 // Ensure no component accessor exceeds the width of the vector type it
3492 // operates on.
3493 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003494 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003495
3496 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003497 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003498
3499 while (*compStr) {
3500 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003501 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003502 << baseType << SourceRange(CompLoc);
3503 return QualType();
3504 }
3505 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003506 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003507
Steve Narofff8fd09e2007-07-27 22:15:19 +00003508 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003509 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003510 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003511 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003512 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003513 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003514 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003515 if (HexSwizzle)
3516 CompSize--;
3517
Steve Narofff8fd09e2007-07-27 22:15:19 +00003518 if (CompSize == 1)
3519 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003520
John McCall4bc41ae2010-11-18 19:01:18 +00003521 if (HasRepeated) VK = VK_RValue;
3522
3523 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003524 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003525 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003526 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3527 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3528 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003529 }
3530 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003531}
3532
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003533static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003534 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003535 const Selector &Sel,
3536 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003537 if (Member)
3538 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3539 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003540 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003541 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003542
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003543 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3544 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003545 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3546 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003547 return D;
3548 }
3549 return 0;
3550}
3551
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003552static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3553 IdentifierInfo *Member,
3554 const Selector &Sel,
3555 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003556 // Check protocols on qualified interfaces.
3557 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003558 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003559 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003560 if (Member)
3561 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3562 GDecl = PD;
3563 break;
3564 }
3565 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003566 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003567 GDecl = OMD;
3568 break;
3569 }
3570 }
3571 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003572 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003573 E = QIdTy->qual_end(); I != E; ++I) {
3574 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003575 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3576 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003577 if (GDecl)
3578 return GDecl;
3579 }
3580 }
3581 return GDecl;
3582}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003583
John McCalldadc5752010-08-24 06:29:42 +00003584ExprResult
John McCallb268a282010-08-23 23:25:46 +00003585Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003586 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003587 const CXXScopeSpec &SS,
3588 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003589 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003590 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003591 // Even in dependent contexts, try to diagnose base expressions with
3592 // obviously wrong types, e.g.:
3593 //
3594 // T* t;
3595 // t.f;
3596 //
3597 // In Obj-C++, however, the above expression is valid, since it could be
3598 // accessing the 'f' property if T is an Obj-C interface. The extra check
3599 // allows this, while still reporting an error if T is a struct pointer.
3600 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003601 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003602 if (PT && (!getLangOptions().ObjC1 ||
3603 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003604 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003605 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003606 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003607 return ExprError();
3608 }
3609 }
3610
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003611 assert(BaseType->isDependentType() ||
3612 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003613 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003614
3615 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3616 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003617 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003618 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003619 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003620 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003621 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003622}
3623
3624/// We know that the given qualified member reference points only to
3625/// declarations which do not belong to the static type of the base
3626/// expression. Diagnose the problem.
3627static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3628 Expr *BaseExpr,
3629 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003630 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003631 NamedDecl *rep,
3632 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003633 // If this is an implicit member access, use a different set of
3634 // diagnostics.
3635 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003636 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003637
John McCallf3a88602011-02-03 08:15:49 +00003638 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3639 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003640}
3641
3642// Check whether the declarations we found through a nested-name
3643// specifier in a member expression are actually members of the base
3644// type. The restriction here is:
3645//
3646// C++ [expr.ref]p2:
3647// ... In these cases, the id-expression shall name a
3648// member of the class or of one of its base classes.
3649//
3650// So it's perfectly legitimate for the nested-name specifier to name
3651// an unrelated class, and for us to find an overload set including
3652// decls from classes which are not superclasses, as long as the decl
3653// we actually pick through overload resolution is from a superclass.
3654bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3655 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003656 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003657 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003658 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3659 if (!BaseRT) {
3660 // We can't check this yet because the base type is still
3661 // dependent.
3662 assert(BaseType->isDependentType());
3663 return false;
3664 }
3665 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003666
3667 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003668 // If this is an implicit member reference and we find a
3669 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003670 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003671 return false;
John McCall10eae182009-11-30 22:42:35 +00003672
John McCall2d74de92009-12-01 22:10:20 +00003673 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003674 DeclContext *DC = (*I)->getDeclContext();
3675 while (DC->isTransparentContext())
3676 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003677
Douglas Gregora9c3e822010-07-28 22:27:52 +00003678 if (!DC->isRecord())
3679 continue;
3680
John McCall2d74de92009-12-01 22:10:20 +00003681 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003682 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003683
3684 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3685 return false;
3686 }
3687
John McCallf3a88602011-02-03 08:15:49 +00003688 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3689 R.getRepresentativeDecl(),
3690 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003691 return true;
3692}
3693
3694static bool
3695LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3696 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003697 SourceLocation OpLoc, CXXScopeSpec &SS,
3698 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003699 RecordDecl *RDecl = RTy->getDecl();
3700 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003701 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003702 << BaseRange))
3703 return true;
3704
John McCalle9cccd82010-06-16 08:42:20 +00003705 if (HasTemplateArgs) {
3706 // LookupTemplateName doesn't expect these both to exist simultaneously.
3707 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3708
3709 bool MOUS;
3710 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3711 return false;
3712 }
3713
John McCall2d74de92009-12-01 22:10:20 +00003714 DeclContext *DC = RDecl;
3715 if (SS.isSet()) {
3716 // If the member name was a qualified-id, look into the
3717 // nested-name-specifier.
3718 DC = SemaRef.computeDeclContext(SS, false);
3719
John McCall0b66eb32010-05-01 00:40:08 +00003720 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003721 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3722 << SS.getRange() << DC;
3723 return true;
3724 }
3725
John McCall2d74de92009-12-01 22:10:20 +00003726 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003727
John McCall2d74de92009-12-01 22:10:20 +00003728 if (!isa<TypeDecl>(DC)) {
3729 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3730 << DC << SS.getRange();
3731 return true;
John McCall10eae182009-11-30 22:42:35 +00003732 }
3733 }
3734
John McCall2d74de92009-12-01 22:10:20 +00003735 // The record definition is complete, now look up the member.
3736 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003737
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003738 if (!R.empty())
3739 return false;
3740
3741 // We didn't find anything with the given name, so try to correct
3742 // for typos.
3743 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003744 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003745 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003746 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3747 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3748 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003749 << FixItHint::CreateReplacement(R.getNameLoc(),
3750 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003751 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3752 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3753 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003754 return false;
3755 } else {
3756 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003757 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003758 }
3759
John McCall10eae182009-11-30 22:42:35 +00003760 return false;
3761}
3762
John McCalldadc5752010-08-24 06:29:42 +00003763ExprResult
John McCallb268a282010-08-23 23:25:46 +00003764Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003765 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003766 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003767 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003768 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003769 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003770 if (BaseType->isDependentType() ||
3771 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003772 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003773 IsArrow, OpLoc,
3774 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003775 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003776
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003777 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003778
John McCall2d74de92009-12-01 22:10:20 +00003779 // Implicit member accesses.
3780 if (!Base) {
3781 QualType RecordTy = BaseType;
3782 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3783 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3784 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003785 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003786 return ExprError();
3787
3788 // Explicit member accesses.
3789 } else {
John Wiegley01296292011-04-08 18:41:53 +00003790 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003791 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003792 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003793 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003794
John Wiegley01296292011-04-08 18:41:53 +00003795 if (BaseResult.isInvalid())
3796 return ExprError();
3797 Base = BaseResult.take();
3798
John McCall2d74de92009-12-01 22:10:20 +00003799 if (Result.isInvalid()) {
3800 Owned(Base);
3801 return ExprError();
3802 }
3803
3804 if (Result.get())
3805 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003806
3807 // LookupMemberExpr can modify Base, and thus change BaseType
3808 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003809 }
3810
John McCallb268a282010-08-23 23:25:46 +00003811 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003812 OpLoc, IsArrow, SS, FirstQualifierInScope,
3813 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003814}
3815
John McCalldadc5752010-08-24 06:29:42 +00003816ExprResult
John McCallb268a282010-08-23 23:25:46 +00003817Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003818 SourceLocation OpLoc, bool IsArrow,
3819 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003820 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003821 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003822 const TemplateArgumentListInfo *TemplateArgs,
3823 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003824 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003825 if (IsArrow) {
3826 assert(BaseType->isPointerType());
3827 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3828 }
John McCalla8ae2222010-04-06 21:38:20 +00003829 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003830
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003831 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3832 DeclarationName MemberName = MemberNameInfo.getName();
3833 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003834
3835 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003836 return ExprError();
3837
John McCall10eae182009-11-30 22:42:35 +00003838 if (R.empty()) {
3839 // Rederive where we looked up.
3840 DeclContext *DC = (SS.isSet()
3841 ? computeDeclContext(SS, false)
3842 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003843
John McCall10eae182009-11-30 22:42:35 +00003844 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003845 << MemberName << DC
3846 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003847 return ExprError();
3848 }
3849
John McCall38836f02010-01-15 08:34:02 +00003850 // Diagnose lookups that find only declarations from a non-base
3851 // type. This is possible for either qualified lookups (which may
3852 // have been qualified with an unrelated type) or implicit member
3853 // expressions (which were found with unqualified lookup and thus
3854 // may have come from an enclosing scope). Note that it's okay for
3855 // lookup to find declarations from a non-base type as long as those
3856 // aren't the ones picked by overload resolution.
3857 if ((SS.isSet() || !BaseExpr ||
3858 (isa<CXXThisExpr>(BaseExpr) &&
3859 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003860 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003861 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003862 return ExprError();
3863
3864 // Construct an unresolved result if we in fact got an unresolved
3865 // result.
3866 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003867 // Suppress any lookup-related diagnostics; we'll do these when we
3868 // pick a member.
3869 R.suppressDiagnostics();
3870
John McCall10eae182009-11-30 22:42:35 +00003871 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003872 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003873 BaseExpr, BaseExprType,
3874 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003875 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003876 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003877 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003878
3879 return Owned(MemExpr);
3880 }
3881
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003882 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003883 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003884 NamedDecl *MemberDecl = R.getFoundDecl();
3885
3886 // FIXME: diagnose the presence of template arguments now.
3887
3888 // If the decl being referenced had an error, return an error for this
3889 // sub-expr without emitting another error, in order to avoid cascading
3890 // error cases.
3891 if (MemberDecl->isInvalidDecl())
3892 return ExprError();
3893
John McCall2d74de92009-12-01 22:10:20 +00003894 // Handle the implicit-member-access case.
3895 if (!BaseExpr) {
3896 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003897 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003898 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003899
Douglas Gregorb15af892010-01-07 23:12:05 +00003900 SourceLocation Loc = R.getNameLoc();
3901 if (SS.getRange().isValid())
3902 Loc = SS.getRange().getBegin();
3903 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003904 }
3905
John McCall10eae182009-11-30 22:42:35 +00003906 bool ShouldCheckUse = true;
3907 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3908 // Don't diagnose the use of a virtual member function unless it's
3909 // explicitly qualified.
3910 if (MD->isVirtual() && !SS.isSet())
3911 ShouldCheckUse = false;
3912 }
3913
3914 // Check the use of this member.
3915 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3916 Owned(BaseExpr);
3917 return ExprError();
3918 }
3919
John McCall34376a62010-12-04 03:47:34 +00003920 // Perform a property load on the base regardless of whether we
3921 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003922 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3923 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3924 if (Result.isInvalid())
3925 return ExprError();
3926 BaseExpr = Result.take();
3927 }
John McCall34376a62010-12-04 03:47:34 +00003928
John McCallfeb624a2010-11-23 20:48:44 +00003929 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3930 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3931 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003932
Francois Pichet783dd6e2010-11-21 06:08:52 +00003933 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3934 // We may have found a field within an anonymous union or struct
3935 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003936 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003937 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003938
John McCall10eae182009-11-30 22:42:35 +00003939 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3940 MarkDeclarationReferenced(MemberLoc, Var);
3941 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003942 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003943 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003944 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003945 }
3946
John McCall7decc9e2010-11-18 06:31:45 +00003947 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00003948 ExprValueKind valueKind;
3949 QualType type;
3950 if (MemberFn->isInstance()) {
3951 valueKind = VK_RValue;
3952 type = Context.BoundMemberTy;
3953 } else {
3954 valueKind = VK_LValue;
3955 type = MemberFn->getType();
3956 }
3957
John McCall10eae182009-11-30 22:42:35 +00003958 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3959 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003960 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00003961 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003962 }
John McCall7decc9e2010-11-18 06:31:45 +00003963 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003964
3965 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3966 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3967 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003968 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003969 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003970 }
3971
3972 Owned(BaseExpr);
3973
Douglas Gregor861eb802010-04-25 20:55:08 +00003974 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003975 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003976 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003977 << MemberName << BaseType << int(IsArrow);
3978 else
3979 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3980 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003981
Douglas Gregor861eb802010-04-25 20:55:08 +00003982 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3983 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003984 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003985 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003986}
3987
John McCall68fc88ec2010-12-15 16:46:44 +00003988/// Given that normal member access failed on the given expression,
3989/// and given that the expression's type involves builtin-id or
3990/// builtin-Class, decide whether substituting in the redefinition
3991/// types would be profitable. The redefinition type is whatever
3992/// this translation unit tried to typedef to id/Class; we store
3993/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00003994static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00003995 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00003996 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00003997 if (!opty) return false;
3998
3999 const ObjCObjectType *ty = opty->getObjectType();
4000
4001 QualType redef;
4002 if (ty->isObjCId()) {
4003 redef = S.Context.ObjCIdRedefinitionType;
4004 } else if (ty->isObjCClass()) {
4005 redef = S.Context.ObjCClassRedefinitionType;
4006 } else {
4007 return false;
4008 }
4009
4010 // Do the substitution as long as the redefinition type isn't just a
4011 // possibly-qualified pointer to builtin-id or builtin-Class again.
4012 opty = redef->getAs<ObjCObjectPointerType>();
4013 if (opty && !opty->getObjectType()->getInterface() != 0)
4014 return false;
4015
John Wiegley01296292011-04-08 18:41:53 +00004016 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004017 return true;
4018}
4019
John McCall10eae182009-11-30 22:42:35 +00004020/// Look up the given member of the given non-type-dependent
4021/// expression. This can return in one of two ways:
4022/// * If it returns a sentinel null-but-valid result, the caller will
4023/// assume that lookup was performed and the results written into
4024/// the provided structure. It will take over from there.
4025/// * Otherwise, the returned expression will be produced in place of
4026/// an ordinary member expression.
4027///
4028/// The ObjCImpDecl bit is a gross hack that will need to be properly
4029/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004030ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004031Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004032 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004033 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004034 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004035 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004036
Steve Naroffeaaae462007-12-16 21:42:28 +00004037 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004038 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004039
John Wiegley01296292011-04-08 18:41:53 +00004040 if (IsArrow) {
4041 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4042 if (BaseExpr.isInvalid())
4043 return ExprError();
4044 }
4045
4046 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004047 assert(!BaseType->isDependentType());
4048
4049 DeclarationName MemberName = R.getLookupName();
4050 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004051
John McCall68fc88ec2010-12-15 16:46:44 +00004052 // For later type-checking purposes, turn arrow accesses into dot
4053 // accesses. The only access type we support that doesn't follow
4054 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4055 // and those never use arrows, so this is unaffected.
4056 if (IsArrow) {
4057 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4058 BaseType = Ptr->getPointeeType();
4059 else if (const ObjCObjectPointerType *Ptr
4060 = BaseType->getAs<ObjCObjectPointerType>())
4061 BaseType = Ptr->getPointeeType();
4062 else if (BaseType->isRecordType()) {
4063 // Recover from arrow accesses to records, e.g.:
4064 // struct MyRecord foo;
4065 // foo->bar
4066 // This is actually well-formed in C++ if MyRecord has an
4067 // overloaded operator->, but that should have been dealt with
4068 // by now.
4069 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004070 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004071 << FixItHint::CreateReplacement(OpLoc, ".");
4072 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004073 } else if (BaseType == Context.BoundMemberTy) {
4074 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004075 } else {
4076 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004077 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004078 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004079 }
4080 }
4081
John McCall68fc88ec2010-12-15 16:46:44 +00004082 // Handle field access to simple records.
4083 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004084 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004085 RTy, OpLoc, SS, HasTemplateArgs))
4086 return ExprError();
4087
4088 // Returning valid-but-null is how we indicate to the caller that
4089 // the lookup result was filled in.
4090 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004091 }
John McCall10eae182009-11-30 22:42:35 +00004092
John McCall68fc88ec2010-12-15 16:46:44 +00004093 // Handle ivar access to Objective-C objects.
4094 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004095 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004096
4097 // There are three cases for the base type:
4098 // - builtin id (qualified or unqualified)
4099 // - builtin Class (qualified or unqualified)
4100 // - an interface
4101 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4102 if (!IDecl) {
4103 // There's an implicit 'isa' ivar on all objects.
4104 // But we only actually find it this way on objects of type 'id',
4105 // apparently.
4106 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004107 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004108 Context.getObjCClassType()));
4109
4110 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4111 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4112 ObjCImpDecl, HasTemplateArgs);
4113 goto fail;
4114 }
4115
4116 ObjCInterfaceDecl *ClassDeclared;
4117 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4118
4119 if (!IV) {
4120 // Attempt to correct for typos in ivar names.
4121 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4122 LookupMemberName);
4123 if (CorrectTypo(Res, 0, 0, IDecl, false,
4124 IsArrow ? CTC_ObjCIvarLookup
4125 : CTC_ObjCPropertyLookup) &&
4126 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4127 Diag(R.getNameLoc(),
4128 diag::err_typecheck_member_reference_ivar_suggest)
4129 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4130 << FixItHint::CreateReplacement(R.getNameLoc(),
4131 IV->getNameAsString());
4132 Diag(IV->getLocation(), diag::note_previous_decl)
4133 << IV->getDeclName();
4134 } else {
4135 Res.clear();
4136 Res.setLookupName(Member);
4137
4138 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4139 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004140 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004141 return ExprError();
4142 }
4143 }
4144
4145 // If the decl being referenced had an error, return an error for this
4146 // sub-expr without emitting another error, in order to avoid cascading
4147 // error cases.
4148 if (IV->isInvalidDecl())
4149 return ExprError();
4150
4151 // Check whether we can reference this field.
4152 if (DiagnoseUseOfDecl(IV, MemberLoc))
4153 return ExprError();
4154 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4155 IV->getAccessControl() != ObjCIvarDecl::Package) {
4156 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4157 if (ObjCMethodDecl *MD = getCurMethodDecl())
4158 ClassOfMethodDecl = MD->getClassInterface();
4159 else if (ObjCImpDecl && getCurFunctionDecl()) {
4160 // Case of a c-function declared inside an objc implementation.
4161 // FIXME: For a c-style function nested inside an objc implementation
4162 // class, there is no implementation context available, so we pass
4163 // down the context as argument to this routine. Ideally, this context
4164 // need be passed down in the AST node and somehow calculated from the
4165 // AST for a function decl.
4166 if (ObjCImplementationDecl *IMPD =
4167 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4168 ClassOfMethodDecl = IMPD->getClassInterface();
4169 else if (ObjCCategoryImplDecl* CatImplClass =
4170 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4171 ClassOfMethodDecl = CatImplClass->getClassInterface();
4172 }
4173
4174 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4175 if (ClassDeclared != IDecl ||
4176 ClassOfMethodDecl != ClassDeclared)
4177 Diag(MemberLoc, diag::error_private_ivar_access)
4178 << IV->getDeclName();
4179 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4180 // @protected
4181 Diag(MemberLoc, diag::error_protected_ivar_access)
4182 << IV->getDeclName();
4183 }
4184
4185 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004186 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004187 IsArrow));
4188 }
4189
4190 // Objective-C property access.
4191 const ObjCObjectPointerType *OPT;
4192 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4193 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004194 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4195 if (BaseExpr.isInvalid())
4196 return ExprError();
4197
4198 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004199
4200 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4201
4202 const ObjCObjectType *OT = OPT->getObjectType();
4203
4204 // id, with and without qualifiers.
4205 if (OT->isObjCId()) {
4206 // Check protocols on qualified interfaces.
4207 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4208 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4209 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4210 // Check the use of this declaration
4211 if (DiagnoseUseOfDecl(PD, MemberLoc))
4212 return ExprError();
4213
4214 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4215 VK_LValue,
4216 OK_ObjCProperty,
4217 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004218 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004219 }
4220
4221 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4222 // Check the use of this method.
4223 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4224 return ExprError();
4225 Selector SetterSel =
4226 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4227 PP.getSelectorTable(), Member);
4228 ObjCMethodDecl *SMD = 0;
4229 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4230 SetterSel, Context))
4231 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4232 QualType PType = OMD->getSendResultType();
4233
4234 ExprValueKind VK = VK_LValue;
4235 if (!getLangOptions().CPlusPlus &&
4236 IsCForbiddenLValueType(Context, PType))
4237 VK = VK_RValue;
4238 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4239
4240 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4241 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004242 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004243 }
4244 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004245 // Use of id.member can only be for a property reference. Do not
4246 // use the 'id' redefinition in this case.
4247 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004248 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4249 ObjCImpDecl, HasTemplateArgs);
4250
4251 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4252 << MemberName << BaseType);
4253 }
4254
4255 // 'Class', unqualified only.
4256 if (OT->isObjCClass()) {
4257 // Only works in a method declaration (??!).
4258 ObjCMethodDecl *MD = getCurMethodDecl();
4259 if (!MD) {
4260 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4261 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4262 ObjCImpDecl, HasTemplateArgs);
4263
4264 goto fail;
4265 }
4266
4267 // Also must look for a getter name which uses property syntax.
4268 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004269 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4270 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004271 if ((Getter = IFace->lookupClassMethod(Sel))) {
4272 // Check the use of this method.
4273 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4274 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004275 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004276 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004277 // If we found a getter then this may be a valid dot-reference, we
4278 // will look for the matching setter, in case it is needed.
4279 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004280 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4281 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004282 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4283 if (!Setter) {
4284 // If this reference is in an @implementation, also check for 'private'
4285 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004286 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004287 }
4288 // Look through local category implementations associated with the class.
4289 if (!Setter)
4290 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004291
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004292 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4293 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004294
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004295 if (Getter || Setter) {
4296 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004297
John McCall4bc41ae2010-11-18 19:01:18 +00004298 ExprValueKind VK = VK_LValue;
4299 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004300 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004301 if (!getLangOptions().CPlusPlus &&
4302 IsCForbiddenLValueType(Context, PType))
4303 VK = VK_RValue;
4304 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004305 // Get the expression type from Setter's incoming parameter.
4306 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004307 }
4308 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4309
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004310 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004311 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4312 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004313 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004314 }
John McCall68fc88ec2010-12-15 16:46:44 +00004315
4316 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4317 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4318 ObjCImpDecl, HasTemplateArgs);
4319
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004320 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004321 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004322 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004323
John McCall68fc88ec2010-12-15 16:46:44 +00004324 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004325 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004326 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004327 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004328
Chris Lattnerb63a7452008-07-21 04:28:12 +00004329 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004330 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004331 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004332 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004333 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004334 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4335 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004336 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004337 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004338
John Wiegley01296292011-04-08 18:41:53 +00004339 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004340 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004341 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004342
John McCall68fc88ec2010-12-15 16:46:44 +00004343 // Adjust builtin-sel to the appropriate redefinition type if that's
4344 // not just a pointer to builtin-sel again.
4345 if (IsArrow &&
4346 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4347 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004348 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4349 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004350 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4351 ObjCImpDecl, HasTemplateArgs);
4352 }
4353
4354 // Failure cases.
4355 fail:
4356
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004357 // Recover from dot accesses to pointers, e.g.:
4358 // type *foo;
4359 // foo.bar
4360 // This is actually well-formed in two cases:
4361 // - 'type' is an Objective C type
4362 // - 'bar' is a pseudo-destructor name which happens to refer to
4363 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004364 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004365 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4366 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004367 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004368 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004369 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004370
4371 // Recurse as an -> access.
4372 IsArrow = true;
4373 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4374 ObjCImpDecl, HasTemplateArgs);
4375 }
John McCall68fc88ec2010-12-15 16:46:44 +00004376 }
4377
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004378 // If the user is trying to apply -> or . to a function name, it's probably
4379 // because they forgot parentheses to call that function.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004380 QualType ZeroArgCallTy;
4381 UnresolvedSet<4> Overloads;
4382 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4383 if (ZeroArgCallTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00004384 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004385 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4386 UnresolvedSet<2> PlausibleOverloads;
4387 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4388 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4389 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4390 QualType OverloadResultTy = OverloadDecl->getResultType();
4391 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4392 (IsArrow && OverloadResultTy->isPointerType() &&
4393 OverloadResultTy->getPointeeType()->isRecordType()))
4394 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004395 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004396 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004397 return ExprError();
4398 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004399 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4400 (IsArrow && ZeroArgCallTy->isPointerType() &&
4401 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4402 // At this point, we know BaseExpr looks like it's potentially callable
4403 // with 0 arguments, and that it returns something of a reasonable type,
4404 // so we can emit a fixit and carry on pretending that BaseExpr was
4405 // actually a CallExpr.
4406 SourceLocation ParenInsertionLoc =
4407 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4408 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4409 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4410 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4411 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4412 // while doing so.
4413 ExprResult NewBase =
4414 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4415 MultiExprArg(*this, 0, 0),
4416 ParenInsertionLoc.getFileLocWithOffset(1));
4417 if (NewBase.isInvalid())
4418 return ExprError();
4419 BaseExpr = NewBase;
4420 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4421 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4422 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004423 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004424 }
4425
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004426 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004427 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004428
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004429 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004430}
4431
John McCall10eae182009-11-30 22:42:35 +00004432/// The main callback when the parser finds something like
4433/// expression . [nested-name-specifier] identifier
4434/// expression -> [nested-name-specifier] identifier
4435/// where 'identifier' encompasses a fairly broad spectrum of
4436/// possibilities, including destructor and operator references.
4437///
4438/// \param OpKind either tok::arrow or tok::period
4439/// \param HasTrailingLParen whether the next token is '(', which
4440/// is used to diagnose mis-uses of special members that can
4441/// only be called
4442/// \param ObjCImpDecl the current ObjC @implementation decl;
4443/// this is an ugly hack around the fact that ObjC @implementations
4444/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004445ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004446 SourceLocation OpLoc,
4447 tok::TokenKind OpKind,
4448 CXXScopeSpec &SS,
4449 UnqualifiedId &Id,
4450 Decl *ObjCImpDecl,
4451 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004452 if (SS.isSet() && SS.isInvalid())
4453 return ExprError();
4454
Francois Pichet64225792011-01-18 05:04:39 +00004455 // Warn about the explicit constructor calls Microsoft extension.
4456 if (getLangOptions().Microsoft &&
4457 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4458 Diag(Id.getSourceRange().getBegin(),
4459 diag::ext_ms_explicit_constructor_call);
4460
John McCall10eae182009-11-30 22:42:35 +00004461 TemplateArgumentListInfo TemplateArgsBuffer;
4462
4463 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004464 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004465 const TemplateArgumentListInfo *TemplateArgs;
4466 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004467 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004468
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004469 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004470 bool IsArrow = (OpKind == tok::arrow);
4471
4472 NamedDecl *FirstQualifierInScope
4473 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4474 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4475
4476 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004477 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004478 if (Result.isInvalid()) return ExprError();
4479 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004480
Douglas Gregor41f90302010-04-12 20:54:26 +00004481 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4482 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004483 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004484 IsArrow, OpLoc,
4485 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004486 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004487 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004488 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004489 ExprResult BaseResult = Owned(Base);
4490 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004491 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004492 if (BaseResult.isInvalid())
4493 return ExprError();
4494 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004495
John McCalle9cccd82010-06-16 08:42:20 +00004496 if (Result.isInvalid()) {
4497 Owned(Base);
4498 return ExprError();
4499 }
John McCall10eae182009-11-30 22:42:35 +00004500
John McCalle9cccd82010-06-16 08:42:20 +00004501 if (Result.get()) {
4502 // The only way a reference to a destructor can be used is to
4503 // immediately call it, which falls into this case. If the
4504 // next token is not a '(', produce a diagnostic and build the
4505 // call now.
4506 if (!HasTrailingLParen &&
4507 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004508 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004509
John McCalle9cccd82010-06-16 08:42:20 +00004510 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004511 }
4512
John McCallb268a282010-08-23 23:25:46 +00004513 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004514 OpLoc, IsArrow, SS, FirstQualifierInScope,
4515 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004516 }
4517
4518 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004519}
4520
John McCalldadc5752010-08-24 06:29:42 +00004521ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004522 FunctionDecl *FD,
4523 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004524 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004525 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004526 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004527 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004528 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004529 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004530 return ExprError();
4531 }
4532
4533 if (Param->hasUninstantiatedDefaultArg()) {
4534 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004535
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004536 // Instantiate the expression.
4537 MultiLevelTemplateArgumentList ArgList
4538 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004539
Nico Weber44887f62010-11-29 18:19:25 +00004540 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004541 = ArgList.getInnermost();
4542 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4543 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004544
Nico Weber44887f62010-11-29 18:19:25 +00004545 ExprResult Result;
4546 {
4547 // C++ [dcl.fct.default]p5:
4548 // The names in the [default argument] expression are bound, and
4549 // the semantic constraints are checked, at the point where the
4550 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004551 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004552 Result = SubstExpr(UninstExpr, ArgList);
4553 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004554 if (Result.isInvalid())
4555 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004556
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004557 // Check the expression as an initializer for the parameter.
4558 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004559 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004560 InitializationKind Kind
4561 = InitializationKind::CreateCopy(Param->getLocation(),
4562 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4563 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004564
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004565 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4566 Result = InitSeq.Perform(*this, Entity, Kind,
4567 MultiExprArg(*this, &ResultE, 1));
4568 if (Result.isInvalid())
4569 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004570
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004571 // Build the default argument expression.
4572 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4573 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004574 }
4575
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004576 // If the default expression creates temporaries, we need to
4577 // push them to the current stack of expression temporaries so they'll
4578 // be properly destroyed.
4579 // FIXME: We should really be rebuilding the default argument with new
4580 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004581 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4582 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4583 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4584 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4585 ExprTemporaries.push_back(Temporary);
4586 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004587
4588 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004589 // Just mark all of the declarations in this potentially-evaluated expression
4590 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004591 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004592 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004593}
4594
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004595/// ConvertArgumentsForCall - Converts the arguments specified in
4596/// Args/NumArgs to the parameter types of the function FDecl with
4597/// function prototype Proto. Call is the call expression itself, and
4598/// Fn is the function expression. For a C++ member function, this
4599/// routine does not attempt to convert the object argument. Returns
4600/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004601bool
4602Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004603 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004604 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004605 Expr **Args, unsigned NumArgs,
4606 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004607 // Bail out early if calling a builtin with custom typechecking.
4608 // We don't need to do this in the
4609 if (FDecl)
4610 if (unsigned ID = FDecl->getBuiltinID())
4611 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4612 return false;
4613
Mike Stump4e1f26a2009-02-19 03:04:26 +00004614 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004615 // assignment, to the types of the corresponding parameter, ...
4616 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004617 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004618
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004619 // If too few arguments are available (and we don't have default
4620 // arguments for the remaining parameters), don't make the call.
4621 if (NumArgs < NumArgsInProto) {
4622 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4623 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004624 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004625 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004626 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004627 }
4628
4629 // If too many are passed and not variadic, error on the extras and drop
4630 // them.
4631 if (NumArgs > NumArgsInProto) {
4632 if (!Proto->isVariadic()) {
4633 Diag(Args[NumArgsInProto]->getLocStart(),
4634 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004635 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004636 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004637 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4638 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004639
4640 // Emit the location of the prototype.
4641 if (FDecl && !FDecl->getBuiltinID())
4642 Diag(FDecl->getLocStart(),
4643 diag::note_typecheck_call_too_many_args)
4644 << FDecl;
4645
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004646 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004647 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004648 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004649 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004650 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004651 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004652 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004653 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4654 if (Fn->getType()->isBlockPointerType())
4655 CallType = VariadicBlock; // Block
4656 else if (isa<MemberExpr>(Fn))
4657 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004658 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004659 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004660 if (Invalid)
4661 return true;
4662 unsigned TotalNumArgs = AllArgs.size();
4663 for (unsigned i = 0; i < TotalNumArgs; ++i)
4664 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004665
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004666 return false;
4667}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004668
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004669bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4670 FunctionDecl *FDecl,
4671 const FunctionProtoType *Proto,
4672 unsigned FirstProtoArg,
4673 Expr **Args, unsigned NumArgs,
4674 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004675 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004676 unsigned NumArgsInProto = Proto->getNumArgs();
4677 unsigned NumArgsToCheck = NumArgs;
4678 bool Invalid = false;
4679 if (NumArgs != NumArgsInProto)
4680 // Use default arguments for missing arguments
4681 NumArgsToCheck = NumArgsInProto;
4682 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004683 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004684 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004685 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004687 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004688 if (ArgIx < NumArgs) {
4689 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004690
Eli Friedman3164fb12009-03-22 22:00:50 +00004691 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4692 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004693 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004694 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004695 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004696
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004697 // Pass the argument
4698 ParmVarDecl *Param = 0;
4699 if (FDecl && i < FDecl->getNumParams())
4700 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004701
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004702 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004703 Param? InitializedEntity::InitializeParameter(Context, Param)
4704 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004705 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004706 SourceLocation(),
4707 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004708 if (ArgE.isInvalid())
4709 return true;
4710
4711 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004712 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004713 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004714
John McCalldadc5752010-08-24 06:29:42 +00004715 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004716 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004717 if (ArgExpr.isInvalid())
4718 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004719
Anders Carlsson355933d2009-08-25 03:49:14 +00004720 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004721 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004722 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004723 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004724
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004725 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004726 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004727
4728 // Assume that extern "C" functions with variadic arguments that
4729 // return __unknown_anytype aren't *really* variadic.
4730 if (Proto->getResultType() == Context.UnknownAnyTy &&
4731 FDecl && FDecl->isExternC()) {
4732 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4733 ExprResult arg;
4734 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4735 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4736 else
4737 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4738 Invalid |= arg.isInvalid();
4739 AllArgs.push_back(arg.take());
4740 }
4741
4742 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4743 } else {
4744 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4745 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4746 Invalid |= Arg.isInvalid();
4747 AllArgs.push_back(Arg.take());
4748 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004749 }
4750 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004751 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004752}
4753
John McCall2979fe02011-04-12 00:42:48 +00004754/// Given a function expression of unknown-any type, try to rebuild it
4755/// to have a function type.
4756static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4757
Steve Naroff83895f72007-09-16 03:34:24 +00004758/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004759/// This provides the location of the left/right parens and a list of comma
4760/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004761ExprResult
John McCallb268a282010-08-23 23:25:46 +00004762Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004763 MultiExprArg args, SourceLocation RParenLoc,
4764 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004765 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004766
4767 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004768 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004769 if (Result.isInvalid()) return ExprError();
4770 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004771
John McCallb268a282010-08-23 23:25:46 +00004772 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004774 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004775 // If this is a pseudo-destructor expression, build the call immediately.
4776 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4777 if (NumArgs > 0) {
4778 // Pseudo-destructor calls should not have any arguments.
4779 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004780 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004781 SourceRange(Args[0]->getLocStart(),
4782 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004783
Douglas Gregorad8a3362009-09-04 17:36:40 +00004784 NumArgs = 0;
4785 }
Mike Stump11289f42009-09-09 15:08:12 +00004786
Douglas Gregorad8a3362009-09-04 17:36:40 +00004787 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004788 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004789 }
Mike Stump11289f42009-09-09 15:08:12 +00004790
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004791 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004792 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004793 // FIXME: Will need to cache the results of name lookup (including ADL) in
4794 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004795 bool Dependent = false;
4796 if (Fn->isTypeDependent())
4797 Dependent = true;
4798 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4799 Dependent = true;
4800
Peter Collingbourne41f85462011-02-09 21:07:24 +00004801 if (Dependent) {
4802 if (ExecConfig) {
4803 return Owned(new (Context) CUDAKernelCallExpr(
4804 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4805 Context.DependentTy, VK_RValue, RParenLoc));
4806 } else {
4807 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4808 Context.DependentTy, VK_RValue,
4809 RParenLoc));
4810 }
4811 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004812
4813 // Determine whether this is a call to an object (C++ [over.call.object]).
4814 if (Fn->getType()->isRecordType())
4815 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004816 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004817
John McCall2979fe02011-04-12 00:42:48 +00004818 if (Fn->getType() == Context.UnknownAnyTy) {
4819 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4820 if (result.isInvalid()) return ExprError();
4821 Fn = result.take();
4822 }
4823
John McCall0009fcc2011-04-26 20:42:42 +00004824 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004825 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004826 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004827 }
John McCall0009fcc2011-04-26 20:42:42 +00004828 }
John McCall10eae182009-11-30 22:42:35 +00004829
John McCall0009fcc2011-04-26 20:42:42 +00004830 // Check for overloaded calls. This can happen even in C due to extensions.
4831 if (Fn->getType() == Context.OverloadTy) {
4832 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4833
4834 // We aren't supposed to apply this logic if there's an '&' involved.
4835 if (!find.IsAddressOfOperand) {
4836 OverloadExpr *ovl = find.Expression;
4837 if (isa<UnresolvedLookupExpr>(ovl)) {
4838 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4839 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4840 RParenLoc, ExecConfig);
4841 } else {
John McCall2d74de92009-12-01 22:10:20 +00004842 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004843 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004844 }
4845 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004846 }
4847
Douglas Gregore254f902009-02-04 00:32:51 +00004848 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004849
Eli Friedmane14b1992009-12-26 03:35:45 +00004850 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004851
John McCall57500772009-12-16 12:17:52 +00004852 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004853 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4854 if (UnOp->getOpcode() == UO_AddrOf)
4855 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4856
John McCall57500772009-12-16 12:17:52 +00004857 if (isa<DeclRefExpr>(NakedFn))
4858 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00004859 else if (isa<MemberExpr>(NakedFn))
4860 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004861
Peter Collingbourne41f85462011-02-09 21:07:24 +00004862 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4863 ExecConfig);
4864}
4865
4866ExprResult
4867Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4868 MultiExprArg execConfig, SourceLocation GGGLoc) {
4869 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4870 if (!ConfigDecl)
4871 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4872 << "cudaConfigureCall");
4873 QualType ConfigQTy = ConfigDecl->getType();
4874
4875 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4876 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4877
4878 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004879}
4880
John McCall57500772009-12-16 12:17:52 +00004881/// BuildResolvedCallExpr - Build a call to a resolved expression,
4882/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004883/// unary-convert to an expression of function-pointer or
4884/// block-pointer type.
4885///
4886/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004887ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004888Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4889 SourceLocation LParenLoc,
4890 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004891 SourceLocation RParenLoc,
4892 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004893 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4894
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004895 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004896 ExprResult Result = UsualUnaryConversions(Fn);
4897 if (Result.isInvalid())
4898 return ExprError();
4899 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004900
Chris Lattner08464942007-12-28 05:29:59 +00004901 // Make the call expr early, before semantic checks. This guarantees cleanup
4902 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004903 CallExpr *TheCall;
4904 if (Config) {
4905 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4906 cast<CallExpr>(Config),
4907 Args, NumArgs,
4908 Context.BoolTy,
4909 VK_RValue,
4910 RParenLoc);
4911 } else {
4912 TheCall = new (Context) CallExpr(Context, Fn,
4913 Args, NumArgs,
4914 Context.BoolTy,
4915 VK_RValue,
4916 RParenLoc);
4917 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004918
John McCallbebede42011-02-26 05:39:39 +00004919 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4920
4921 // Bail out early if calling a builtin with custom typechecking.
4922 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4923 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4924
John McCall31996342011-04-07 08:22:57 +00004925 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004926 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004927 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004928 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4929 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004930 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004931 if (FuncT == 0)
4932 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4933 << Fn->getType() << Fn->getSourceRange());
4934 } else if (const BlockPointerType *BPT =
4935 Fn->getType()->getAs<BlockPointerType>()) {
4936 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4937 } else {
John McCall31996342011-04-07 08:22:57 +00004938 // Handle calls to expressions of unknown-any type.
4939 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004940 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004941 if (rewrite.isInvalid()) return ExprError();
4942 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004943 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004944 goto retry;
4945 }
4946
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004947 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4948 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004949 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004950
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004951 if (getLangOptions().CUDA) {
4952 if (Config) {
4953 // CUDA: Kernel calls must be to global functions
4954 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4955 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4956 << FDecl->getName() << Fn->getSourceRange());
4957
4958 // CUDA: Kernel function must have 'void' return type
4959 if (!FuncT->getResultType()->isVoidType())
4960 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4961 << Fn->getType() << Fn->getSourceRange());
4962 }
4963 }
4964
Eli Friedman3164fb12009-03-22 22:00:50 +00004965 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004966 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004967 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004968 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004969 return ExprError();
4970
Chris Lattner08464942007-12-28 05:29:59 +00004971 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004972 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004973 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004974
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004975 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004976 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004977 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004978 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004979 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004980 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004981
Douglas Gregord8e97de2009-04-02 15:37:10 +00004982 if (FDecl) {
4983 // Check if we have too few/too many template arguments, based
4984 // on our knowledge of the function definition.
4985 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004986 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004987 const FunctionProtoType *Proto
4988 = Def->getType()->getAs<FunctionProtoType>();
4989 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004990 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4991 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004992 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004993
4994 // If the function we're calling isn't a function prototype, but we have
4995 // a function prototype from a prior declaratiom, use that prototype.
4996 if (!FDecl->hasPrototype())
4997 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004998 }
4999
Steve Naroff0b661582007-08-28 23:30:39 +00005000 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005001 for (unsigned i = 0; i != NumArgs; i++) {
5002 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005003
5004 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005005 InitializedEntity Entity
5006 = InitializedEntity::InitializeParameter(Context,
5007 Proto->getArgType(i));
5008 ExprResult ArgE = PerformCopyInitialization(Entity,
5009 SourceLocation(),
5010 Owned(Arg));
5011 if (ArgE.isInvalid())
5012 return true;
5013
5014 Arg = ArgE.takeAs<Expr>();
5015
5016 } else {
John Wiegley01296292011-04-08 18:41:53 +00005017 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5018
5019 if (ArgE.isInvalid())
5020 return true;
5021
5022 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005023 }
5024
Douglas Gregor83025412010-10-26 05:45:40 +00005025 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5026 Arg->getType(),
5027 PDiag(diag::err_call_incomplete_argument)
5028 << Arg->getSourceRange()))
5029 return ExprError();
5030
Chris Lattner08464942007-12-28 05:29:59 +00005031 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005032 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005033 }
Chris Lattner08464942007-12-28 05:29:59 +00005034
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005035 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5036 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005037 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5038 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005039
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005040 // Check for sentinels
5041 if (NDecl)
5042 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005043
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005044 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005045 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005046 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005047 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005048
John McCallbebede42011-02-26 05:39:39 +00005049 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005050 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005051 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005052 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005053 return ExprError();
5054 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005055
John McCallb268a282010-08-23 23:25:46 +00005056 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005057}
5058
John McCalldadc5752010-08-24 06:29:42 +00005059ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005060Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005061 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005062 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005063 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005064 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005065
5066 TypeSourceInfo *TInfo;
5067 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5068 if (!TInfo)
5069 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5070
John McCallb268a282010-08-23 23:25:46 +00005071 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005072}
5073
John McCalldadc5752010-08-24 06:29:42 +00005074ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005075Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005076 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005077 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005078
Eli Friedman37a186d2008-05-20 05:22:08 +00005079 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005080 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5081 PDiag(diag::err_illegal_decl_array_incomplete_type)
5082 << SourceRange(LParenLoc,
5083 literalExpr->getSourceRange().getEnd())))
5084 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005085 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005086 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5087 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005088 } else if (!literalType->isDependentType() &&
5089 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005090 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005091 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005092 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005093 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005094
Douglas Gregor85dabae2009-12-16 01:38:02 +00005095 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005096 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005097 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005098 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005099 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005100 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005101 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005102 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005103 &literalType);
5104 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005105 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005106 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005107
Chris Lattner79413952008-12-04 23:50:19 +00005108 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005109 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005110 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005111 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005112 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005113
John McCall7decc9e2010-11-18 06:31:45 +00005114 // In C, compound literals are l-values for some reason.
5115 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5116
John McCall5d7aa7f2010-01-19 22:33:45 +00005117 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005118 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005119}
5120
John McCalldadc5752010-08-24 06:29:42 +00005121ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005122Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005123 SourceLocation RBraceLoc) {
5124 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005125 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005126
Steve Naroff30d242c2007-09-15 18:49:24 +00005127 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005128 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005129
Ted Kremenekac034612010-04-13 23:39:13 +00005130 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5131 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005132 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005133 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005134}
5135
John McCalld7646252010-11-14 08:17:51 +00005136/// Prepares for a scalar cast, performing all the necessary stages
5137/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005138static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005139 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5140 // Also, callers should have filtered out the invalid cases with
5141 // pointers. Everything else should be possible.
5142
John Wiegley01296292011-04-08 18:41:53 +00005143 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005144 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005145 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005146
John McCall8cb679e2010-11-15 09:13:47 +00005147 switch (SrcTy->getScalarTypeKind()) {
5148 case Type::STK_MemberPointer:
5149 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005150
John McCall8cb679e2010-11-15 09:13:47 +00005151 case Type::STK_Pointer:
5152 switch (DestTy->getScalarTypeKind()) {
5153 case Type::STK_Pointer:
5154 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005155 CK_AnyPointerToObjCPointerCast :
5156 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005157 case Type::STK_Bool:
5158 return CK_PointerToBoolean;
5159 case Type::STK_Integral:
5160 return CK_PointerToIntegral;
5161 case Type::STK_Floating:
5162 case Type::STK_FloatingComplex:
5163 case Type::STK_IntegralComplex:
5164 case Type::STK_MemberPointer:
5165 llvm_unreachable("illegal cast from pointer");
5166 }
5167 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005168
John McCall8cb679e2010-11-15 09:13:47 +00005169 case Type::STK_Bool: // casting from bool is like casting from an integer
5170 case Type::STK_Integral:
5171 switch (DestTy->getScalarTypeKind()) {
5172 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005173 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005174 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005175 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005176 case Type::STK_Bool:
5177 return CK_IntegralToBoolean;
5178 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005179 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005180 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005181 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005182 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005183 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5184 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005185 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005186 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005187 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5188 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005189 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005190 case Type::STK_MemberPointer:
5191 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005192 }
5193 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005194
John McCall8cb679e2010-11-15 09:13:47 +00005195 case Type::STK_Floating:
5196 switch (DestTy->getScalarTypeKind()) {
5197 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005198 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005199 case Type::STK_Bool:
5200 return CK_FloatingToBoolean;
5201 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005202 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005203 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005204 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5205 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005206 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005207 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005208 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5209 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005210 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005211 case Type::STK_Pointer:
5212 llvm_unreachable("valid float->pointer cast?");
5213 case Type::STK_MemberPointer:
5214 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005215 }
5216 break;
5217
John McCall8cb679e2010-11-15 09:13:47 +00005218 case Type::STK_FloatingComplex:
5219 switch (DestTy->getScalarTypeKind()) {
5220 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005221 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005222 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005223 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005224 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005225 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005226 if (S.Context.hasSameType(ET, DestTy))
5227 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005228 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005229 return CK_FloatingCast;
5230 }
John McCall8cb679e2010-11-15 09:13:47 +00005231 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005232 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005233 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005234 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5235 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005236 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005237 case Type::STK_Pointer:
5238 llvm_unreachable("valid complex float->pointer cast?");
5239 case Type::STK_MemberPointer:
5240 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005241 }
5242 break;
5243
John McCall8cb679e2010-11-15 09:13:47 +00005244 case Type::STK_IntegralComplex:
5245 switch (DestTy->getScalarTypeKind()) {
5246 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005247 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005248 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005249 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005250 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005251 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005252 if (S.Context.hasSameType(ET, DestTy))
5253 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005254 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005255 return CK_IntegralCast;
5256 }
John McCall8cb679e2010-11-15 09:13:47 +00005257 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005258 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005259 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005260 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5261 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005262 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005263 case Type::STK_Pointer:
5264 llvm_unreachable("valid complex int->pointer cast?");
5265 case Type::STK_MemberPointer:
5266 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005267 }
5268 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005269 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005270
John McCalld7646252010-11-14 08:17:51 +00005271 llvm_unreachable("Unhandled scalar cast");
5272 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005273}
5274
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005275/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005276ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5277 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5278 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005279 if (castExpr->getType() == Context.UnknownAnyTy)
5280 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5281
Sebastian Redl9f831db2009-07-25 15:41:38 +00005282 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005283 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5284 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005285 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005286 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005287
John McCall3aef3d82011-04-10 19:13:55 +00005288 assert(!castExpr->getType()->isPlaceholderType());
5289
John McCall7decc9e2010-11-18 06:31:45 +00005290 // We only support r-value casts in C.
5291 VK = VK_RValue;
5292
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005293 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5294 // type needs to be scalar.
5295 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005296 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005297 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5298 if (castExprRes.isInvalid())
5299 return ExprError();
5300 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005301
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005302 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005303 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005304 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005305 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005306
John Wiegley01296292011-04-08 18:41:53 +00005307 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5308 if (castExprRes.isInvalid())
5309 return ExprError();
5310 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005311
Eli Friedmane98194d2010-07-17 20:43:49 +00005312 if (RequireCompleteType(TyR.getBegin(), castType,
5313 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005314 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005315
Anders Carlssonef918ac2009-10-16 02:35:04 +00005316 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005317 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005318 (castType->isStructureType() || castType->isUnionType())) {
5319 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005320 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005321 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5322 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005323 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005324 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005326
Anders Carlsson525b76b2009-10-16 02:48:28 +00005327 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005328 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005329 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005330 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005331 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005332 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005333 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005334 castExpr->getType()) &&
5335 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005336 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5337 << castExpr->getSourceRange();
5338 break;
5339 }
5340 }
John Wiegley01296292011-04-08 18:41:53 +00005341 if (Field == FieldEnd) {
5342 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005343 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005344 return ExprError();
5345 }
John McCalle3027922010-08-25 11:45:40 +00005346 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005347 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005348 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005349
Anders Carlsson525b76b2009-10-16 02:48:28 +00005350 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005351 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005352 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005353 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005354 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005355
John McCalld7646252010-11-14 08:17:51 +00005356 // The type we're casting to is known to be a scalar or vector.
5357
5358 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005359 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005360 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005361 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005362 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005363 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005364 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005365 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005366
5367 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005368 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005369
Anton Yartsev28ccef72011-03-27 09:32:40 +00005370 if (castType->isVectorType()) {
5371 if (castType->getAs<VectorType>()->getVectorKind() ==
5372 VectorType::AltiVecVector &&
5373 (castExpr->getType()->isIntegerType() ||
5374 castExpr->getType()->isFloatingType())) {
5375 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005376 return Owned(castExpr);
5377 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5378 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005379 } else
John Wiegley01296292011-04-08 18:41:53 +00005380 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005381 }
John Wiegley01296292011-04-08 18:41:53 +00005382 if (castExpr->getType()->isVectorType()) {
5383 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5384 return ExprError();
5385 else
5386 return Owned(castExpr);
5387 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005388
John McCalld7646252010-11-14 08:17:51 +00005389 // The source and target types are both scalars, i.e.
5390 // - arithmetic types (fundamental, enum, and complex)
5391 // - all kinds of pointers
5392 // Note that member pointers were filtered out with C++, above.
5393
John Wiegley01296292011-04-08 18:41:53 +00005394 if (isa<ObjCSelectorExpr>(castExpr)) {
5395 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5396 return ExprError();
5397 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005398
John McCalld7646252010-11-14 08:17:51 +00005399 // If either type is a pointer, the other type has to be either an
5400 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005401 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005402 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005403 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005404 castExprType->isArithmeticType()) {
5405 Diag(castExpr->getLocStart(),
5406 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005407 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005408 return ExprError();
5409 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005410 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005411 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5412 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005413 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005414 return ExprError();
5415 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005416 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005417
John Wiegley01296292011-04-08 18:41:53 +00005418 castExprRes = Owned(castExpr);
5419 Kind = PrepareScalarCast(*this, castExprRes, castType);
5420 if (castExprRes.isInvalid())
5421 return ExprError();
5422 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005423
John McCalld7646252010-11-14 08:17:51 +00005424 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005425 CheckCastAlign(castExpr, castType, TyR);
5426
John Wiegley01296292011-04-08 18:41:53 +00005427 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005428}
5429
Anders Carlsson525b76b2009-10-16 02:48:28 +00005430bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005431 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005432 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005433
Anders Carlssonde71adf2007-11-27 05:51:55 +00005434 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005435 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005436 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005437 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005438 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005439 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005440 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005441 } else
5442 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005443 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005444 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005445
John McCalle3027922010-08-25 11:45:40 +00005446 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005447 return false;
5448}
5449
John Wiegley01296292011-04-08 18:41:53 +00005450ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5451 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005452 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005453
Anders Carlsson43d70f82009-10-16 05:23:41 +00005454 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005455
Nate Begemanc8961a42009-06-27 22:05:55 +00005456 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5457 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005458 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005459 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5460 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005461 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005462 return ExprError();
5463 }
John McCalle3027922010-08-25 11:45:40 +00005464 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005465 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005466 }
5467
Nate Begemanbd956c42009-06-28 02:36:38 +00005468 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005469 // conversion will take place first from scalar to elt type, and then
5470 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005471 if (SrcTy->isPointerType())
5472 return Diag(R.getBegin(),
5473 diag::err_invalid_conversion_between_vector_and_scalar)
5474 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005475
5476 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005477 ExprResult CastExprRes = Owned(CastExpr);
5478 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5479 if (CastExprRes.isInvalid())
5480 return ExprError();
5481 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005482
John McCalle3027922010-08-25 11:45:40 +00005483 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005484 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005485}
5486
John McCalldadc5752010-08-24 06:29:42 +00005487ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005488Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005489 SourceLocation RParenLoc, Expr *castExpr) {
5490 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005491 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005492
John McCall97513962010-01-15 18:39:57 +00005493 TypeSourceInfo *castTInfo;
5494 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5495 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005496 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005497
Nate Begeman5ec4b312009-08-10 23:49:36 +00005498 // If the Expr being casted is a ParenListExpr, handle it specially.
5499 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005500 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005501 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005502
John McCallb268a282010-08-23 23:25:46 +00005503 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005504}
5505
John McCalldadc5752010-08-24 06:29:42 +00005506ExprResult
John McCallebe54742010-01-15 18:56:44 +00005507Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005508 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005509 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005510 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005511 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005512 ExprResult CastResult =
5513 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5514 Kind, VK, BasePath);
5515 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005516 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005517 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005518
John McCallcf142162010-08-07 06:22:56 +00005519 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005520 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005521 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005522 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005523}
5524
Nate Begeman5ec4b312009-08-10 23:49:36 +00005525/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5526/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005527ExprResult
John McCallb268a282010-08-23 23:25:46 +00005528Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005529 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5530 if (!E)
5531 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005532
John McCalldadc5752010-08-24 06:29:42 +00005533 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005534
Nate Begeman5ec4b312009-08-10 23:49:36 +00005535 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005536 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5537 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005538
John McCallb268a282010-08-23 23:25:46 +00005539 if (Result.isInvalid()) return ExprError();
5540
5541 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005542}
5543
John McCalldadc5752010-08-24 06:29:42 +00005544ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005545Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005546 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005547 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005548 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005549 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005550 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005551
Anton Yartsev28ccef72011-03-27 09:32:40 +00005552 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005553 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005554 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5555 if (PE->getNumExprs() == 0) {
5556 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5557 return ExprError();
5558 }
John Thompson781ad172010-06-30 22:55:51 +00005559 if (PE->getNumExprs() == 1) {
5560 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005561 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005562 }
5563 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005564 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005565 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005566
Anton Yartsev28ccef72011-03-27 09:32:40 +00005567 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005568 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005569 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005570 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005571 // '(...)' form of vector initialization in AltiVec: the number of
5572 // initializers must be one or must match the size of the vector.
5573 // If a single value is specified in the initializer then it will be
5574 // replicated to all the components of the vector
5575 if (Ty->getAs<VectorType>()->getVectorKind() ==
5576 VectorType::AltiVecVector) {
5577 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5578 // The number of initializers must be one or must match the size of the
5579 // vector. If a single value is specified in the initializer then it will
5580 // be replicated to all the components of the vector
5581 if (PE->getNumExprs() == 1) {
5582 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005583 ExprResult Literal = Owned(PE->getExpr(0));
5584 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5585 PrepareScalarCast(*this, Literal, ElemTy));
5586 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005587 }
5588 else if (PE->getNumExprs() < numElems) {
5589 Diag(PE->getExprLoc(),
5590 diag::err_incorrect_number_of_vector_initializers);
5591 return ExprError();
5592 }
5593 else
5594 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5595 initExprs.push_back(PE->getExpr(i));
5596 }
5597 else
5598 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5599 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005600
5601 // FIXME: This means that pretty-printing the final AST will produce curly
5602 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005603 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5604 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005605 initExprs.size(), RParenLoc);
5606 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005607 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005608 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005609 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005610 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005611 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005612 if (Result.isInvalid()) return ExprError();
5613 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005614 }
5615}
5616
John McCalldadc5752010-08-24 06:29:42 +00005617ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005618 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005619 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005620 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005621 unsigned nexprs = Val.size();
5622 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005623 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5624 Expr *expr;
5625 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5626 expr = new (Context) ParenExpr(L, R, exprs[0]);
5627 else
5628 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005629 return Owned(expr);
5630}
5631
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005632/// \brief Emit a specialized diagnostic when one expression is a null pointer
5633/// constant and the other is not a pointer.
5634bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5635 SourceLocation QuestionLoc) {
5636 Expr *NullExpr = LHS;
5637 Expr *NonPointerExpr = RHS;
5638 Expr::NullPointerConstantKind NullKind =
5639 NullExpr->isNullPointerConstant(Context,
5640 Expr::NPC_ValueDependentIsNotNull);
5641
5642 if (NullKind == Expr::NPCK_NotNull) {
5643 NullExpr = RHS;
5644 NonPointerExpr = LHS;
5645 NullKind =
5646 NullExpr->isNullPointerConstant(Context,
5647 Expr::NPC_ValueDependentIsNotNull);
5648 }
5649
5650 if (NullKind == Expr::NPCK_NotNull)
5651 return false;
5652
5653 if (NullKind == Expr::NPCK_ZeroInteger) {
5654 // In this case, check to make sure that we got here from a "NULL"
5655 // string in the source code.
5656 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005657 SourceLocation loc = NullExpr->getExprLoc();
5658 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005659 return false;
5660 }
5661
5662 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5663 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5664 << NonPointerExpr->getType() << DiagType
5665 << NonPointerExpr->getSourceRange();
5666 return true;
5667}
5668
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005669/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5670/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005671/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005672QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005673 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005674 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005675
John McCall3aef3d82011-04-10 19:13:55 +00005676 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005677 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005678 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005679
John McCall3aef3d82011-04-10 19:13:55 +00005680 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005681 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005682 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005683
Sebastian Redl1a99f442009-04-16 17:51:27 +00005684 // C++ is sufficiently different to merit its own checker.
5685 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005686 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005687
5688 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005689 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005690
John Wiegley01296292011-04-08 18:41:53 +00005691 Cond = UsualUnaryConversions(Cond.take());
5692 if (Cond.isInvalid())
5693 return QualType();
5694 LHS = UsualUnaryConversions(LHS.take());
5695 if (LHS.isInvalid())
5696 return QualType();
5697 RHS = UsualUnaryConversions(RHS.take());
5698 if (RHS.isInvalid())
5699 return QualType();
5700
5701 QualType CondTy = Cond.get()->getType();
5702 QualType LHSTy = LHS.get()->getType();
5703 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005704
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005705 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005706 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005707 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5708 // Throw an error if its not either.
5709 if (getLangOptions().OpenCL) {
5710 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005711 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005712 diag::err_typecheck_cond_expect_scalar_or_vector)
5713 << CondTy;
5714 return QualType();
5715 }
5716 }
5717 else {
John Wiegley01296292011-04-08 18:41:53 +00005718 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005719 << CondTy;
5720 return QualType();
5721 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005722 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005723
Chris Lattnere2949f42008-01-06 22:42:25 +00005724 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005725 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5726 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005727
Nate Begemanabb5a732010-09-20 22:41:17 +00005728 // OpenCL: If the condition is a vector, and both operands are scalar,
5729 // attempt to implicity convert them to the vector type to act like the
5730 // built in select.
5731 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5732 // Both operands should be of scalar type.
5733 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005734 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005735 << CondTy;
5736 return QualType();
5737 }
5738 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005739 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005740 << CondTy;
5741 return QualType();
5742 }
5743 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005744 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5745 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005746 }
5747
Chris Lattnere2949f42008-01-06 22:42:25 +00005748 // If both operands have arithmetic type, do the usual arithmetic conversions
5749 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005750 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5751 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005752 if (LHS.isInvalid() || RHS.isInvalid())
5753 return QualType();
5754 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005755 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005756
Chris Lattnere2949f42008-01-06 22:42:25 +00005757 // If both operands are the same structure or union type, the result is that
5758 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005759 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5760 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005761 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005762 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005763 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005764 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005765 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005766 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005767
Chris Lattnere2949f42008-01-06 22:42:25 +00005768 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005769 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005770 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5771 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005772 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5773 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005774 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005775 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5776 << LHS.get()->getSourceRange();
5777 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5778 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005779 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005780 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005781 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5782 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005783 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005784 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005785 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005786 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005787 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005788 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005789 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005790 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5791 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005792 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005793 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005794
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005795 // All objective-c pointer type analysis is done here.
5796 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5797 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005798 if (LHS.isInvalid() || RHS.isInvalid())
5799 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005800 if (!compositeType.isNull())
5801 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005802
5803
Steve Naroff05efa972009-07-01 14:36:47 +00005804 // Handle block pointer types.
5805 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5806 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5807 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5808 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005809 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5810 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005811 return destType;
5812 }
5813 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005814 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005815 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005816 }
Steve Naroff05efa972009-07-01 14:36:47 +00005817 // We have 2 block pointer types.
5818 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5819 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005820 return LHSTy;
5821 }
Steve Naroff05efa972009-07-01 14:36:47 +00005822 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005823 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5824 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005825
Steve Naroff05efa972009-07-01 14:36:47 +00005826 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5827 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005828 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005829 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005830 // In this situation, we assume void* type. No especially good
5831 // reason, but this is what gcc does, and we do have to pick
5832 // to get a consistent AST.
5833 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005834 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5835 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005836 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005837 }
Steve Naroff05efa972009-07-01 14:36:47 +00005838 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005839 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5840 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005841 return LHSTy;
5842 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005843
Steve Naroff05efa972009-07-01 14:36:47 +00005844 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5845 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5846 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005847 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5848 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005849
5850 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5851 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5852 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005853 QualType destPointee
5854 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005855 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005856 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005857 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005858 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005859 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005860 return destType;
5861 }
5862 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005863 QualType destPointee
5864 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005865 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005866 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005867 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005868 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005869 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005870 return destType;
5871 }
5872
5873 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5874 // Two identical pointer types are always compatible.
5875 return LHSTy;
5876 }
5877 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5878 rhptee.getUnqualifiedType())) {
5879 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005880 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005881 // In this situation, we assume void* type. No especially good
5882 // reason, but this is what gcc does, and we do have to pick
5883 // to get a consistent AST.
5884 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005885 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5886 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005887 return incompatTy;
5888 }
5889 // The pointer types are compatible.
5890 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5891 // differently qualified versions of compatible types, the result type is
5892 // a pointer to an appropriately qualified version of the *composite*
5893 // type.
5894 // FIXME: Need to calculate the composite type.
5895 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005896 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5897 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005898 return LHSTy;
5899 }
Mike Stump11289f42009-09-09 15:08:12 +00005900
John McCalle84af4e2010-11-13 01:35:44 +00005901 // GCC compatibility: soften pointer/integer mismatch. Note that
5902 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005903 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5904 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005905 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5906 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005907 return RHSTy;
5908 }
5909 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5910 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005911 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5912 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005913 return LHSTy;
5914 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005915
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005916 // Emit a better diagnostic if one of the expressions is a null pointer
5917 // constant and the other is not a pointer type. In this case, the user most
5918 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005919 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005920 return QualType();
5921
Chris Lattnere2949f42008-01-06 22:42:25 +00005922 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005923 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005924 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005925 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005926}
5927
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005928/// FindCompositeObjCPointerType - Helper method to find composite type of
5929/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005930QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005931 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005932 QualType LHSTy = LHS.get()->getType();
5933 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005934
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005935 // Handle things like Class and struct objc_class*. Here we case the result
5936 // to the pseudo-builtin, because that will be implicitly cast back to the
5937 // redefinition type if an attempt is made to access its fields.
5938 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005939 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005940 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005941 return LHSTy;
5942 }
5943 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005944 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005945 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005946 return RHSTy;
5947 }
5948 // And the same for struct objc_object* / id
5949 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005950 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005951 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005952 return LHSTy;
5953 }
5954 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005955 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005956 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005957 return RHSTy;
5958 }
5959 // And the same for struct objc_selector* / SEL
5960 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005961 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005962 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005963 return LHSTy;
5964 }
5965 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005966 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005967 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005968 return RHSTy;
5969 }
5970 // Check constraints for Objective-C object pointers types.
5971 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005972
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005973 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5974 // Two identical object pointer types are always compatible.
5975 return LHSTy;
5976 }
5977 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5978 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5979 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005980
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005981 // If both operands are interfaces and either operand can be
5982 // assigned to the other, use that type as the composite
5983 // type. This allows
5984 // xxx ? (A*) a : (B*) b
5985 // where B is a subclass of A.
5986 //
5987 // Additionally, as for assignment, if either type is 'id'
5988 // allow silent coercion. Finally, if the types are
5989 // incompatible then make sure to use 'id' as the composite
5990 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005991
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005992 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5993 // It could return the composite type.
5994 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5995 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5996 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5997 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5998 } else if ((LHSTy->isObjCQualifiedIdType() ||
5999 RHSTy->isObjCQualifiedIdType()) &&
6000 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6001 // Need to handle "id<xx>" explicitly.
6002 // GCC allows qualified id and any Objective-C type to devolve to
6003 // id. Currently localizing to here until clear this should be
6004 // part of ObjCQualifiedIdTypesAreCompatible.
6005 compositeType = Context.getObjCIdType();
6006 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6007 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006008 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006009 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6010 ;
6011 else {
6012 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6013 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006014 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006015 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006016 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6017 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006018 return incompatTy;
6019 }
6020 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006021 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6022 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006023 return compositeType;
6024 }
6025 // Check Objective-C object pointer types and 'void *'
6026 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6027 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6028 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6029 QualType destPointee
6030 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6031 QualType destType = Context.getPointerType(destPointee);
6032 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006033 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006034 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006035 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006036 return destType;
6037 }
6038 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6039 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6040 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6041 QualType destPointee
6042 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6043 QualType destType = Context.getPointerType(destPointee);
6044 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006045 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006046 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006047 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006048 return destType;
6049 }
6050 return QualType();
6051}
6052
Steve Naroff83895f72007-09-16 03:34:24 +00006053/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006054/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006055ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006056 SourceLocation ColonLoc,
6057 Expr *CondExpr, Expr *LHSExpr,
6058 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006059 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6060 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006061 OpaqueValueExpr *opaqueValue = 0;
6062 Expr *commonExpr = 0;
6063 if (LHSExpr == 0) {
6064 commonExpr = CondExpr;
6065
6066 // We usually want to apply unary conversions *before* saving, except
6067 // in the special case of a C++ l-value conditional.
6068 if (!(getLangOptions().CPlusPlus
6069 && !commonExpr->isTypeDependent()
6070 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6071 && commonExpr->isGLValue()
6072 && commonExpr->isOrdinaryOrBitFieldObject()
6073 && RHSExpr->isOrdinaryOrBitFieldObject()
6074 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006075 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6076 if (commonRes.isInvalid())
6077 return ExprError();
6078 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006079 }
6080
6081 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6082 commonExpr->getType(),
6083 commonExpr->getValueKind(),
6084 commonExpr->getObjectKind());
6085 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006086 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006087
John McCall7decc9e2010-11-18 06:31:45 +00006088 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006089 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006090 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6091 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006092 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006093 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6094 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006095 return ExprError();
6096
John McCallc07a0c72011-02-17 10:25:35 +00006097 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006098 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6099 LHS.take(), ColonLoc,
6100 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006101
6102 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006103 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6104 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006105}
6106
John McCallaba90822011-01-31 23:13:11 +00006107// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006108// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006109// routine is it effectively iqnores the qualifiers on the top level pointee.
6110// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6111// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006112static Sema::AssignConvertType
6113checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6114 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6115 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006116
Steve Naroff1f4d7272007-05-11 04:00:31 +00006117 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006118 const Type *lhptee, *rhptee;
6119 Qualifiers lhq, rhq;
6120 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6121 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006122
John McCallaba90822011-01-31 23:13:11 +00006123 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006124
6125 // C99 6.5.16.1p1: This following citation is common to constraints
6126 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6127 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006128 Qualifiers lq;
6129
6130 if (!lhq.compatiblyIncludes(rhq)) {
6131 // Treat address-space mismatches as fatal. TODO: address subspaces
6132 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6133 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6134
John McCall78535952011-03-26 02:56:45 +00006135 // It's okay to add or remove GC qualifiers when converting to
6136 // and from void*.
6137 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6138 && (lhptee->isVoidType() || rhptee->isVoidType()))
6139 ; // keep old
6140
John McCall4fff8f62011-02-01 00:10:29 +00006141 // For GCC compatibility, other qualifier mismatches are treated
6142 // as still compatible in C.
6143 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6144 }
Steve Naroff3f597292007-05-11 22:18:03 +00006145
Mike Stump4e1f26a2009-02-19 03:04:26 +00006146 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6147 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006148 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006149 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006150 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006151 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006152
Chris Lattner0a788432008-01-03 22:56:36 +00006153 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006154 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006155 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006156 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006157
Chris Lattner0a788432008-01-03 22:56:36 +00006158 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006159 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006160 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006161
6162 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006163 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006164 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006165 }
John McCall4fff8f62011-02-01 00:10:29 +00006166
Mike Stump4e1f26a2009-02-19 03:04:26 +00006167 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006168 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006169 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6170 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006171 // Check if the pointee types are compatible ignoring the sign.
6172 // We explicitly check for char so that we catch "char" vs
6173 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006174 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006175 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006176 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006177 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006178
Chris Lattnerec3a1562009-10-17 20:33:28 +00006179 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006180 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006181 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006182 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006183
John McCall4fff8f62011-02-01 00:10:29 +00006184 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006185 // Types are compatible ignoring the sign. Qualifier incompatibility
6186 // takes priority over sign incompatibility because the sign
6187 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006188 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006189 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006190
John McCallaba90822011-01-31 23:13:11 +00006191 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006192 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006193
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006194 // If we are a multi-level pointer, it's possible that our issue is simply
6195 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6196 // the eventual target type is the same and the pointers have the same
6197 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006198 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006199 do {
John McCall4fff8f62011-02-01 00:10:29 +00006200 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6201 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006202 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006203
John McCall4fff8f62011-02-01 00:10:29 +00006204 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006205 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006206 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006207
Eli Friedman80160bd2009-03-22 23:59:44 +00006208 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006209 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006210 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006211 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006212}
6213
John McCallaba90822011-01-31 23:13:11 +00006214/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006215/// block pointer types are compatible or whether a block and normal pointer
6216/// are compatible. It is more restrict than comparing two function pointer
6217// types.
John McCallaba90822011-01-31 23:13:11 +00006218static Sema::AssignConvertType
6219checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6220 QualType rhsType) {
6221 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6222 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6223
Steve Naroff081c7422008-09-04 15:10:53 +00006224 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006225
Steve Naroff081c7422008-09-04 15:10:53 +00006226 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006227 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6228 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006229
John McCallaba90822011-01-31 23:13:11 +00006230 // In C++, the types have to match exactly.
6231 if (S.getLangOptions().CPlusPlus)
6232 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006233
John McCallaba90822011-01-31 23:13:11 +00006234 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235
Steve Naroff081c7422008-09-04 15:10:53 +00006236 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006237 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6238 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006239
John McCallaba90822011-01-31 23:13:11 +00006240 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6241 return Sema::IncompatibleBlockPointer;
6242
Steve Naroff081c7422008-09-04 15:10:53 +00006243 return ConvTy;
6244}
6245
John McCallaba90822011-01-31 23:13:11 +00006246/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006247/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006248static Sema::AssignConvertType
6249checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6250 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6251 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6252
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006253 if (lhsType->isObjCBuiltinType()) {
6254 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006255 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6256 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006257 return Sema::IncompatiblePointer;
6258 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006259 }
6260 if (rhsType->isObjCBuiltinType()) {
6261 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006262 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6263 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006264 return Sema::IncompatiblePointer;
6265 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006266 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006267 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006268 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006269 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006270 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006271
John McCallaba90822011-01-31 23:13:11 +00006272 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6273 return Sema::CompatiblePointerDiscardsQualifiers;
6274
6275 if (S.Context.typesAreCompatible(lhsType, rhsType))
6276 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006277 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006278 return Sema::IncompatibleObjCQualifiedId;
6279 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006280}
6281
John McCall29600e12010-11-16 02:32:08 +00006282Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006283Sema::CheckAssignmentConstraints(SourceLocation Loc,
6284 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006285 // Fake up an opaque expression. We don't actually care about what
6286 // cast operations are required, so if CheckAssignmentConstraints
6287 // adds casts to this they'll be wasted, but fortunately that doesn't
6288 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006289 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006290 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006291 CastKind K = CK_Invalid;
6292
6293 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6294}
6295
Mike Stump4e1f26a2009-02-19 03:04:26 +00006296/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6297/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006298/// pointers. Here are some objectionable examples that GCC considers warnings:
6299///
6300/// int a, *pint;
6301/// short *pshort;
6302/// struct foo *pfoo;
6303///
6304/// pint = pshort; // warning: assignment from incompatible pointer type
6305/// a = pint; // warning: assignment makes integer from pointer without a cast
6306/// pint = a; // warning: assignment makes pointer from integer without a cast
6307/// pint = pfoo; // warning: assignment from incompatible pointer type
6308///
6309/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006310/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006311///
John McCall8cb679e2010-11-15 09:13:47 +00006312/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006313Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006314Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006315 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006316 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006317
Chris Lattnera52c2f22008-01-04 23:18:45 +00006318 // Get canonical types. We're not formatting these types, just comparing
6319 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006320 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6321 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006322
John McCalle5255932011-01-31 22:28:28 +00006323 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006324 if (lhsType == rhsType) {
6325 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006326 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006327 }
6328
Douglas Gregor6b754842008-10-28 00:22:11 +00006329 // If the left-hand side is a reference type, then we are in a
6330 // (rare!) case where we've allowed the use of references in C,
6331 // e.g., as a parameter type in a built-in function. In this case,
6332 // just make sure that the type referenced is compatible with the
6333 // right-hand side type. The caller is responsible for adjusting
6334 // lhsType so that the resulting expression does not have reference
6335 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006336 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006337 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6338 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006339 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006340 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006341 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006342 }
John McCalle5255932011-01-31 22:28:28 +00006343
Nate Begemanbd956c42009-06-28 02:36:38 +00006344 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6345 // to the same ExtVector type.
6346 if (lhsType->isExtVectorType()) {
6347 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006348 return Incompatible;
6349 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006350 // CK_VectorSplat does T -> vector T, so first cast to the
6351 // element type.
6352 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6353 if (elType != rhsType) {
6354 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006355 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006356 }
6357 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006358 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006359 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006360 }
Mike Stump11289f42009-09-09 15:08:12 +00006361
John McCalle5255932011-01-31 22:28:28 +00006362 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006363 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006364 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006365 // Allow assignments of an AltiVec vector type to an equivalent GCC
6366 // vector type and vice versa
6367 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6368 Kind = CK_BitCast;
6369 return Compatible;
6370 }
6371
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006372 // If we are allowing lax vector conversions, and LHS and RHS are both
6373 // vectors, the total size only needs to be the same. This is a bitcast;
6374 // no bits are changed but the result type is different.
6375 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006376 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006377 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006378 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006379 }
Chris Lattner881a2122008-01-04 23:32:24 +00006380 }
6381 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006382 }
Eli Friedman3360d892008-05-30 18:07:22 +00006383
John McCalle5255932011-01-31 22:28:28 +00006384 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006385 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006386 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006387 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006388 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006389 }
Eli Friedman3360d892008-05-30 18:07:22 +00006390
John McCalle5255932011-01-31 22:28:28 +00006391 // Conversions to normal pointers.
6392 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6393 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006394 if (isa<PointerType>(rhsType)) {
6395 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006396 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006398
John McCalle5255932011-01-31 22:28:28 +00006399 // int -> T*
6400 if (rhsType->isIntegerType()) {
6401 Kind = CK_IntegralToPointer; // FIXME: null?
6402 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006403 }
John McCalle5255932011-01-31 22:28:28 +00006404
6405 // C pointers are not compatible with ObjC object pointers,
6406 // with two exceptions:
6407 if (isa<ObjCObjectPointerType>(rhsType)) {
6408 // - conversions to void*
6409 if (lhsPointer->getPointeeType()->isVoidType()) {
6410 Kind = CK_AnyPointerToObjCPointerCast;
6411 return Compatible;
6412 }
6413
6414 // - conversions from 'Class' to the redefinition type
6415 if (rhsType->isObjCClassType() &&
6416 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006417 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006418 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006419 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006420
John McCalle5255932011-01-31 22:28:28 +00006421 Kind = CK_BitCast;
6422 return IncompatiblePointer;
6423 }
6424
6425 // U^ -> void*
6426 if (rhsType->getAs<BlockPointerType>()) {
6427 if (lhsPointer->getPointeeType()->isVoidType()) {
6428 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006429 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006430 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006431 }
John McCalle5255932011-01-31 22:28:28 +00006432
Steve Naroff081c7422008-09-04 15:10:53 +00006433 return Incompatible;
6434 }
6435
John McCalle5255932011-01-31 22:28:28 +00006436 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006437 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006438 // U^ -> T^
6439 if (rhsType->isBlockPointerType()) {
6440 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006441 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006442 }
6443
6444 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006445 if (rhsType->isIntegerType()) {
6446 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006447 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006448 }
6449
John McCalle5255932011-01-31 22:28:28 +00006450 // id -> T^
6451 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6452 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006453 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006454 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006455
John McCalle5255932011-01-31 22:28:28 +00006456 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006457 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006458 if (RHSPT->getPointeeType()->isVoidType()) {
6459 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006460 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006461 }
John McCall8cb679e2010-11-15 09:13:47 +00006462
Chris Lattnera52c2f22008-01-04 23:18:45 +00006463 return Incompatible;
6464 }
6465
John McCalle5255932011-01-31 22:28:28 +00006466 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006467 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006468 // A* -> B*
6469 if (rhsType->isObjCObjectPointerType()) {
6470 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006471 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006472 }
6473
6474 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006475 if (rhsType->isIntegerType()) {
6476 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006477 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006478 }
6479
John McCalle5255932011-01-31 22:28:28 +00006480 // In general, C pointers are not compatible with ObjC object pointers,
6481 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006482 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006483 // - conversions from 'void*'
6484 if (rhsType->isVoidPointerType()) {
6485 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006486 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006487 }
6488
6489 // - conversions to 'Class' from its redefinition type
6490 if (lhsType->isObjCClassType() &&
6491 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6492 Kind = CK_BitCast;
6493 return Compatible;
6494 }
6495
6496 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006497 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006498 }
John McCalle5255932011-01-31 22:28:28 +00006499
6500 // T^ -> A*
6501 if (rhsType->isBlockPointerType()) {
6502 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006503 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006504 }
6505
Steve Naroff7cae42b2009-07-10 23:34:53 +00006506 return Incompatible;
6507 }
John McCalle5255932011-01-31 22:28:28 +00006508
6509 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006510 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006511 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006512 if (lhsType == Context.BoolTy) {
6513 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006514 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006515 }
Eli Friedman3360d892008-05-30 18:07:22 +00006516
John McCalle5255932011-01-31 22:28:28 +00006517 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006518 if (lhsType->isIntegerType()) {
6519 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006520 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006521 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006522
Chris Lattnera52c2f22008-01-04 23:18:45 +00006523 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006524 }
John McCalle5255932011-01-31 22:28:28 +00006525
6526 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006527 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006528 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006529 if (lhsType == Context.BoolTy) {
6530 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006531 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006532 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006533
John McCalle5255932011-01-31 22:28:28 +00006534 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006535 if (lhsType->isIntegerType()) {
6536 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006537 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006538 }
6539
Steve Naroff7cae42b2009-07-10 23:34:53 +00006540 return Incompatible;
6541 }
Eli Friedman3360d892008-05-30 18:07:22 +00006542
John McCalle5255932011-01-31 22:28:28 +00006543 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006544 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006545 if (Context.typesAreCompatible(lhsType, rhsType)) {
6546 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006547 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006548 }
Bill Wendling216423b2007-05-30 06:30:29 +00006549 }
John McCalle5255932011-01-31 22:28:28 +00006550
Steve Naroff98cf3e92007-06-06 18:38:38 +00006551 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006552}
6553
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006554/// \brief Constructs a transparent union from an expression that is
6555/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006556static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006557 QualType UnionType, FieldDecl *Field) {
6558 // Build an initializer list that designates the appropriate member
6559 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006560 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006561 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006562 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006563 SourceLocation());
6564 Initializer->setType(UnionType);
6565 Initializer->setInitializedFieldInUnion(Field);
6566
6567 // Build a compound literal constructing a value of the transparent
6568 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006569 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006570 EResult = S.Owned(
6571 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6572 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006573}
6574
6575Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006576Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6577 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006578
Mike Stump11289f42009-09-09 15:08:12 +00006579 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006580 // transparent_union GCC extension.
6581 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006582 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006583 return Incompatible;
6584
6585 // The field to initialize within the transparent union.
6586 RecordDecl *UD = UT->getDecl();
6587 FieldDecl *InitField = 0;
6588 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006589 for (RecordDecl::field_iterator it = UD->field_begin(),
6590 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006591 it != itend; ++it) {
6592 if (it->getType()->isPointerType()) {
6593 // If the transparent union contains a pointer type, we allow:
6594 // 1) void pointer
6595 // 2) null pointer constant
6596 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006597 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006598 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006599 InitField = *it;
6600 break;
6601 }
Mike Stump11289f42009-09-09 15:08:12 +00006602
John Wiegley01296292011-04-08 18:41:53 +00006603 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006604 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006605 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006606 InitField = *it;
6607 break;
6608 }
6609 }
6610
John McCall8cb679e2010-11-15 09:13:47 +00006611 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006612 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006613 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006614 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006615 InitField = *it;
6616 break;
6617 }
6618 }
6619
6620 if (!InitField)
6621 return Incompatible;
6622
John Wiegley01296292011-04-08 18:41:53 +00006623 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006624 return Compatible;
6625}
6626
Chris Lattner9bad62c2008-01-04 18:04:52 +00006627Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006628Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006629 if (getLangOptions().CPlusPlus) {
6630 if (!lhsType->isRecordType()) {
6631 // C++ 5.17p3: If the left operand is not of class type, the
6632 // expression is implicitly converted (C++ 4) to the
6633 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006634 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6635 lhsType.getUnqualifiedType(),
6636 AA_Assigning);
6637 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006638 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006639 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006640 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006641 }
6642
6643 // FIXME: Currently, we fall through and treat C++ classes like C
6644 // structures.
John McCall34376a62010-12-04 03:47:34 +00006645 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006646
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006647 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6648 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006649 if ((lhsType->isPointerType() ||
6650 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006651 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006652 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006653 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006654 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006655 return Compatible;
6656 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006657
Chris Lattnere6dcd502007-10-16 02:55:40 +00006658 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006659 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006660 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006661 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006662 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006663 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006664 if (!lhsType->isReferenceType()) {
6665 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6666 if (rExpr.isInvalid())
6667 return Incompatible;
6668 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006669
John McCall8cb679e2010-11-15 09:13:47 +00006670 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006671 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006672 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006673
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006674 // C99 6.5.16.1p2: The value of the right operand is converted to the
6675 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006676 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6677 // so that we can use references in built-in functions even in C.
6678 // The getNonReferenceType() call makes sure that the resulting expression
6679 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006680 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6681 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006682 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006683}
6684
John Wiegley01296292011-04-08 18:41:53 +00006685QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006686 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006687 << lex.get()->getType() << rex.get()->getType()
6688 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006689 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006690}
6691
John Wiegley01296292011-04-08 18:41:53 +00006692QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006693 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006694 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006695 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006696 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006697 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006698 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006699
Nate Begeman191a6b12008-07-14 18:02:46 +00006700 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006701 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006702 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006703
Nate Begeman191a6b12008-07-14 18:02:46 +00006704 // Handle the case of a vector & extvector type of the same size and element
6705 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006706 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006707 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006708 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006709 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006710 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006711 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006712 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006713 return lhsType;
6714 }
6715
John Wiegley01296292011-04-08 18:41:53 +00006716 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006717 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006718 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6719 // If we are allowing lax vector conversions, and LHS and RHS are both
6720 // vectors, the total size only needs to be the same. This is a
6721 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006722 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006723 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006724 }
Eric Christophera613f562010-08-26 00:42:16 +00006725 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006726 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006727 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006728
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006729 // Handle the case of equivalent AltiVec and GCC vector types
6730 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6731 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006732 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006733 return rhsType;
6734 }
6735
Nate Begemanbd956c42009-06-28 02:36:38 +00006736 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6737 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6738 bool swapped = false;
6739 if (rhsType->isExtVectorType()) {
6740 swapped = true;
6741 std::swap(rex, lex);
6742 std::swap(rhsType, lhsType);
6743 }
Mike Stump11289f42009-09-09 15:08:12 +00006744
Nate Begeman886448d2009-06-28 19:12:57 +00006745 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006746 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006747 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006748 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006749 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6750 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006751 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006752 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006753 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006754 if (swapped) std::swap(rex, lex);
6755 return lhsType;
6756 }
6757 }
6758 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6759 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006760 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6761 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006762 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006763 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006764 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006765 if (swapped) std::swap(rex, lex);
6766 return lhsType;
6767 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006768 }
6769 }
Mike Stump11289f42009-09-09 15:08:12 +00006770
Nate Begeman886448d2009-06-28 19:12:57 +00006771 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006772 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006773 << lex.get()->getType() << rex.get()->getType()
6774 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006775 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006776}
6777
Chris Lattnerfaa54172010-01-12 21:23:57 +00006778QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006779 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6780 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006781 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006782
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006783 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006784 if (lex.isInvalid() || rex.isInvalid())
6785 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006786
John Wiegley01296292011-04-08 18:41:53 +00006787 if (!lex.get()->getType()->isArithmeticType() ||
6788 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006789 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006790
Chris Lattnerfaa54172010-01-12 21:23:57 +00006791 // Check for division by zero.
6792 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006793 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6794 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6795 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006796
Chris Lattnerfaa54172010-01-12 21:23:57 +00006797 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006798}
6799
Chris Lattnerfaa54172010-01-12 21:23:57 +00006800QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006801 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6802 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6803 if (lex.get()->getType()->hasIntegerRepresentation() &&
6804 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006805 return CheckVectorOperands(Loc, lex, rex);
6806 return InvalidOperands(Loc, lex, rex);
6807 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006808
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006809 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006810 if (lex.isInvalid() || rex.isInvalid())
6811 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006812
John Wiegley01296292011-04-08 18:41:53 +00006813 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006814 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006815
Chris Lattnerfaa54172010-01-12 21:23:57 +00006816 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006817 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6818 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6819 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006820
Chris Lattnerfaa54172010-01-12 21:23:57 +00006821 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006822}
6823
Chris Lattnerfaa54172010-01-12 21:23:57 +00006824QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006825 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6826 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006827 QualType compType = CheckVectorOperands(Loc, lex, rex);
6828 if (CompLHSTy) *CompLHSTy = compType;
6829 return compType;
6830 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006831
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006832 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006833 if (lex.isInvalid() || rex.isInvalid())
6834 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006835
Steve Naroffe4718892007-04-27 18:30:00 +00006836 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006837 if (lex.get()->getType()->isArithmeticType() &&
6838 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006839 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006840 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006841 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006842
Eli Friedman8e122982008-05-18 18:08:51 +00006843 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006844 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006845 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006846 std::swap(PExp, IExp);
6847
Steve Naroff6b712a72009-07-14 18:25:06 +00006848 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006849
Eli Friedman8e122982008-05-18 18:08:51 +00006850 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006851 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006852
Chris Lattner12bdebb2009-04-24 23:50:08 +00006853 // Check for arithmetic on pointers to incomplete types.
6854 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006855 if (getLangOptions().CPlusPlus) {
6856 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006857 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006858 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006859 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006860
6861 // GNU extension: arithmetic on pointer to void
6862 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006863 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006864 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006865 if (getLangOptions().CPlusPlus) {
6866 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006867 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006868 return QualType();
6869 }
6870
6871 // GNU extension: arithmetic on pointer to function
6872 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006873 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006874 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006875 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006876 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006877 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006878 PExp->getType()->isObjCObjectPointerType()) &&
6879 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006880 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6881 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006882 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006883 return QualType();
6884 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006885 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006886 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006887 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6888 << PointeeTy << PExp->getSourceRange();
6889 return QualType();
6890 }
Mike Stump11289f42009-09-09 15:08:12 +00006891
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006892 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006893 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006894 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006895 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006896 if (LHSTy->isPromotableIntegerType())
6897 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006898 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006899 *CompLHSTy = LHSTy;
6900 }
Eli Friedman8e122982008-05-18 18:08:51 +00006901 return PExp->getType();
6902 }
6903 }
6904
Chris Lattner326f7572008-11-18 01:30:42 +00006905 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006906}
6907
Chris Lattner2a3569b2008-04-07 05:30:13 +00006908// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006909QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006910 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006911 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006912 QualType compType = CheckVectorOperands(Loc, lex, rex);
6913 if (CompLHSTy) *CompLHSTy = compType;
6914 return compType;
6915 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006916
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006917 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006918 if (lex.isInvalid() || rex.isInvalid())
6919 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006920
Chris Lattner4d62f422007-12-09 21:53:25 +00006921 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006922
Chris Lattner4d62f422007-12-09 21:53:25 +00006923 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006924 if (lex.get()->getType()->isArithmeticType() &&
6925 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006926 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006927 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006928 }
Mike Stump11289f42009-09-09 15:08:12 +00006929
Chris Lattner4d62f422007-12-09 21:53:25 +00006930 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006931 if (lex.get()->getType()->isAnyPointerType()) {
6932 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006933
Douglas Gregorac1fb652009-03-24 19:52:54 +00006934 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006935
Douglas Gregorac1fb652009-03-24 19:52:54 +00006936 bool ComplainAboutVoid = false;
6937 Expr *ComplainAboutFunc = 0;
6938 if (lpointee->isVoidType()) {
6939 if (getLangOptions().CPlusPlus) {
6940 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006941 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006942 return QualType();
6943 }
6944
6945 // GNU C extension: arithmetic on pointer to void
6946 ComplainAboutVoid = true;
6947 } else if (lpointee->isFunctionType()) {
6948 if (getLangOptions().CPlusPlus) {
6949 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006950 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006951 return QualType();
6952 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006953
6954 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00006955 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006956 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006957 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006958 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006959 << lex.get()->getSourceRange()
6960 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006961 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006962
Chris Lattner12bdebb2009-04-24 23:50:08 +00006963 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006964 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006965 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006966 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006967 return QualType();
6968 }
Mike Stump11289f42009-09-09 15:08:12 +00006969
Chris Lattner4d62f422007-12-09 21:53:25 +00006970 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006971 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006972 if (ComplainAboutVoid)
6973 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006974 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006975 if (ComplainAboutFunc)
6976 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006977 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006978 << ComplainAboutFunc->getSourceRange();
6979
John Wiegley01296292011-04-08 18:41:53 +00006980 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6981 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006982 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006983
Chris Lattner4d62f422007-12-09 21:53:25 +00006984 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00006985 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006986 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006987
Douglas Gregorac1fb652009-03-24 19:52:54 +00006988 // RHS must be a completely-type object type.
6989 // Handle the GNU void* extension.
6990 if (rpointee->isVoidType()) {
6991 if (getLangOptions().CPlusPlus) {
6992 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006993 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006994 return QualType();
6995 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006996
Douglas Gregorac1fb652009-03-24 19:52:54 +00006997 ComplainAboutVoid = true;
6998 } else if (rpointee->isFunctionType()) {
6999 if (getLangOptions().CPlusPlus) {
7000 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007001 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007002 return QualType();
7003 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007004
7005 // GNU extension: arithmetic on pointer to function
7006 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007007 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007008 } else if (!rpointee->isDependentType() &&
7009 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007010 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007011 << rex.get()->getSourceRange()
7012 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007013 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007014
Eli Friedman168fe152009-05-16 13:54:38 +00007015 if (getLangOptions().CPlusPlus) {
7016 // Pointee types must be the same: C++ [expr.add]
7017 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7018 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007019 << lex.get()->getType() << rex.get()->getType()
7020 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007021 return QualType();
7022 }
7023 } else {
7024 // Pointee types must be compatible C99 6.5.6p3
7025 if (!Context.typesAreCompatible(
7026 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7027 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7028 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007029 << lex.get()->getType() << rex.get()->getType()
7030 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007031 return QualType();
7032 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007033 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007034
Douglas Gregorac1fb652009-03-24 19:52:54 +00007035 if (ComplainAboutVoid)
7036 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007037 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007038 if (ComplainAboutFunc)
7039 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007040 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007041 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007042
John Wiegley01296292011-04-08 18:41:53 +00007043 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007044 return Context.getPointerDiffType();
7045 }
7046 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007047
Chris Lattner326f7572008-11-18 01:30:42 +00007048 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007049}
7050
Douglas Gregor0bf31402010-10-08 23:50:27 +00007051static bool isScopedEnumerationType(QualType T) {
7052 if (const EnumType *ET = dyn_cast<EnumType>(T))
7053 return ET->getDecl()->isScoped();
7054 return false;
7055}
7056
John Wiegley01296292011-04-08 18:41:53 +00007057static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007058 SourceLocation Loc, unsigned Opc,
7059 QualType LHSTy) {
7060 llvm::APSInt Right;
7061 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007062 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007063 return;
7064
7065 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007066 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007067 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007068 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007069 return;
7070 }
7071 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007072 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007073 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007074 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007075 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007076 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007077 return;
7078 }
7079 if (Opc != BO_Shl)
7080 return;
7081
7082 // When left shifting an ICE which is signed, we can check for overflow which
7083 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7084 // integers have defined behavior modulo one more than the maximum value
7085 // representable in the result type, so never warn for those.
7086 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007087 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007088 LHSTy->hasUnsignedIntegerRepresentation())
7089 return;
7090 llvm::APInt ResultBits =
7091 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7092 if (LeftBits.uge(ResultBits))
7093 return;
7094 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7095 Result = Result.shl(Right);
7096
7097 // If we are only missing a sign bit, this is less likely to result in actual
7098 // bugs -- if the result is cast back to an unsigned type, it will have the
7099 // expected value. Thus we place this behind a different warning that can be
7100 // turned off separately if needed.
7101 if (LeftBits == ResultBits - 1) {
7102 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7103 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007104 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007105 return;
7106 }
7107
7108 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7109 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007110 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007111}
7112
Chris Lattner2a3569b2008-04-07 05:30:13 +00007113// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007114QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007115 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007116 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007117 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7118 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007119 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007120
Douglas Gregor0bf31402010-10-08 23:50:27 +00007121 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7122 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007123 if (isScopedEnumerationType(lex.get()->getType()) ||
7124 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007125 return InvalidOperands(Loc, lex, rex);
7126 }
7127
Nate Begemane46ee9a2009-10-25 02:26:48 +00007128 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007129 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007130 return CheckVectorOperands(Loc, lex, rex);
7131
Chris Lattner5c11c412007-12-12 05:47:28 +00007132 // Shifts don't perform usual arithmetic conversions, they just do integer
7133 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007134
John McCall57cdd882010-12-16 19:28:59 +00007135 // For the LHS, do usual unary conversions, but then reset them away
7136 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007137 ExprResult old_lex = lex;
7138 lex = UsualUnaryConversions(lex.take());
7139 if (lex.isInvalid())
7140 return QualType();
7141 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007142 if (isCompAssign) lex = old_lex;
7143
7144 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007145 rex = UsualUnaryConversions(rex.take());
7146 if (rex.isInvalid())
7147 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007148
Ryan Flynnf53fab82009-08-07 16:20:20 +00007149 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007150 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007151
Chris Lattner5c11c412007-12-12 05:47:28 +00007152 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007153 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007154}
7155
Chandler Carruth17773fc2010-07-10 12:30:03 +00007156static bool IsWithinTemplateSpecialization(Decl *D) {
7157 if (DeclContext *DC = D->getDeclContext()) {
7158 if (isa<ClassTemplateSpecializationDecl>(DC))
7159 return true;
7160 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7161 return FD->isFunctionTemplateSpecialization();
7162 }
7163 return false;
7164}
7165
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007166// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007167QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007168 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007169 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007170
Chris Lattner9a152e22009-12-05 05:40:13 +00007171 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007172 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007173 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007174
John Wiegley01296292011-04-08 18:41:53 +00007175 QualType lType = lex.get()->getType();
7176 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007177
John Wiegley01296292011-04-08 18:41:53 +00007178 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7179 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007180 QualType LHSStrippedType = LHSStripped->getType();
7181 QualType RHSStrippedType = RHSStripped->getType();
7182
Douglas Gregor1beec452011-03-12 01:48:56 +00007183
7184
Chandler Carruth712563b2011-02-17 08:37:06 +00007185 // Two different enums will raise a warning when compared.
7186 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7187 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7188 if (LHSEnumType->getDecl()->getIdentifier() &&
7189 RHSEnumType->getDecl()->getIdentifier() &&
7190 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7191 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7192 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007193 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007194 }
7195 }
7196 }
7197
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007198 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007199 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007200 !lex.get()->getLocStart().isMacroID() &&
7201 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007202 // For non-floating point types, check for self-comparisons of the form
7203 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7204 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007205 //
7206 // NOTE: Don't warn about comparison expressions resulting from macro
7207 // expansion. Also don't warn about comparisons which are only self
7208 // comparisons within a template specialization. The warnings should catch
7209 // obvious cases in the definition of the template anyways. The idea is to
7210 // warn when the typed comparison operator will always evaluate to the same
7211 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007212 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007213 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007214 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007215 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007216 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007217 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007218 << (Opc == BO_EQ
7219 || Opc == BO_LE
7220 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007221 } else if (lType->isArrayType() && rType->isArrayType() &&
7222 !DRL->getDecl()->getType()->isReferenceType() &&
7223 !DRR->getDecl()->getType()->isReferenceType()) {
7224 // what is it always going to eval to?
7225 char always_evals_to;
7226 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007227 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007228 always_evals_to = 0; // false
7229 break;
John McCalle3027922010-08-25 11:45:40 +00007230 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007231 always_evals_to = 1; // true
7232 break;
7233 default:
7234 // best we can say is 'a constant'
7235 always_evals_to = 2; // e.g. array1 <= array2
7236 break;
7237 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007238 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007239 << 1 // array
7240 << always_evals_to);
7241 }
7242 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007243 }
Mike Stump11289f42009-09-09 15:08:12 +00007244
Chris Lattner222b8bd2009-03-08 19:39:53 +00007245 if (isa<CastExpr>(LHSStripped))
7246 LHSStripped = LHSStripped->IgnoreParenCasts();
7247 if (isa<CastExpr>(RHSStripped))
7248 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007249
Chris Lattner222b8bd2009-03-08 19:39:53 +00007250 // Warn about comparisons against a string constant (unless the other
7251 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007252 Expr *literalString = 0;
7253 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007254 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007255 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007256 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007257 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007258 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007259 } else if ((isa<StringLiteral>(RHSStripped) ||
7260 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007261 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007262 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007263 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007264 literalStringStripped = RHSStripped;
7265 }
7266
7267 if (literalString) {
7268 std::string resultComparison;
7269 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007270 case BO_LT: resultComparison = ") < 0"; break;
7271 case BO_GT: resultComparison = ") > 0"; break;
7272 case BO_LE: resultComparison = ") <= 0"; break;
7273 case BO_GE: resultComparison = ") >= 0"; break;
7274 case BO_EQ: resultComparison = ") == 0"; break;
7275 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007276 default: assert(false && "Invalid comparison operator");
7277 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007278
Ted Kremenek3427fac2011-02-23 01:52:04 +00007279 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007280 PDiag(diag::warn_stringcompare)
7281 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007282 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007283 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007284 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007285
Douglas Gregorec170db2010-06-08 19:50:34 +00007286 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007287 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007288 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007289 if (lex.isInvalid() || rex.isInvalid())
7290 return QualType();
7291 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007292 else {
John Wiegley01296292011-04-08 18:41:53 +00007293 lex = UsualUnaryConversions(lex.take());
7294 if (lex.isInvalid())
7295 return QualType();
7296
7297 rex = UsualUnaryConversions(rex.take());
7298 if (rex.isInvalid())
7299 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007300 }
7301
John Wiegley01296292011-04-08 18:41:53 +00007302 lType = lex.get()->getType();
7303 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007304
Douglas Gregorca63811b2008-11-19 03:25:36 +00007305 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007306 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007307
Chris Lattnerb620c342007-08-26 01:18:55 +00007308 if (isRelational) {
7309 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007310 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007311 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007312 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007313 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007314 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007315
Chris Lattnerb620c342007-08-26 01:18:55 +00007316 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007317 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007319
John Wiegley01296292011-04-08 18:41:53 +00007320 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007321 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007322 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007323 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007324
Douglas Gregorf267edd2010-06-15 21:38:40 +00007325 // All of the following pointer-related warnings are GCC extensions, except
7326 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007327 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007328 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007329 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007330 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007331 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007332
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007333 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007334 if (LCanPointeeTy == RCanPointeeTy)
7335 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007336 if (!isRelational &&
7337 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7338 // Valid unless comparison between non-null pointer and function pointer
7339 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007340 // In a SFINAE context, we treat this as a hard error to maintain
7341 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007342 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7343 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007344 Diag(Loc,
7345 isSFINAEContext()?
7346 diag::err_typecheck_comparison_of_fptr_to_void
7347 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007348 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007349
7350 if (isSFINAEContext())
7351 return QualType();
7352
John Wiegley01296292011-04-08 18:41:53 +00007353 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007354 return ResultTy;
7355 }
7356 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007357
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007358 // C++ [expr.rel]p2:
7359 // [...] Pointer conversions (4.10) and qualification
7360 // conversions (4.4) are performed on pointer operands (or on
7361 // a pointer operand and a null pointer constant) to bring
7362 // them to their composite pointer type. [...]
7363 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007364 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007365 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007366 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007367 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007368 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007369 if (T.isNull()) {
7370 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007371 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007372 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007373 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007374 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007375 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007376 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007377 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007378 }
7379
John Wiegley01296292011-04-08 18:41:53 +00007380 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7381 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007382 return ResultTy;
7383 }
Eli Friedman16c209612009-08-23 00:27:47 +00007384 // C99 6.5.9p2 and C99 6.5.8p2
7385 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7386 RCanPointeeTy.getUnqualifiedType())) {
7387 // Valid unless a relational comparison of function pointers
7388 if (isRelational && LCanPointeeTy->isFunctionType()) {
7389 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007390 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007391 }
7392 } else if (!isRelational &&
7393 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7394 // Valid unless comparison between non-null pointer and function pointer
7395 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7396 && !LHSIsNull && !RHSIsNull) {
7397 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007398 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007399 }
7400 } else {
7401 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007402 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007403 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007404 }
John McCall7684dde2011-03-11 04:25:25 +00007405 if (LCanPointeeTy != RCanPointeeTy) {
7406 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007407 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007408 else
John Wiegley01296292011-04-08 18:41:53 +00007409 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007410 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007411 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007412 }
Mike Stump11289f42009-09-09 15:08:12 +00007413
Sebastian Redl576fd422009-05-10 18:38:11 +00007414 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007415 // Comparison of nullptr_t with itself.
7416 if (lType->isNullPtrType() && rType->isNullPtrType())
7417 return ResultTy;
7418
Mike Stump11289f42009-09-09 15:08:12 +00007419 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007420 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007421 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007422 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007423 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007424 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007425 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007426 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007427 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007428 return ResultTy;
7429 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007430 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007431 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007432 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007433 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007434 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007435 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007436 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007437 return ResultTy;
7438 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007439
7440 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007441 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007442 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7443 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007444 // In addition, pointers to members can be compared, or a pointer to
7445 // member and a null pointer constant. Pointer to member conversions
7446 // (4.11) and qualification conversions (4.4) are performed to bring
7447 // them to a common type. If one operand is a null pointer constant,
7448 // the common type is the type of the other operand. Otherwise, the
7449 // common type is a pointer to member type similar (4.4) to the type
7450 // of one of the operands, with a cv-qualification signature (4.4)
7451 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007452 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007453 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007454 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007455 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007456 if (T.isNull()) {
7457 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007458 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007459 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007460 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007461 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007462 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007463 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007464 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007465 }
Mike Stump11289f42009-09-09 15:08:12 +00007466
John Wiegley01296292011-04-08 18:41:53 +00007467 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7468 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007469 return ResultTy;
7470 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007471
7472 // Handle scoped enumeration types specifically, since they don't promote
7473 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007474 if (lex.get()->getType()->isEnumeralType() &&
7475 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007476 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007477 }
Mike Stump11289f42009-09-09 15:08:12 +00007478
Steve Naroff081c7422008-09-04 15:10:53 +00007479 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007480 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007481 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7482 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007483
Steve Naroff081c7422008-09-04 15:10:53 +00007484 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007485 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007486 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007487 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007488 }
John Wiegley01296292011-04-08 18:41:53 +00007489 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007490 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007491 }
John Wiegley01296292011-04-08 18:41:53 +00007492
Steve Naroffe18f94c2008-09-28 01:11:11 +00007493 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007494 if (!isRelational
7495 && ((lType->isBlockPointerType() && rType->isPointerType())
7496 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007497 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007498 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007499 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007500 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007501 ->getPointeeType()->isVoidType())))
7502 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007503 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007504 }
John McCall7684dde2011-03-11 04:25:25 +00007505 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007506 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007507 else
John Wiegley01296292011-04-08 18:41:53 +00007508 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007509 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007510 }
Steve Naroff081c7422008-09-04 15:10:53 +00007511
John McCall7684dde2011-03-11 04:25:25 +00007512 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7513 const PointerType *LPT = lType->getAs<PointerType>();
7514 const PointerType *RPT = rType->getAs<PointerType>();
7515 if (LPT || RPT) {
7516 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7517 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007518
Steve Naroff753567f2008-11-17 19:49:16 +00007519 if (!LPtrToVoid && !RPtrToVoid &&
7520 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007521 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007522 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007523 }
John McCall7684dde2011-03-11 04:25:25 +00007524 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007525 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007526 else
John Wiegley01296292011-04-08 18:41:53 +00007527 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007528 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007529 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007530 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007531 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007532 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007533 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007534 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007535 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007536 else
John Wiegley01296292011-04-08 18:41:53 +00007537 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007538 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007539 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007540 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007541 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7542 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007543 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007544 bool isError = false;
7545 if ((LHSIsNull && lType->isIntegerType()) ||
7546 (RHSIsNull && rType->isIntegerType())) {
7547 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007548 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007549 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007550 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007551 else if (getLangOptions().CPlusPlus) {
7552 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7553 isError = true;
7554 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007555 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007556
Chris Lattnerd99bd522009-08-23 00:03:44 +00007557 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007558 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007559 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007560 if (isError)
7561 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007562 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007563
7564 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007565 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007566 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007567 else
John Wiegley01296292011-04-08 18:41:53 +00007568 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007569 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007570 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007571 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007572
Steve Naroff4b191572008-09-04 16:56:14 +00007573 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007574 if (!isRelational && RHSIsNull
7575 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007576 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007577 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007578 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007579 if (!isRelational && LHSIsNull
7580 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007581 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007582 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007583 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007584
Chris Lattner326f7572008-11-18 01:30:42 +00007585 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007586}
7587
Nate Begeman191a6b12008-07-14 18:02:46 +00007588/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007589/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007590/// like a scalar comparison, a vector comparison produces a vector of integer
7591/// types.
John Wiegley01296292011-04-08 18:41:53 +00007592QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007593 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007594 bool isRelational) {
7595 // Check to make sure we're operating on vectors of the same type and width,
7596 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007597 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007598 if (vType.isNull())
7599 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007600
John Wiegley01296292011-04-08 18:41:53 +00007601 QualType lType = lex.get()->getType();
7602 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007603
Anton Yartsev530deb92011-03-27 15:36:07 +00007604 // If AltiVec, the comparison results in a numeric type, i.e.
7605 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007606 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007607 return Context.getLogicalOperationType();
7608
Nate Begeman191a6b12008-07-14 18:02:46 +00007609 // For non-floating point types, check for self-comparisons of the form
7610 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7611 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007612 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007613 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7614 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007615 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007616 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007617 PDiag(diag::warn_comparison_always)
7618 << 0 // self-
7619 << 2 // "a constant"
7620 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007621 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007622
Nate Begeman191a6b12008-07-14 18:02:46 +00007623 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007624 if (!isRelational && lType->hasFloatingRepresentation()) {
7625 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007626 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007627 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007628
Nate Begeman191a6b12008-07-14 18:02:46 +00007629 // Return the type for the comparison, which is the same as vector type for
7630 // integer vectors, or an integer type of identical size and number of
7631 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007632 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007633 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007634
John McCall9dd450b2009-09-21 23:43:11 +00007635 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007636 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007637 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007638 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007639 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007640 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7641
Mike Stump4e1f26a2009-02-19 03:04:26 +00007642 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007643 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007644 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7645}
7646
Steve Naroff218bc2b2007-05-04 21:54:46 +00007647inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007648 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7649 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7650 if (lex.get()->getType()->hasIntegerRepresentation() &&
7651 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007652 return CheckVectorOperands(Loc, lex, rex);
7653
7654 return InvalidOperands(Loc, lex, rex);
7655 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007656
John Wiegley01296292011-04-08 18:41:53 +00007657 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7658 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7659 if (lexResult.isInvalid() || rexResult.isInvalid())
7660 return QualType();
7661 lex = lexResult.take();
7662 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007663
John Wiegley01296292011-04-08 18:41:53 +00007664 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7665 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007666 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007667 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007668}
7669
Steve Naroff218bc2b2007-05-04 21:54:46 +00007670inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007671 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007672
7673 // Diagnose cases where the user write a logical and/or but probably meant a
7674 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7675 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007676 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7677 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007678 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007679 !Loc.isMacroID()) {
7680 // If the RHS can be constant folded, and if it constant folds to something
7681 // that isn't 0 or 1 (which indicate a potential logical operation that
7682 // happened to fold to true/false) then warn.
7683 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007684 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007685 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7686 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007687 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007688 << (Opc == BO_LAnd ? "&&" : "||")
7689 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007690 }
7691 }
Chris Lattner8406c512010-07-13 19:41:32 +00007692
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007693 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007694 lex = UsualUnaryConversions(lex.take());
7695 if (lex.isInvalid())
7696 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007697
John Wiegley01296292011-04-08 18:41:53 +00007698 rex = UsualUnaryConversions(rex.take());
7699 if (rex.isInvalid())
7700 return QualType();
7701
7702 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007703 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007704
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007705 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007706 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007707
John McCall4a2429a2010-06-04 00:29:51 +00007708 // The following is safe because we only use this method for
7709 // non-overloadable operands.
7710
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007711 // C++ [expr.log.and]p1
7712 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007713 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007714 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7715 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007716 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007717 lex = move(lexRes);
7718
7719 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7720 if (rexRes.isInvalid())
7721 return InvalidOperands(Loc, lex, rex);
7722 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007723
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007724 // C++ [expr.log.and]p2
7725 // C++ [expr.log.or]p2
7726 // The result is a bool.
7727 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007728}
7729
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007730/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7731/// is a read-only property; return true if so. A readonly property expression
7732/// depends on various declarations and thus must be treated specially.
7733///
Mike Stump11289f42009-09-09 15:08:12 +00007734static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007735 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7736 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007737 if (PropExpr->isImplicitProperty()) return false;
7738
7739 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7740 QualType BaseType = PropExpr->isSuperReceiver() ?
7741 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007742 PropExpr->getBase()->getType();
7743
John McCallb7bd14f2010-12-02 01:19:52 +00007744 if (const ObjCObjectPointerType *OPT =
7745 BaseType->getAsObjCInterfacePointerType())
7746 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7747 if (S.isPropertyReadonly(PDecl, IFace))
7748 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007749 }
7750 return false;
7751}
7752
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007753static bool IsConstProperty(Expr *E, Sema &S) {
7754 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7755 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7756 if (PropExpr->isImplicitProperty()) return false;
7757
7758 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7759 QualType T = PDecl->getType();
7760 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007761 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007762 CanQualType CT = S.Context.getCanonicalType(T);
7763 return CT.isConstQualified();
7764 }
7765 return false;
7766}
7767
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007768static bool IsReadonlyMessage(Expr *E, Sema &S) {
7769 if (E->getStmtClass() != Expr::MemberExprClass)
7770 return false;
7771 const MemberExpr *ME = cast<MemberExpr>(E);
7772 NamedDecl *Member = ME->getMemberDecl();
7773 if (isa<FieldDecl>(Member)) {
7774 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7775 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7776 return false;
7777 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7778 }
7779 return false;
7780}
7781
Chris Lattner30bd3272008-11-18 01:22:49 +00007782/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7783/// emit an error and return true. If so, return false.
7784static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007785 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007786 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007787 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007788 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7789 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007790 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7791 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007792 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7793 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007794 if (IsLV == Expr::MLV_Valid)
7795 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007796
Chris Lattner30bd3272008-11-18 01:22:49 +00007797 unsigned Diag = 0;
7798 bool NeedType = false;
7799 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007800 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007801 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007802 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7803 NeedType = true;
7804 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007805 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007806 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7807 NeedType = true;
7808 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007809 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007810 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7811 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007812 case Expr::MLV_Valid:
7813 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007814 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007815 case Expr::MLV_MemberFunction:
7816 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007817 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7818 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007819 case Expr::MLV_IncompleteType:
7820 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007821 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007822 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007823 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007824 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007825 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7826 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007827 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007828 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7829 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007830 case Expr::MLV_ReadonlyProperty:
7831 Diag = diag::error_readonly_property_assignment;
7832 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007833 case Expr::MLV_NoSetterProperty:
7834 Diag = diag::error_nosetter_property_assignment;
7835 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007836 case Expr::MLV_InvalidMessageExpression:
7837 Diag = diag::error_readonly_message_assignment;
7838 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007839 case Expr::MLV_SubObjCPropertySetting:
7840 Diag = diag::error_no_subobject_property_setting;
7841 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007842 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007843
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007844 SourceRange Assign;
7845 if (Loc != OrigLoc)
7846 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007847 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007848 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007849 else
Mike Stump11289f42009-09-09 15:08:12 +00007850 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007851 return true;
7852}
7853
7854
7855
7856// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007857QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007858 SourceLocation Loc,
7859 QualType CompoundType) {
7860 // Verify that LHS is a modifiable lvalue, and emit error if not.
7861 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007862 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007863
7864 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007865 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007866 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007867 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007868 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007869 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007870 if (LHS->getObjectKind() == OK_ObjCProperty) {
7871 ExprResult LHSResult = Owned(LHS);
7872 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7873 if (LHSResult.isInvalid())
7874 return QualType();
7875 LHS = LHSResult.take();
7876 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007877 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007878 if (RHS.isInvalid())
7879 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007880 // Special case of NSObject attributes on c-style pointer types.
7881 if (ConvTy == IncompatiblePointer &&
7882 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007883 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007884 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007885 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007886 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007887
John McCall7decc9e2010-11-18 06:31:45 +00007888 if (ConvTy == Compatible &&
7889 getLangOptions().ObjCNonFragileABI &&
7890 LHSType->isObjCObjectType())
7891 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7892 << LHSType;
7893
Chris Lattnerea714382008-08-21 18:04:13 +00007894 // If the RHS is a unary plus or minus, check to see if they = and + are
7895 // right next to each other. If so, the user may have typo'd "x =+ 4"
7896 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007897 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007898 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7899 RHSCheck = ICE->getSubExpr();
7900 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007901 if ((UO->getOpcode() == UO_Plus ||
7902 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007903 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007904 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007905 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7906 // And there is a space or other character before the subexpr of the
7907 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007908 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7909 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007910 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007911 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007912 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007913 }
Chris Lattnerea714382008-08-21 18:04:13 +00007914 }
7915 } else {
7916 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007917 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007918 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007919
Chris Lattner326f7572008-11-18 01:30:42 +00007920 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007921 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007922 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007923
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007924 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00007925 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007926 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007927
Steve Naroff98cf3e92007-06-06 18:38:38 +00007928 // C99 6.5.16p3: The type of an assignment expression is the type of the
7929 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007930 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007931 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7932 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007933 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007934 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007935 return (getLangOptions().CPlusPlus
7936 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007937}
7938
Chris Lattner326f7572008-11-18 01:30:42 +00007939// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007940static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007941 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007942 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007943
John McCall3aef3d82011-04-10 19:13:55 +00007944 LHS = S.CheckPlaceholderExpr(LHS.take());
7945 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007946 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007947 return QualType();
7948
John McCall73d36182010-10-12 07:14:40 +00007949 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7950 // operands, but not unary promotions.
7951 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007952
John McCall34376a62010-12-04 03:47:34 +00007953 // So we treat the LHS as a ignored value, and in C++ we allow the
7954 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007955 LHS = S.IgnoredValueConversions(LHS.take());
7956 if (LHS.isInvalid())
7957 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007958
7959 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007960 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7961 if (RHS.isInvalid())
7962 return QualType();
7963 if (!RHS.get()->getType()->isVoidType())
7964 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007965 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007966
John Wiegley01296292011-04-08 18:41:53 +00007967 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007968}
7969
Steve Naroff7a5af782007-07-13 16:58:59 +00007970/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7971/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007972static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7973 ExprValueKind &VK,
7974 SourceLocation OpLoc,
7975 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007976 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007977 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007978
Chris Lattner6b0cf142008-11-21 07:05:48 +00007979 QualType ResType = Op->getType();
7980 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007981
John McCall4bc41ae2010-11-18 19:01:18 +00007982 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007983 // Decrement of bool is not allowed.
7984 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007985 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007986 return QualType();
7987 }
7988 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007989 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007990 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007991 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007992 } else if (ResType->isAnyPointerType()) {
7993 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007994
Chris Lattner6b0cf142008-11-21 07:05:48 +00007995 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007996 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007997 if (S.getLangOptions().CPlusPlus) {
7998 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007999 << Op->getSourceRange();
8000 return QualType();
8001 }
8002
8003 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008004 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008005 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008006 if (S.getLangOptions().CPlusPlus) {
8007 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008008 << Op->getType() << Op->getSourceRange();
8009 return QualType();
8010 }
8011
John McCall4bc41ae2010-11-18 19:01:18 +00008012 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008013 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008014 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8015 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008016 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008017 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008018 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008019 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008020 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8021 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008022 << PointeeTy << Op->getSourceRange();
8023 return QualType();
8024 }
Eli Friedman090addd2010-01-03 00:20:48 +00008025 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008026 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008027 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008028 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008029 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008030 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008031 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008032 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8033 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008034 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8035 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008036 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008037 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008038 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008039 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008040 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008041 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008042 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008043 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008044 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008045 // In C++, a prefix increment is the same type as the operand. Otherwise
8046 // (in C or with postfix), the increment is the unqualified type of the
8047 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008048 if (isPrefix && S.getLangOptions().CPlusPlus) {
8049 VK = VK_LValue;
8050 return ResType;
8051 } else {
8052 VK = VK_RValue;
8053 return ResType.getUnqualifiedType();
8054 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008055}
8056
John Wiegley01296292011-04-08 18:41:53 +00008057ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008058 assert(E->getValueKind() == VK_LValue &&
8059 E->getObjectKind() == OK_ObjCProperty);
8060 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8061
8062 ExprValueKind VK = VK_RValue;
8063 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008064 if (const ObjCMethodDecl *GetterMethod =
8065 PRE->getImplicitPropertyGetter()) {
8066 QualType Result = GetterMethod->getResultType();
8067 VK = Expr::getValueKindForType(Result);
8068 }
8069 else {
8070 Diag(PRE->getLocation(), diag::err_getter_not_found)
8071 << PRE->getBase()->getType();
8072 }
John McCall34376a62010-12-04 03:47:34 +00008073 }
8074
8075 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8076 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008077
8078 ExprResult Result = MaybeBindToTemporary(E);
8079 if (!Result.isInvalid())
8080 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008081
8082 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008083}
8084
John Wiegley01296292011-04-08 18:41:53 +00008085void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8086 assert(LHS.get()->getValueKind() == VK_LValue &&
8087 LHS.get()->getObjectKind() == OK_ObjCProperty);
8088 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008089
John Wiegley01296292011-04-08 18:41:53 +00008090 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008091 // If using property-dot syntax notation for assignment, and there is a
8092 // setter, RHS expression is being passed to the setter argument. So,
8093 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008094 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008095 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8096 LHSTy = (*P)->getType();
8097
8098 // Otherwise, if the getter returns an l-value, just call that.
8099 } else {
John Wiegley01296292011-04-08 18:41:53 +00008100 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008101 ExprValueKind VK = Expr::getValueKindForType(Result);
8102 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008103 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8104 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008105 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008106 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008107 }
John McCall34376a62010-12-04 03:47:34 +00008108 }
8109
8110 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008111 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008112 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008113 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008114 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008115 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008116 }
8117}
8118
8119
Anders Carlsson806700f2008-02-01 07:15:58 +00008120/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008121/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008122/// where the declaration is needed for type checking. We only need to
8123/// handle cases when the expression references a function designator
8124/// or is an lvalue. Here are some examples:
8125/// - &(x) => x
8126/// - &*****f => f for f a function designator.
8127/// - &s.xx => s
8128/// - &s.zz[1].yy -> s, if zz is an array
8129/// - *(x + 1) -> x, if x is an array
8130/// - &"123"[2] -> 0
8131/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008132static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008133 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008134 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008135 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008136 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008137 // If this is an arrow operator, the address is an offset from
8138 // the base's value, so the object the base refers to is
8139 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008140 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008141 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008142 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008143 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008144 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008145 // FIXME: This code shouldn't be necessary! We should catch the implicit
8146 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008147 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8148 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8149 if (ICE->getSubExpr()->getType()->isArrayType())
8150 return getPrimaryDecl(ICE->getSubExpr());
8151 }
8152 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008153 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008154 case Stmt::UnaryOperatorClass: {
8155 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008156
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008157 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008158 case UO_Real:
8159 case UO_Imag:
8160 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008161 return getPrimaryDecl(UO->getSubExpr());
8162 default:
8163 return 0;
8164 }
8165 }
Steve Naroff47500512007-04-19 23:00:49 +00008166 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008167 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008168 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008169 // If the result of an implicit cast is an l-value, we care about
8170 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008171 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008172 default:
8173 return 0;
8174 }
8175}
8176
8177/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008178/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008179/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008180/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008181/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008182/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008183/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008184static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8185 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008186 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008187 return S.Context.DependentTy;
8188 if (OrigOp->getType() == S.Context.OverloadTy)
8189 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008190 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8191 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008192 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8193 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8194 << OrigOp->getSourceRange();
8195 return QualType();
8196 }
John McCall8d08b9b2010-08-27 09:08:28 +00008197
John McCall2979fe02011-04-12 00:42:48 +00008198 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008199
John McCall8d08b9b2010-08-27 09:08:28 +00008200 // Make sure to ignore parentheses in subsequent checks
8201 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008202
John McCall4bc41ae2010-11-18 19:01:18 +00008203 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008204 // Implement C99-only parts of addressof rules.
8205 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008206 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008207 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8208 // (assuming the deref expression is valid).
8209 return uOp->getSubExpr()->getType();
8210 }
8211 // Technically, there should be a check for array subscript
8212 // expressions here, but the result of one is always an lvalue anyway.
8213 }
John McCallf3a88602011-02-03 08:15:49 +00008214 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008215 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008216
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008217 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008218 bool sfinae = S.isSFINAEContext();
8219 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8220 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008221 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008222 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008223 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008224 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008225 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008226 } else if (lval == Expr::LV_MemberFunction) {
8227 // If it's an instance method, make a member pointer.
8228 // The expression must have exactly the form &A::foo.
8229
8230 // If the underlying expression isn't a decl ref, give up.
8231 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008232 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008233 << OrigOp->getSourceRange();
8234 return QualType();
8235 }
8236 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8237 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8238
8239 // The id-expression was parenthesized.
8240 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008241 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008242 << OrigOp->getSourceRange();
8243
8244 // The method was named without a qualifier.
8245 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008246 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008247 << op->getSourceRange();
8248 }
8249
John McCall4bc41ae2010-11-18 19:01:18 +00008250 return S.Context.getMemberPointerType(op->getType(),
8251 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008252 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008253 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008254 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008255 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008256 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008257 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008258 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008259 return QualType();
8260 }
John McCall086a4642010-11-24 05:12:34 +00008261 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008262 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008263 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008264 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008265 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008266 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008267 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008268 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008269 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008270 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008271 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008272 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008273 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008274 << "property expression" << op->getSourceRange();
8275 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008276 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008277 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008278 // with the register storage-class specifier.
8279 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008280 // in C++ it is not error to take address of a register
8281 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008282 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008283 !S.getLangOptions().CPlusPlus) {
8284 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008285 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008286 return QualType();
8287 }
John McCalld14a8642009-11-21 08:51:07 +00008288 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008289 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008290 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008291 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008292 // Could be a pointer to member, though, if there is an explicit
8293 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008294 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008295 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008296 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008297 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008298 S.Diag(OpLoc,
8299 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008300 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008301 return QualType();
8302 }
Mike Stump11289f42009-09-09 15:08:12 +00008303
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008304 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8305 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008306 return S.Context.getMemberPointerType(op->getType(),
8307 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008308 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008309 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008310 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008311 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008312 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008313
Eli Friedmance7f9002009-05-16 23:27:50 +00008314 if (lval == Expr::LV_IncompleteVoidType) {
8315 // Taking the address of a void variable is technically illegal, but we
8316 // allow it in cases which are otherwise valid.
8317 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008318 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008319 }
8320
Steve Naroff47500512007-04-19 23:00:49 +00008321 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008322 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008323 return S.Context.getObjCObjectPointerType(op->getType());
8324 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008325}
8326
Chris Lattner9156f1b2010-07-05 19:17:26 +00008327/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008328static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8329 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008330 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008331 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008332
John Wiegley01296292011-04-08 18:41:53 +00008333 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8334 if (ConvResult.isInvalid())
8335 return QualType();
8336 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008337 QualType OpTy = Op->getType();
8338 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008339
8340 if (isa<CXXReinterpretCastExpr>(Op)) {
8341 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8342 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8343 Op->getSourceRange());
8344 }
8345
Chris Lattner9156f1b2010-07-05 19:17:26 +00008346 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8347 // is an incomplete type or void. It would be possible to warn about
8348 // dereferencing a void pointer, but it's completely well-defined, and such a
8349 // warning is unlikely to catch any mistakes.
8350 if (const PointerType *PT = OpTy->getAs<PointerType>())
8351 Result = PT->getPointeeType();
8352 else if (const ObjCObjectPointerType *OPT =
8353 OpTy->getAs<ObjCObjectPointerType>())
8354 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008355 else {
John McCall3aef3d82011-04-10 19:13:55 +00008356 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008357 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008358 if (PR.take() != Op)
8359 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008360 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008361
Chris Lattner9156f1b2010-07-05 19:17:26 +00008362 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008363 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008364 << OpTy << Op->getSourceRange();
8365 return QualType();
8366 }
John McCall4bc41ae2010-11-18 19:01:18 +00008367
8368 // Dereferences are usually l-values...
8369 VK = VK_LValue;
8370
8371 // ...except that certain expressions are never l-values in C.
8372 if (!S.getLangOptions().CPlusPlus &&
8373 IsCForbiddenLValueType(S.Context, Result))
8374 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008375
8376 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008377}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008378
John McCalle3027922010-08-25 11:45:40 +00008379static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008380 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008381 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008382 switch (Kind) {
8383 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008384 case tok::periodstar: Opc = BO_PtrMemD; break;
8385 case tok::arrowstar: Opc = BO_PtrMemI; break;
8386 case tok::star: Opc = BO_Mul; break;
8387 case tok::slash: Opc = BO_Div; break;
8388 case tok::percent: Opc = BO_Rem; break;
8389 case tok::plus: Opc = BO_Add; break;
8390 case tok::minus: Opc = BO_Sub; break;
8391 case tok::lessless: Opc = BO_Shl; break;
8392 case tok::greatergreater: Opc = BO_Shr; break;
8393 case tok::lessequal: Opc = BO_LE; break;
8394 case tok::less: Opc = BO_LT; break;
8395 case tok::greaterequal: Opc = BO_GE; break;
8396 case tok::greater: Opc = BO_GT; break;
8397 case tok::exclaimequal: Opc = BO_NE; break;
8398 case tok::equalequal: Opc = BO_EQ; break;
8399 case tok::amp: Opc = BO_And; break;
8400 case tok::caret: Opc = BO_Xor; break;
8401 case tok::pipe: Opc = BO_Or; break;
8402 case tok::ampamp: Opc = BO_LAnd; break;
8403 case tok::pipepipe: Opc = BO_LOr; break;
8404 case tok::equal: Opc = BO_Assign; break;
8405 case tok::starequal: Opc = BO_MulAssign; break;
8406 case tok::slashequal: Opc = BO_DivAssign; break;
8407 case tok::percentequal: Opc = BO_RemAssign; break;
8408 case tok::plusequal: Opc = BO_AddAssign; break;
8409 case tok::minusequal: Opc = BO_SubAssign; break;
8410 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8411 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8412 case tok::ampequal: Opc = BO_AndAssign; break;
8413 case tok::caretequal: Opc = BO_XorAssign; break;
8414 case tok::pipeequal: Opc = BO_OrAssign; break;
8415 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008416 }
8417 return Opc;
8418}
8419
John McCalle3027922010-08-25 11:45:40 +00008420static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008421 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008422 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008423 switch (Kind) {
8424 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008425 case tok::plusplus: Opc = UO_PreInc; break;
8426 case tok::minusminus: Opc = UO_PreDec; break;
8427 case tok::amp: Opc = UO_AddrOf; break;
8428 case tok::star: Opc = UO_Deref; break;
8429 case tok::plus: Opc = UO_Plus; break;
8430 case tok::minus: Opc = UO_Minus; break;
8431 case tok::tilde: Opc = UO_Not; break;
8432 case tok::exclaim: Opc = UO_LNot; break;
8433 case tok::kw___real: Opc = UO_Real; break;
8434 case tok::kw___imag: Opc = UO_Imag; break;
8435 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008436 }
8437 return Opc;
8438}
8439
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008440/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8441/// This warning is only emitted for builtin assignment operations. It is also
8442/// suppressed in the event of macro expansions.
8443static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8444 SourceLocation OpLoc) {
8445 if (!S.ActiveTemplateInstantiations.empty())
8446 return;
8447 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8448 return;
8449 lhs = lhs->IgnoreParenImpCasts();
8450 rhs = rhs->IgnoreParenImpCasts();
8451 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8452 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8453 if (!LeftDeclRef || !RightDeclRef ||
8454 LeftDeclRef->getLocation().isMacroID() ||
8455 RightDeclRef->getLocation().isMacroID())
8456 return;
8457 const ValueDecl *LeftDecl =
8458 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8459 const ValueDecl *RightDecl =
8460 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8461 if (LeftDecl != RightDecl)
8462 return;
8463 if (LeftDecl->getType().isVolatileQualified())
8464 return;
8465 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8466 if (RefTy->getPointeeType().isVolatileQualified())
8467 return;
8468
8469 S.Diag(OpLoc, diag::warn_self_assignment)
8470 << LeftDeclRef->getType()
8471 << lhs->getSourceRange() << rhs->getSourceRange();
8472}
8473
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008474/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8475/// operator @p Opc at location @c TokLoc. This routine only supports
8476/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008477ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008478 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008479 Expr *lhsExpr, Expr *rhsExpr) {
8480 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008481 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008482 // The following two variables are used for compound assignment operators
8483 QualType CompLHSTy; // Type of LHS after promotions for computation
8484 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008485 ExprValueKind VK = VK_RValue;
8486 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008487
Douglas Gregor1beec452011-03-12 01:48:56 +00008488 // Check if a 'foo<int>' involved in a binary op, identifies a single
8489 // function unambiguously (i.e. an lvalue ala 13.4)
8490 // But since an assignment can trigger target based overload, exclude it in
8491 // our blind search. i.e:
8492 // template<class T> void f(); template<class T, class U> void f(U);
8493 // f<int> == 0; // resolve f<int> blindly
8494 // void (*p)(int); p = f<int>; // resolve f<int> using target
8495 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008496 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008497 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008498 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008499
John McCall3aef3d82011-04-10 19:13:55 +00008500 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008501 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008502 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008503 }
8504
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008505 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008506 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008507 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008508 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008509 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8510 VK = lhs.get()->getValueKind();
8511 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008512 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008513 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008514 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008515 break;
John McCalle3027922010-08-25 11:45:40 +00008516 case BO_PtrMemD:
8517 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008518 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008519 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008520 break;
John McCalle3027922010-08-25 11:45:40 +00008521 case BO_Mul:
8522 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008523 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008524 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008525 break;
John McCalle3027922010-08-25 11:45:40 +00008526 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008527 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8528 break;
John McCalle3027922010-08-25 11:45:40 +00008529 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008530 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8531 break;
John McCalle3027922010-08-25 11:45:40 +00008532 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008533 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8534 break;
John McCalle3027922010-08-25 11:45:40 +00008535 case BO_Shl:
8536 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008537 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008538 break;
John McCalle3027922010-08-25 11:45:40 +00008539 case BO_LE:
8540 case BO_LT:
8541 case BO_GE:
8542 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008543 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008544 break;
John McCalle3027922010-08-25 11:45:40 +00008545 case BO_EQ:
8546 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008547 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008548 break;
John McCalle3027922010-08-25 11:45:40 +00008549 case BO_And:
8550 case BO_Xor:
8551 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008552 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8553 break;
John McCalle3027922010-08-25 11:45:40 +00008554 case BO_LAnd:
8555 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008556 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008557 break;
John McCalle3027922010-08-25 11:45:40 +00008558 case BO_MulAssign:
8559 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008560 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008561 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008562 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008563 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8564 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008565 break;
John McCalle3027922010-08-25 11:45:40 +00008566 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008567 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8568 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008569 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8570 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008571 break;
John McCalle3027922010-08-25 11:45:40 +00008572 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008573 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008574 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8575 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008576 break;
John McCalle3027922010-08-25 11:45:40 +00008577 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008578 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008579 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8580 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008581 break;
John McCalle3027922010-08-25 11:45:40 +00008582 case BO_ShlAssign:
8583 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008584 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008585 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008586 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8587 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008588 break;
John McCalle3027922010-08-25 11:45:40 +00008589 case BO_AndAssign:
8590 case BO_XorAssign:
8591 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008592 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8593 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008594 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8595 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008596 break;
John McCalle3027922010-08-25 11:45:40 +00008597 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008598 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008599 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8600 VK = rhs.get()->getValueKind();
8601 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008602 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008603 break;
8604 }
John Wiegley01296292011-04-08 18:41:53 +00008605 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008606 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008607 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008608 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8609 ResultTy, VK, OK, OpLoc));
8610 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008611 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008612 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008613 }
John Wiegley01296292011-04-08 18:41:53 +00008614 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8615 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008616 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008617}
8618
Sebastian Redl44615072009-10-27 12:10:02 +00008619/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8620/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008621static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8622 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008623 const PartialDiagnostic &FirstNote,
8624 SourceRange FirstParenRange,
8625 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008626 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008627 Self.Diag(Loc, PD);
8628
8629 if (!FirstNote.getDiagID())
8630 return;
8631
8632 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8633 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8634 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008635 return;
8636 }
8637
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008638 Self.Diag(Loc, FirstNote)
8639 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008640 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008641
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008642 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008643 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008644
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008645 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8646 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8647 // We can't display the parentheses, so just dig the
8648 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008649 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008650 return;
8651 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008652
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008653 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008654 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8655 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008656}
8657
Sebastian Redl44615072009-10-27 12:10:02 +00008658/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8659/// operators are mixed in a way that suggests that the programmer forgot that
8660/// comparison operators have higher precedence. The most typical example of
8661/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008662static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008663 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008664 typedef BinaryOperator BinOp;
8665 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8666 rhsopc = static_cast<BinOp::Opcode>(-1);
8667 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008668 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008669 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008670 rhsopc = BO->getOpcode();
8671
8672 // Subs are not binary operators.
8673 if (lhsopc == -1 && rhsopc == -1)
8674 return;
8675
8676 // Bitwise operations are sometimes used as eager logical ops.
8677 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008678 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8679 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008680 return;
8681
Sebastian Redl44615072009-10-27 12:10:02 +00008682 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008683 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008684 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008685 << SourceRange(lhs->getLocStart(), OpLoc)
8686 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008687 Self.PDiag(diag::note_precedence_bitwise_silence)
8688 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008689 lhs->getSourceRange(),
8690 Self.PDiag(diag::note_precedence_bitwise_first)
8691 << BinOp::getOpcodeStr(Opc),
8692 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redl44615072009-10-27 12:10:02 +00008693 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008694 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008695 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008696 << SourceRange(OpLoc, rhs->getLocEnd())
8697 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008698 Self.PDiag(diag::note_precedence_bitwise_silence)
8699 << BinOp::getOpcodeStr(rhsopc),
8700 rhs->getSourceRange(),
Douglas Gregor89336232010-03-29 23:34:08 +00008701 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008702 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008703 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00008704}
8705
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008706/// \brief It accepts a '&&' expr that is inside a '||' one.
8707/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8708/// in parentheses.
8709static void
8710EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008711 BinaryOperator *Bop) {
8712 assert(Bop->getOpcode() == BO_LAnd);
8713 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008714 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008715 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008716 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008717 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008718 Self.PDiag(0), SourceRange());
8719}
8720
8721/// \brief Returns true if the given expression can be evaluated as a constant
8722/// 'true'.
8723static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8724 bool Res;
8725 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8726}
8727
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008728/// \brief Returns true if the given expression can be evaluated as a constant
8729/// 'false'.
8730static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8731 bool Res;
8732 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8733}
8734
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008735/// \brief Look for '&&' in the left hand of a '||' expr.
8736static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008737 Expr *OrLHS, Expr *OrRHS) {
8738 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008739 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008740 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8741 if (EvaluatesAsFalse(S, OrRHS))
8742 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008743 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8744 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8745 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8746 } else if (Bop->getOpcode() == BO_LOr) {
8747 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8748 // If it's "a || b && 1 || c" we didn't warn earlier for
8749 // "a || b && 1", but warn now.
8750 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8751 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8752 }
8753 }
8754 }
8755}
8756
8757/// \brief Look for '&&' in the right hand of a '||' expr.
8758static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008759 Expr *OrLHS, Expr *OrRHS) {
8760 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008761 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008762 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8763 if (EvaluatesAsFalse(S, OrLHS))
8764 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008765 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8766 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8767 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008768 }
8769 }
8770}
8771
Sebastian Redl43028242009-10-26 15:24:15 +00008772/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008773/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008774static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008775 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008776 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008777 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008778 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8779
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008780 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8781 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008782 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008783 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8784 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008785 }
Sebastian Redl43028242009-10-26 15:24:15 +00008786}
8787
Steve Naroff218bc2b2007-05-04 21:54:46 +00008788// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008789ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008790 tok::TokenKind Kind,
8791 Expr *lhs, Expr *rhs) {
8792 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008793 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8794 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008795
Sebastian Redl43028242009-10-26 15:24:15 +00008796 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8797 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8798
Douglas Gregor5287f092009-11-05 00:51:44 +00008799 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8800}
8801
John McCalldadc5752010-08-24 06:29:42 +00008802ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008803 BinaryOperatorKind Opc,
8804 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008805 if (getLangOptions().CPlusPlus) {
8806 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008807
John McCall622114c2010-12-06 05:26:58 +00008808 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8809 UseBuiltinOperator = false;
8810 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8811 UseBuiltinOperator = true;
8812 } else {
8813 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8814 !rhs->getType()->isOverloadableType();
8815 }
8816
8817 if (!UseBuiltinOperator) {
8818 // Find all of the overloaded operators visible from this
8819 // point. We perform both an operator-name lookup from the local
8820 // scope and an argument-dependent lookup based on the types of
8821 // the arguments.
8822 UnresolvedSet<16> Functions;
8823 OverloadedOperatorKind OverOp
8824 = BinaryOperator::getOverloadedOperator(Opc);
8825 if (S && OverOp != OO_None)
8826 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8827 Functions);
8828
8829 // Build the (potentially-overloaded, potentially-dependent)
8830 // binary operation.
8831 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8832 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008833 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008834
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008835 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008836 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008837}
8838
John McCalldadc5752010-08-24 06:29:42 +00008839ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008840 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008841 Expr *InputExpr) {
8842 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008843 ExprValueKind VK = VK_RValue;
8844 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008845 QualType resultType;
8846 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008847 case UO_PreInc:
8848 case UO_PreDec:
8849 case UO_PostInc:
8850 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008851 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008852 Opc == UO_PreInc ||
8853 Opc == UO_PostInc,
8854 Opc == UO_PreInc ||
8855 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008856 break;
John McCalle3027922010-08-25 11:45:40 +00008857 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008858 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008859 break;
John McCall31996342011-04-07 08:22:57 +00008860 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008861 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008862 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008863 Input = move(resolved);
8864 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8865 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008866 break;
John McCall31996342011-04-07 08:22:57 +00008867 }
John McCalle3027922010-08-25 11:45:40 +00008868 case UO_Plus:
8869 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008870 Input = UsualUnaryConversions(Input.take());
8871 if (Input.isInvalid()) return ExprError();
8872 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008873 if (resultType->isDependentType())
8874 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008875 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8876 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008877 break;
8878 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8879 resultType->isEnumeralType())
8880 break;
8881 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008882 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008883 resultType->isPointerType())
8884 break;
John McCall36226622010-10-12 02:09:17 +00008885 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008886 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008887 if (Input.isInvalid()) return ExprError();
8888 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008889 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008890
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008892 << resultType << Input.get()->getSourceRange());
8893
John McCalle3027922010-08-25 11:45:40 +00008894 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008895 Input = UsualUnaryConversions(Input.take());
8896 if (Input.isInvalid()) return ExprError();
8897 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008898 if (resultType->isDependentType())
8899 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008900 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8901 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8902 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008903 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008904 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008905 else if (resultType->hasIntegerRepresentation())
8906 break;
8907 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008908 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008909 if (Input.isInvalid()) return ExprError();
8910 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008911 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008912 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008913 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008914 }
Steve Naroff35d85152007-05-07 00:24:15 +00008915 break;
John Wiegley01296292011-04-08 18:41:53 +00008916
John McCalle3027922010-08-25 11:45:40 +00008917 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008918 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008919 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8920 if (Input.isInvalid()) return ExprError();
8921 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008922 if (resultType->isDependentType())
8923 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008924 if (resultType->isScalarType()) {
8925 // C99 6.5.3.3p1: ok, fallthrough;
8926 if (Context.getLangOptions().CPlusPlus) {
8927 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8928 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008929 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8930 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008931 }
John McCall36226622010-10-12 02:09:17 +00008932 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008933 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008934 if (Input.isInvalid()) return ExprError();
8935 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008936 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008937 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008938 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008939 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008940
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008941 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008942 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008943 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008944 break;
John McCalle3027922010-08-25 11:45:40 +00008945 case UO_Real:
8946 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008947 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008948 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008949 if (Input.isInvalid()) return ExprError();
8950 if (Input.get()->getValueKind() != VK_RValue &&
8951 Input.get()->getObjectKind() == OK_Ordinary)
8952 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008953 break;
John McCalle3027922010-08-25 11:45:40 +00008954 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008955 resultType = Input.get()->getType();
8956 VK = Input.get()->getValueKind();
8957 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008958 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008959 }
John Wiegley01296292011-04-08 18:41:53 +00008960 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008961 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008962
John Wiegley01296292011-04-08 18:41:53 +00008963 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008964 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008965}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008966
John McCalldadc5752010-08-24 06:29:42 +00008967ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008968 UnaryOperatorKind Opc,
8969 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008970 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008971 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008972 // Find all of the overloaded operators visible from this
8973 // point. We perform both an operator-name lookup from the local
8974 // scope and an argument-dependent lookup based on the types of
8975 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008976 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008977 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008978 if (S && OverOp != OO_None)
8979 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8980 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008981
John McCallb268a282010-08-23 23:25:46 +00008982 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008984
John McCallb268a282010-08-23 23:25:46 +00008985 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008986}
8987
Douglas Gregor5287f092009-11-05 00:51:44 +00008988// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008989ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008990 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008991 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008992}
8993
Steve Naroff66356bd2007-09-16 14:56:35 +00008994/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008995ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008996 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008997 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008998 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008999 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009000 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009001}
9002
John McCalldadc5752010-08-24 06:29:42 +00009003ExprResult
John McCallb268a282010-08-23 23:25:46 +00009004Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009005 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009006 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9007 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9008
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009009 bool isFileScope
9010 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009011 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009012 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009013
Chris Lattner366727f2007-07-24 16:58:17 +00009014 // FIXME: there are a variety of strange constraints to enforce here, for
9015 // example, it is not possible to goto into a stmt expression apparently.
9016 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009017
Chris Lattner366727f2007-07-24 16:58:17 +00009018 // If there are sub stmts in the compound stmt, take the type of the last one
9019 // as the type of the stmtexpr.
9020 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009021 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009022 if (!Compound->body_empty()) {
9023 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009024 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009025 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009026 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9027 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009028 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009029 }
John Wiegley01296292011-04-08 18:41:53 +00009030 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009031 // Do function/array conversion on the last expression, but not
9032 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009033 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9034 if (LastExpr.isInvalid())
9035 return ExprError();
9036 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009037
John Wiegley01296292011-04-08 18:41:53 +00009038 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9039 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009040 InitializedEntity::InitializeResult(LPLoc,
9041 Ty,
9042 false),
9043 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00009044 LastExpr);
9045 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009046 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009047 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009048 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009049 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009050 else
John Wiegley01296292011-04-08 18:41:53 +00009051 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009052 StmtExprMayBindToTemp = true;
9053 }
9054 }
9055 }
Chris Lattner944d3062008-07-26 19:51:01 +00009056 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009057
Eli Friedmanba961a92009-03-23 00:24:07 +00009058 // FIXME: Check that expression type is complete/non-abstract; statement
9059 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009060 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9061 if (StmtExprMayBindToTemp)
9062 return MaybeBindToTemporary(ResStmtExpr);
9063 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009064}
Steve Naroff78864672007-08-01 22:05:33 +00009065
John McCalldadc5752010-08-24 06:29:42 +00009066ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009067 TypeSourceInfo *TInfo,
9068 OffsetOfComponent *CompPtr,
9069 unsigned NumComponents,
9070 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009071 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009072 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009073 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009074
Chris Lattnerf17bd422007-08-30 17:45:32 +00009075 // We must have at least one component that refers to the type, and the first
9076 // one is known to be a field designator. Verify that the ArgTy represents
9077 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009078 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009079 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9080 << ArgTy << TypeRange);
9081
9082 // Type must be complete per C99 7.17p3 because a declaring a variable
9083 // with an incomplete type would be ill-formed.
9084 if (!Dependent
9085 && RequireCompleteType(BuiltinLoc, ArgTy,
9086 PDiag(diag::err_offsetof_incomplete_type)
9087 << TypeRange))
9088 return ExprError();
9089
Chris Lattner78502cf2007-08-31 21:49:13 +00009090 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9091 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009092 // FIXME: This diagnostic isn't actually visible because the location is in
9093 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009094 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009095 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9096 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009097
9098 bool DidWarnAboutNonPOD = false;
9099 QualType CurrentType = ArgTy;
9100 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9101 llvm::SmallVector<OffsetOfNode, 4> Comps;
9102 llvm::SmallVector<Expr*, 4> Exprs;
9103 for (unsigned i = 0; i != NumComponents; ++i) {
9104 const OffsetOfComponent &OC = CompPtr[i];
9105 if (OC.isBrackets) {
9106 // Offset of an array sub-field. TODO: Should we allow vector elements?
9107 if (!CurrentType->isDependentType()) {
9108 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9109 if(!AT)
9110 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9111 << CurrentType);
9112 CurrentType = AT->getElementType();
9113 } else
9114 CurrentType = Context.DependentTy;
9115
9116 // The expression must be an integral expression.
9117 // FIXME: An integral constant expression?
9118 Expr *Idx = static_cast<Expr*>(OC.U.E);
9119 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9120 !Idx->getType()->isIntegerType())
9121 return ExprError(Diag(Idx->getLocStart(),
9122 diag::err_typecheck_subscript_not_integer)
9123 << Idx->getSourceRange());
9124
9125 // Record this array index.
9126 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9127 Exprs.push_back(Idx);
9128 continue;
9129 }
9130
9131 // Offset of a field.
9132 if (CurrentType->isDependentType()) {
9133 // We have the offset of a field, but we can't look into the dependent
9134 // type. Just record the identifier of the field.
9135 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9136 CurrentType = Context.DependentTy;
9137 continue;
9138 }
9139
9140 // We need to have a complete type to look into.
9141 if (RequireCompleteType(OC.LocStart, CurrentType,
9142 diag::err_offsetof_incomplete_type))
9143 return ExprError();
9144
9145 // Look for the designated field.
9146 const RecordType *RC = CurrentType->getAs<RecordType>();
9147 if (!RC)
9148 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9149 << CurrentType);
9150 RecordDecl *RD = RC->getDecl();
9151
9152 // C++ [lib.support.types]p5:
9153 // The macro offsetof accepts a restricted set of type arguments in this
9154 // International Standard. type shall be a POD structure or a POD union
9155 // (clause 9).
9156 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9157 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009158 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009159 PDiag(diag::warn_offsetof_non_pod_type)
9160 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9161 << CurrentType))
9162 DidWarnAboutNonPOD = true;
9163 }
9164
9165 // Look for the field.
9166 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9167 LookupQualifiedName(R, RD);
9168 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009169 IndirectFieldDecl *IndirectMemberDecl = 0;
9170 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009171 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009172 MemberDecl = IndirectMemberDecl->getAnonField();
9173 }
9174
Douglas Gregor882211c2010-04-28 22:16:22 +00009175 if (!MemberDecl)
9176 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9177 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9178 OC.LocEnd));
9179
Douglas Gregor10982ea2010-04-28 22:36:06 +00009180 // C99 7.17p3:
9181 // (If the specified member is a bit-field, the behavior is undefined.)
9182 //
9183 // We diagnose this as an error.
9184 if (MemberDecl->getBitWidth()) {
9185 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9186 << MemberDecl->getDeclName()
9187 << SourceRange(BuiltinLoc, RParenLoc);
9188 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9189 return ExprError();
9190 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009191
9192 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009193 if (IndirectMemberDecl)
9194 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009195
Douglas Gregord1702062010-04-29 00:18:15 +00009196 // If the member was found in a base class, introduce OffsetOfNodes for
9197 // the base class indirections.
9198 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9199 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009200 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009201 CXXBasePath &Path = Paths.front();
9202 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9203 B != BEnd; ++B)
9204 Comps.push_back(OffsetOfNode(B->Base));
9205 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009206
Francois Pichet783dd6e2010-11-21 06:08:52 +00009207 if (IndirectMemberDecl) {
9208 for (IndirectFieldDecl::chain_iterator FI =
9209 IndirectMemberDecl->chain_begin(),
9210 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9211 assert(isa<FieldDecl>(*FI));
9212 Comps.push_back(OffsetOfNode(OC.LocStart,
9213 cast<FieldDecl>(*FI), OC.LocEnd));
9214 }
9215 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009216 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009217
Douglas Gregor882211c2010-04-28 22:16:22 +00009218 CurrentType = MemberDecl->getType().getNonReferenceType();
9219 }
9220
9221 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9222 TInfo, Comps.data(), Comps.size(),
9223 Exprs.data(), Exprs.size(), RParenLoc));
9224}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009225
John McCalldadc5752010-08-24 06:29:42 +00009226ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009227 SourceLocation BuiltinLoc,
9228 SourceLocation TypeLoc,
9229 ParsedType argty,
9230 OffsetOfComponent *CompPtr,
9231 unsigned NumComponents,
9232 SourceLocation RPLoc) {
9233
Douglas Gregor882211c2010-04-28 22:16:22 +00009234 TypeSourceInfo *ArgTInfo;
9235 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9236 if (ArgTy.isNull())
9237 return ExprError();
9238
Eli Friedman06dcfd92010-08-05 10:15:45 +00009239 if (!ArgTInfo)
9240 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9241
9242 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9243 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009244}
9245
9246
John McCalldadc5752010-08-24 06:29:42 +00009247ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009248 Expr *CondExpr,
9249 Expr *LHSExpr, Expr *RHSExpr,
9250 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009251 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9252
John McCall7decc9e2010-11-18 06:31:45 +00009253 ExprValueKind VK = VK_RValue;
9254 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009255 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009256 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009257 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009258 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009259 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009260 } else {
9261 // The conditional expression is required to be a constant expression.
9262 llvm::APSInt condEval(32);
9263 SourceLocation ExpLoc;
9264 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009265 return ExprError(Diag(ExpLoc,
9266 diag::err_typecheck_choose_expr_requires_constant)
9267 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009268
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009269 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009270 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9271
9272 resType = ActiveExpr->getType();
9273 ValueDependent = ActiveExpr->isValueDependent();
9274 VK = ActiveExpr->getValueKind();
9275 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009276 }
9277
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009278 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009279 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009280 resType->isDependentType(),
9281 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009282}
9283
Steve Naroffc540d662008-09-03 18:15:37 +00009284//===----------------------------------------------------------------------===//
9285// Clang Extensions.
9286//===----------------------------------------------------------------------===//
9287
9288/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009289void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009290 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9291 PushBlockScope(BlockScope, Block);
9292 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009293 if (BlockScope)
9294 PushDeclContext(BlockScope, Block);
9295 else
9296 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009297}
9298
Mike Stump82f071f2009-02-04 22:31:32 +00009299void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009300 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009301 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009302 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009303
John McCall8cb7bdf2010-06-04 23:28:52 +00009304 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009305 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009306
John McCall3882ace2011-01-05 12:14:39 +00009307 // GetTypeForDeclarator always produces a function type for a block
9308 // literal signature. Furthermore, it is always a FunctionProtoType
9309 // unless the function was written with a typedef.
9310 assert(T->isFunctionType() &&
9311 "GetTypeForDeclarator made a non-function block signature");
9312
9313 // Look for an explicit signature in that function type.
9314 FunctionProtoTypeLoc ExplicitSignature;
9315
9316 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9317 if (isa<FunctionProtoTypeLoc>(tmp)) {
9318 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9319
9320 // Check whether that explicit signature was synthesized by
9321 // GetTypeForDeclarator. If so, don't save that as part of the
9322 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009323 if (ExplicitSignature.getLocalRangeBegin() ==
9324 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009325 // This would be much cheaper if we stored TypeLocs instead of
9326 // TypeSourceInfos.
9327 TypeLoc Result = ExplicitSignature.getResultLoc();
9328 unsigned Size = Result.getFullDataSize();
9329 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9330 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9331
9332 ExplicitSignature = FunctionProtoTypeLoc();
9333 }
John McCalla3ccba02010-06-04 11:21:44 +00009334 }
Mike Stump11289f42009-09-09 15:08:12 +00009335
John McCall3882ace2011-01-05 12:14:39 +00009336 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9337 CurBlock->FunctionType = T;
9338
9339 const FunctionType *Fn = T->getAs<FunctionType>();
9340 QualType RetTy = Fn->getResultType();
9341 bool isVariadic =
9342 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9343
John McCall8e346702010-06-04 19:02:56 +00009344 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009345
John McCalla3ccba02010-06-04 11:21:44 +00009346 // Don't allow returning a objc interface by value.
9347 if (RetTy->isObjCObjectType()) {
9348 Diag(ParamInfo.getSourceRange().getBegin(),
9349 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9350 return;
9351 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009352
John McCalla3ccba02010-06-04 11:21:44 +00009353 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009354 // return type. TODO: what should we do with declarators like:
9355 // ^ * { ... }
9356 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009357 if (RetTy != Context.DependentTy)
9358 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009359
John McCalla3ccba02010-06-04 11:21:44 +00009360 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009361 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009362 if (ExplicitSignature) {
9363 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9364 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009365 if (Param->getIdentifier() == 0 &&
9366 !Param->isImplicit() &&
9367 !Param->isInvalidDecl() &&
9368 !getLangOptions().CPlusPlus)
9369 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009370 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009371 }
John McCalla3ccba02010-06-04 11:21:44 +00009372
9373 // Fake up parameter variables if we have a typedef, like
9374 // ^ fntype { ... }
9375 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9376 for (FunctionProtoType::arg_type_iterator
9377 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9378 ParmVarDecl *Param =
9379 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9380 ParamInfo.getSourceRange().getBegin(),
9381 *I);
John McCall8e346702010-06-04 19:02:56 +00009382 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009383 }
Steve Naroffc540d662008-09-03 18:15:37 +00009384 }
John McCalla3ccba02010-06-04 11:21:44 +00009385
John McCall8e346702010-06-04 19:02:56 +00009386 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009387 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009388 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009389 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9390 CurBlock->TheDecl->param_end(),
9391 /*CheckParameterNames=*/false);
9392 }
9393
John McCalla3ccba02010-06-04 11:21:44 +00009394 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009395 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009396
John McCall8e346702010-06-04 19:02:56 +00009397 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009398 Diag(ParamInfo.getAttributes()->getLoc(),
9399 diag::warn_attribute_sentinel_not_variadic) << 1;
9400 // FIXME: remove the attribute.
9401 }
9402
9403 // Put the parameter variables in scope. We can bail out immediately
9404 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009405 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009406 return;
9407
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009408 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009409 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9410 (*AI)->setOwningFunction(CurBlock->TheDecl);
9411
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009412 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009413 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009414 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009415
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009416 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009417 }
John McCallf7b2fb52010-01-22 00:28:27 +00009418 }
Steve Naroffc540d662008-09-03 18:15:37 +00009419}
9420
9421/// ActOnBlockError - If there is an error parsing a block, this callback
9422/// is invoked to pop the information about the block from the action impl.
9423void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009424 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009425 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009426 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009427}
9428
9429/// ActOnBlockStmtExpr - This is called when the body of a block statement
9430/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009431ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009432 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009433 // If blocks are disabled, emit an error.
9434 if (!LangOpts.Blocks)
9435 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009436
Douglas Gregor9a28e842010-03-01 23:15:13 +00009437 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009438
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009439 PopDeclContext();
9440
Steve Naroffc540d662008-09-03 18:15:37 +00009441 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009442 if (!BSI->ReturnType.isNull())
9443 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009444
Mike Stump3bf1ab42009-07-28 22:04:01 +00009445 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009446 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009447
John McCallc63de662011-02-02 13:00:07 +00009448 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009449 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9450 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009451
John McCall8e346702010-06-04 19:02:56 +00009452 // If the user wrote a function type in some form, try to use that.
9453 if (!BSI->FunctionType.isNull()) {
9454 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9455
9456 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9457 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9458
9459 // Turn protoless block types into nullary block types.
9460 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009461 FunctionProtoType::ExtProtoInfo EPI;
9462 EPI.ExtInfo = Ext;
9463 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009464
9465 // Otherwise, if we don't need to change anything about the function type,
9466 // preserve its sugar structure.
9467 } else if (FTy->getResultType() == RetTy &&
9468 (!NoReturn || FTy->getNoReturnAttr())) {
9469 BlockTy = BSI->FunctionType;
9470
9471 // Otherwise, make the minimal modifications to the function type.
9472 } else {
9473 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009474 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9475 EPI.TypeQuals = 0; // FIXME: silently?
9476 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009477 BlockTy = Context.getFunctionType(RetTy,
9478 FPT->arg_type_begin(),
9479 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009480 EPI);
John McCall8e346702010-06-04 19:02:56 +00009481 }
9482
9483 // If we don't have a function type, just build one from nothing.
9484 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009485 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009486 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009487 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009488 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009489
John McCall8e346702010-06-04 19:02:56 +00009490 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9491 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009492 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009493
Chris Lattner45542ea2009-04-19 05:28:12 +00009494 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009495 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009496 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009497
Chris Lattner60f84492011-02-17 23:58:47 +00009498 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009499
John McCallc63de662011-02-02 13:00:07 +00009500 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009501
Ted Kremenek1767a272011-02-23 01:51:48 +00009502 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9503 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009504 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009505}
9506
John McCalldadc5752010-08-24 06:29:42 +00009507ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009508 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009509 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009510 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009511 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009512 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009513}
9514
John McCalldadc5752010-08-24 06:29:42 +00009515ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009516 Expr *E, TypeSourceInfo *TInfo,
9517 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009518 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009519
Eli Friedman121ba0c2008-08-09 23:32:40 +00009520 // Get the va_list type
9521 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009522 if (VaListType->isArrayType()) {
9523 // Deal with implicit array decay; for example, on x86-64,
9524 // va_list is an array, but it's supposed to decay to
9525 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009526 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009527 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009528 ExprResult Result = UsualUnaryConversions(E);
9529 if (Result.isInvalid())
9530 return ExprError();
9531 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009532 } else {
9533 // Otherwise, the va_list argument must be an l-value because
9534 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009535 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009536 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009537 return ExprError();
9538 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009539
Douglas Gregorad3150c2009-05-19 23:10:31 +00009540 if (!E->isTypeDependent() &&
9541 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009542 return ExprError(Diag(E->getLocStart(),
9543 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009544 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009545 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009546
Eli Friedmanba961a92009-03-23 00:24:07 +00009547 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009548 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009549
Abramo Bagnara27db2392010-08-10 10:06:15 +00009550 QualType T = TInfo->getType().getNonLValueExprType(Context);
9551 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009552}
9553
John McCalldadc5752010-08-24 06:29:42 +00009554ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009555 // The type of __null will be int or long, depending on the size of
9556 // pointers on the target.
9557 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009558 unsigned pw = Context.Target.getPointerWidth(0);
9559 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009560 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009561 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009562 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009563 else if (pw == Context.Target.getLongLongWidth())
9564 Ty = Context.LongLongTy;
9565 else {
9566 assert(!"I don't know size of pointer!");
9567 Ty = Context.IntTy;
9568 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009569
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009570 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009571}
9572
Alexis Huntc46382e2010-04-28 23:02:27 +00009573static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009574 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009575 if (!SemaRef.getLangOptions().ObjC1)
9576 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009577
Anders Carlssonace5d072009-11-10 04:46:30 +00009578 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9579 if (!PT)
9580 return;
9581
9582 // Check if the destination is of type 'id'.
9583 if (!PT->isObjCIdType()) {
9584 // Check if the destination is the 'NSString' interface.
9585 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9586 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9587 return;
9588 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009589
Anders Carlssonace5d072009-11-10 04:46:30 +00009590 // Strip off any parens and casts.
9591 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9592 if (!SL || SL->isWide())
9593 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009594
Douglas Gregora771f462010-03-31 17:46:05 +00009595 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009596}
9597
Chris Lattner9bad62c2008-01-04 18:04:52 +00009598bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9599 SourceLocation Loc,
9600 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009601 Expr *SrcExpr, AssignmentAction Action,
9602 bool *Complained) {
9603 if (Complained)
9604 *Complained = false;
9605
Chris Lattner9bad62c2008-01-04 18:04:52 +00009606 // Decode the result (notice that AST's are still created for extensions).
9607 bool isInvalid = false;
9608 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009609 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009610
Chris Lattner9bad62c2008-01-04 18:04:52 +00009611 switch (ConvTy) {
9612 default: assert(0 && "Unknown conversion type");
9613 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009614 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009615 DiagKind = diag::ext_typecheck_convert_pointer_int;
9616 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009617 case IntToPointer:
9618 DiagKind = diag::ext_typecheck_convert_int_pointer;
9619 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009620 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009621 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009622 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9623 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009624 case IncompatiblePointerSign:
9625 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9626 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009627 case FunctionVoidPointer:
9628 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9629 break;
John McCall4fff8f62011-02-01 00:10:29 +00009630 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009631 // Perform array-to-pointer decay if necessary.
9632 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9633
John McCall4fff8f62011-02-01 00:10:29 +00009634 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9635 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9636 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9637 DiagKind = diag::err_typecheck_incompatible_address_space;
9638 break;
9639 }
9640
9641 llvm_unreachable("unknown error case for discarding qualifiers!");
9642 // fallthrough
9643 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009644 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009645 // If the qualifiers lost were because we were applying the
9646 // (deprecated) C++ conversion from a string literal to a char*
9647 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9648 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009649 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009650 // bit of refactoring (so that the second argument is an
9651 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009652 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009653 // C++ semantics.
9654 if (getLangOptions().CPlusPlus &&
9655 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9656 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009657 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9658 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009659 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009660 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009661 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009662 case IntToBlockPointer:
9663 DiagKind = diag::err_int_to_block_pointer;
9664 break;
9665 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009666 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009667 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009668 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009669 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009670 // it can give a more specific diagnostic.
9671 DiagKind = diag::warn_incompatible_qualified_id;
9672 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009673 case IncompatibleVectors:
9674 DiagKind = diag::warn_incompatible_vectors;
9675 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009676 case Incompatible:
9677 DiagKind = diag::err_typecheck_convert_incompatible;
9678 isInvalid = true;
9679 break;
9680 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009681
Douglas Gregorc68e1402010-04-09 00:35:39 +00009682 QualType FirstType, SecondType;
9683 switch (Action) {
9684 case AA_Assigning:
9685 case AA_Initializing:
9686 // The destination type comes first.
9687 FirstType = DstType;
9688 SecondType = SrcType;
9689 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009690
Douglas Gregorc68e1402010-04-09 00:35:39 +00009691 case AA_Returning:
9692 case AA_Passing:
9693 case AA_Converting:
9694 case AA_Sending:
9695 case AA_Casting:
9696 // The source type comes first.
9697 FirstType = SrcType;
9698 SecondType = DstType;
9699 break;
9700 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009701
Douglas Gregorc68e1402010-04-09 00:35:39 +00009702 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009703 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009704 if (Complained)
9705 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009706 return isInvalid;
9707}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009708
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009709bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009710 llvm::APSInt ICEResult;
9711 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9712 if (Result)
9713 *Result = ICEResult;
9714 return false;
9715 }
9716
Anders Carlssone54e8a12008-11-30 19:50:32 +00009717 Expr::EvalResult EvalResult;
9718
Mike Stump4e1f26a2009-02-19 03:04:26 +00009719 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009720 EvalResult.HasSideEffects) {
9721 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9722
9723 if (EvalResult.Diag) {
9724 // We only show the note if it's not the usual "invalid subexpression"
9725 // or if it's actually in a subexpression.
9726 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9727 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9728 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9729 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009730
Anders Carlssone54e8a12008-11-30 19:50:32 +00009731 return true;
9732 }
9733
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009734 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9735 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009736
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009737 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009738 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9739 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009740 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009741
Anders Carlssone54e8a12008-11-30 19:50:32 +00009742 if (Result)
9743 *Result = EvalResult.Val.getInt();
9744 return false;
9745}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009746
Douglas Gregorff790f12009-11-26 00:44:06 +00009747void
Mike Stump11289f42009-09-09 15:08:12 +00009748Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009749 ExprEvalContexts.push_back(
9750 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009751}
9752
Mike Stump11289f42009-09-09 15:08:12 +00009753void
Douglas Gregorff790f12009-11-26 00:44:06 +00009754Sema::PopExpressionEvaluationContext() {
9755 // Pop the current expression evaluation context off the stack.
9756 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9757 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009758
Douglas Gregorfab31f42009-12-12 07:57:52 +00009759 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9760 if (Rec.PotentiallyReferenced) {
9761 // Mark any remaining declarations in the current position of the stack
9762 // as "referenced". If they were not meant to be referenced, semantic
9763 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009764 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009765 I = Rec.PotentiallyReferenced->begin(),
9766 IEnd = Rec.PotentiallyReferenced->end();
9767 I != IEnd; ++I)
9768 MarkDeclarationReferenced(I->first, I->second);
9769 }
9770
9771 if (Rec.PotentiallyDiagnosed) {
9772 // Emit any pending diagnostics.
9773 for (PotentiallyEmittedDiagnostics::iterator
9774 I = Rec.PotentiallyDiagnosed->begin(),
9775 IEnd = Rec.PotentiallyDiagnosed->end();
9776 I != IEnd; ++I)
9777 Diag(I->first, I->second);
9778 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009779 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009780
9781 // When are coming out of an unevaluated context, clear out any
9782 // temporaries that we may have created as part of the evaluation of
9783 // the expression in that context: they aren't relevant because they
9784 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009785 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009786 ExprTemporaries.size() > Rec.NumTemporaries)
9787 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9788 ExprTemporaries.end());
9789
9790 // Destroy the popped expression evaluation record.
9791 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009792}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009793
9794/// \brief Note that the given declaration was referenced in the source code.
9795///
9796/// This routine should be invoke whenever a given declaration is referenced
9797/// in the source code, and where that reference occurred. If this declaration
9798/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9799/// C99 6.9p3), then the declaration will be marked as used.
9800///
9801/// \param Loc the location where the declaration was referenced.
9802///
9803/// \param D the declaration that has been referenced by the source code.
9804void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9805 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009806
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009807 D->setReferenced();
9808
Douglas Gregorebada0772010-06-17 23:14:26 +00009809 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009810 return;
Mike Stump11289f42009-09-09 15:08:12 +00009811
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009812 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9813 // template or not. The reason for this is that unevaluated expressions
9814 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9815 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009816 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009817 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009818 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009819 return;
9820 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009821
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009822 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9823 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009824
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009825 // Do not mark anything as "used" within a dependent context; wait for
9826 // an instantiation.
9827 if (CurContext->isDependentContext())
9828 return;
Mike Stump11289f42009-09-09 15:08:12 +00009829
Douglas Gregorff790f12009-11-26 00:44:06 +00009830 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009831 case Unevaluated:
9832 // We are in an expression that is not potentially evaluated; do nothing.
9833 return;
Mike Stump11289f42009-09-09 15:08:12 +00009834
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009835 case PotentiallyEvaluated:
9836 // We are in a potentially-evaluated expression, so this declaration is
9837 // "used"; handle this below.
9838 break;
Mike Stump11289f42009-09-09 15:08:12 +00009839
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009840 case PotentiallyPotentiallyEvaluated:
9841 // We are in an expression that may be potentially evaluated; queue this
9842 // declaration reference until we know whether the expression is
9843 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009844 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009845 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009846
9847 case PotentiallyEvaluatedIfUsed:
9848 // Referenced declarations will only be used if the construct in the
9849 // containing expression is used.
9850 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009851 }
Mike Stump11289f42009-09-09 15:08:12 +00009852
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009853 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009855 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009856 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009857 if (Constructor->getParent()->hasTrivialConstructor())
9858 return;
9859 if (!Constructor->isUsed(false))
9860 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009861 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009862 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009863 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009864 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9865 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009866
Douglas Gregor88d292c2010-05-13 16:44:06 +00009867 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009868 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009869 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009870 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009871 if (Destructor->isVirtual())
9872 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009873 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9874 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9875 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009876 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009877 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009878 } else if (MethodDecl->isVirtual())
9879 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009880 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009881 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009882 // Recursive functions should be marked when used from another function.
9883 if (CurContext == Function) return;
9884
Mike Stump11289f42009-09-09 15:08:12 +00009885 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009886 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009887 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009888 bool AlreadyInstantiated = false;
9889 if (FunctionTemplateSpecializationInfo *SpecInfo
9890 = Function->getTemplateSpecializationInfo()) {
9891 if (SpecInfo->getPointOfInstantiation().isInvalid())
9892 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009893 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009894 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009895 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009896 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009897 = Function->getMemberSpecializationInfo()) {
9898 if (MSInfo->getPointOfInstantiation().isInvalid())
9899 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009900 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009901 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009902 AlreadyInstantiated = true;
9903 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009904
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009905 if (!AlreadyInstantiated) {
9906 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9907 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9908 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9909 Loc));
9910 else
Chandler Carruth54080172010-08-25 08:44:16 +00009911 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009912 }
John McCall83779672011-02-19 02:53:41 +00009913 } else {
9914 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009915 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9916 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009917 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009918 MarkDeclarationReferenced(Loc, *i);
9919 }
John McCall83779672011-02-19 02:53:41 +00009920 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009921
John McCall83779672011-02-19 02:53:41 +00009922 // Keep track of used but undefined functions.
9923 if (!Function->isPure() && !Function->hasBody() &&
9924 Function->getLinkage() != ExternalLinkage) {
9925 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9926 if (old.isInvalid()) old = Loc;
9927 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009928
John McCall83779672011-02-19 02:53:41 +00009929 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009930 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009931 }
Mike Stump11289f42009-09-09 15:08:12 +00009932
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009933 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009934 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009935 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009936 Var->getInstantiatedFromStaticDataMember()) {
9937 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9938 assert(MSInfo && "Missing member specialization information?");
9939 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9940 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9941 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009942 // This is a modification of an existing AST node. Notify listeners.
9943 if (ASTMutationListener *L = getASTMutationListener())
9944 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009945 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009946 }
9947 }
Mike Stump11289f42009-09-09 15:08:12 +00009948
John McCall15dd4042011-02-21 19:25:48 +00009949 // Keep track of used but undefined variables. We make a hole in
9950 // the warning for static const data members with in-line
9951 // initializers.
John McCall83779672011-02-19 02:53:41 +00009952 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009953 && Var->getLinkage() != ExternalLinkage
9954 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009955 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9956 if (old.isInvalid()) old = Loc;
9957 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009958
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009959 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009960 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009961 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009962}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009963
Douglas Gregor5597ab42010-05-07 23:12:07 +00009964namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009965 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009966 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009967 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009968 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9969 Sema &S;
9970 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009971
Douglas Gregor5597ab42010-05-07 23:12:07 +00009972 public:
9973 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009974
Douglas Gregor5597ab42010-05-07 23:12:07 +00009975 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009976
9977 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9978 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009979 };
9980}
9981
Chandler Carruthaf80f662010-06-09 08:17:30 +00009982bool MarkReferencedDecls::TraverseTemplateArgument(
9983 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009984 if (Arg.getKind() == TemplateArgument::Declaration) {
9985 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9986 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009987
9988 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009989}
9990
Chandler Carruthaf80f662010-06-09 08:17:30 +00009991bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009992 if (ClassTemplateSpecializationDecl *Spec
9993 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9994 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009995 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009996 }
9997
Chandler Carruthc65667c2010-06-10 10:31:57 +00009998 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009999}
10000
10001void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10002 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010003 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010004}
10005
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010006namespace {
10007 /// \brief Helper class that marks all of the declarations referenced by
10008 /// potentially-evaluated subexpressions as "referenced".
10009 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10010 Sema &S;
10011
10012 public:
10013 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10014
10015 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10016
10017 void VisitDeclRefExpr(DeclRefExpr *E) {
10018 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10019 }
10020
10021 void VisitMemberExpr(MemberExpr *E) {
10022 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010023 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010024 }
10025
10026 void VisitCXXNewExpr(CXXNewExpr *E) {
10027 if (E->getConstructor())
10028 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10029 if (E->getOperatorNew())
10030 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10031 if (E->getOperatorDelete())
10032 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010033 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010034 }
10035
10036 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10037 if (E->getOperatorDelete())
10038 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010039 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10040 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10041 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10042 S.MarkDeclarationReferenced(E->getLocStart(),
10043 S.LookupDestructor(Record));
10044 }
10045
Douglas Gregor32b3de52010-09-11 23:32:50 +000010046 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010047 }
10048
10049 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10050 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010051 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010052 }
10053
10054 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10055 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10056 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010057
10058 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10059 Visit(E->getExpr());
10060 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010061 };
10062}
10063
10064/// \brief Mark any declarations that appear within this expression or any
10065/// potentially-evaluated subexpressions as "referenced".
10066void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10067 EvaluatedExprMarker(*this).Visit(E);
10068}
10069
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010070/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10071/// of the program being compiled.
10072///
10073/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010074/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010075/// possibility that the code will actually be executable. Code in sizeof()
10076/// expressions, code used only during overload resolution, etc., are not
10077/// potentially evaluated. This routine will suppress such diagnostics or,
10078/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010079/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010080/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010081///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010082/// This routine should be used for all diagnostics that describe the run-time
10083/// behavior of a program, such as passing a non-POD value through an ellipsis.
10084/// Failure to do so will likely result in spurious diagnostics or failures
10085/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010086bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010087 const PartialDiagnostic &PD) {
10088 switch (ExprEvalContexts.back().Context ) {
10089 case Unevaluated:
10090 // The argument will never be evaluated, so don't complain.
10091 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010092
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010093 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010094 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010095 if (stmt && getCurFunctionOrMethodDecl()) {
10096 FunctionScopes.back()->PossiblyUnreachableDiags.
10097 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10098 }
10099 else
10100 Diag(Loc, PD);
10101
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010102 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010103
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010104 case PotentiallyPotentiallyEvaluated:
10105 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10106 break;
10107 }
10108
10109 return false;
10110}
10111
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010112bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10113 CallExpr *CE, FunctionDecl *FD) {
10114 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10115 return false;
10116
10117 PartialDiagnostic Note =
10118 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10119 << FD->getDeclName() : PDiag();
10120 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010121
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010122 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010123 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010124 PDiag(diag::err_call_function_incomplete_return)
10125 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010126 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010127 << CE->getSourceRange(),
10128 std::make_pair(NoteLoc, Note)))
10129 return true;
10130
10131 return false;
10132}
10133
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010134// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010135// will prevent this condition from triggering, which is what we want.
10136void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10137 SourceLocation Loc;
10138
John McCall0506e4a2009-11-11 02:41:58 +000010139 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010140 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010141
John McCalld5707ab2009-10-12 21:59:07 +000010142 if (isa<BinaryOperator>(E)) {
10143 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010144 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010145 return;
10146
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010147 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10148
John McCallb0e419e2009-11-12 00:06:05 +000010149 // Greylist some idioms by putting them into a warning subcategory.
10150 if (ObjCMessageExpr *ME
10151 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10152 Selector Sel = ME->getSelector();
10153
John McCallb0e419e2009-11-12 00:06:05 +000010154 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010155 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010156 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10157
10158 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010159 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010160 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10161 }
John McCall0506e4a2009-11-11 02:41:58 +000010162
John McCalld5707ab2009-10-12 21:59:07 +000010163 Loc = Op->getOperatorLoc();
10164 } else if (isa<CXXOperatorCallExpr>(E)) {
10165 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010166 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010167 return;
10168
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010169 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010170 Loc = Op->getOperatorLoc();
10171 } else {
10172 // Not an assignment.
10173 return;
10174 }
10175
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010176 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010177
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010178 SourceLocation Open = E->getSourceRange().getBegin();
10179 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10180 Diag(Loc, diag::note_condition_assign_silence)
10181 << FixItHint::CreateInsertion(Open, "(")
10182 << FixItHint::CreateInsertion(Close, ")");
10183
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010184 if (IsOrAssign)
10185 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10186 << FixItHint::CreateReplacement(Loc, "!=");
10187 else
10188 Diag(Loc, diag::note_condition_assign_to_comparison)
10189 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010190}
10191
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010192/// \brief Redundant parentheses over an equality comparison can indicate
10193/// that the user intended an assignment used as condition.
10194void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010195 // Don't warn if the parens came from a macro.
10196 SourceLocation parenLoc = parenE->getLocStart();
10197 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10198 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010199 // Don't warn for dependent expressions.
10200 if (parenE->isTypeDependent())
10201 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010202
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010203 Expr *E = parenE->IgnoreParens();
10204
10205 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010206 if (opE->getOpcode() == BO_EQ &&
10207 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10208 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010209 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010210
Ted Kremenekae022092011-02-02 02:20:30 +000010211 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010212 Diag(Loc, diag::note_equality_comparison_silence)
10213 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10214 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010215 Diag(Loc, diag::note_equality_comparison_to_assign)
10216 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010217 }
10218}
10219
John Wiegley01296292011-04-08 18:41:53 +000010220ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010221 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010222 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10223 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010224
John McCall0009fcc2011-04-26 20:42:42 +000010225 ExprResult result = CheckPlaceholderExpr(E);
10226 if (result.isInvalid()) return ExprError();
10227 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010228
John McCall0009fcc2011-04-26 20:42:42 +000010229 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010230 if (getLangOptions().CPlusPlus)
10231 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10232
John Wiegley01296292011-04-08 18:41:53 +000010233 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10234 if (ERes.isInvalid())
10235 return ExprError();
10236 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010237
10238 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010239 if (!T->isScalarType()) { // C99 6.8.4.1p1
10240 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10241 << T << E->getSourceRange();
10242 return ExprError();
10243 }
John McCalld5707ab2009-10-12 21:59:07 +000010244 }
10245
John Wiegley01296292011-04-08 18:41:53 +000010246 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010247}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010248
John McCalldadc5752010-08-24 06:29:42 +000010249ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10250 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010251 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010252 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010253
10254 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010255}
John McCall36e7fe32010-10-12 00:20:44 +000010256
John McCall31996342011-04-07 08:22:57 +000010257namespace {
John McCall2979fe02011-04-12 00:42:48 +000010258 /// A visitor for rebuilding a call to an __unknown_any expression
10259 /// to have an appropriate type.
10260 struct RebuildUnknownAnyFunction
10261 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10262
10263 Sema &S;
10264
10265 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10266
10267 ExprResult VisitStmt(Stmt *S) {
10268 llvm_unreachable("unexpected statement!");
10269 return ExprError();
10270 }
10271
10272 ExprResult VisitExpr(Expr *expr) {
10273 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10274 << expr->getSourceRange();
10275 return ExprError();
10276 }
10277
10278 /// Rebuild an expression which simply semantically wraps another
10279 /// expression which it shares the type and value kind of.
10280 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10281 ExprResult subResult = Visit(expr->getSubExpr());
10282 if (subResult.isInvalid()) return ExprError();
10283
10284 Expr *subExpr = subResult.take();
10285 expr->setSubExpr(subExpr);
10286 expr->setType(subExpr->getType());
10287 expr->setValueKind(subExpr->getValueKind());
10288 assert(expr->getObjectKind() == OK_Ordinary);
10289 return expr;
10290 }
10291
10292 ExprResult VisitParenExpr(ParenExpr *paren) {
10293 return rebuildSugarExpr(paren);
10294 }
10295
10296 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10297 return rebuildSugarExpr(op);
10298 }
10299
10300 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10301 ExprResult subResult = Visit(op->getSubExpr());
10302 if (subResult.isInvalid()) return ExprError();
10303
10304 Expr *subExpr = subResult.take();
10305 op->setSubExpr(subExpr);
10306 op->setType(S.Context.getPointerType(subExpr->getType()));
10307 assert(op->getValueKind() == VK_RValue);
10308 assert(op->getObjectKind() == OK_Ordinary);
10309 return op;
10310 }
10311
10312 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10313 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10314
10315 expr->setType(decl->getType());
10316
10317 assert(expr->getValueKind() == VK_RValue);
10318 if (S.getLangOptions().CPlusPlus &&
10319 !(isa<CXXMethodDecl>(decl) &&
10320 cast<CXXMethodDecl>(decl)->isInstance()))
10321 expr->setValueKind(VK_LValue);
10322
10323 return expr;
10324 }
10325
10326 ExprResult VisitMemberExpr(MemberExpr *mem) {
10327 return resolveDecl(mem, mem->getMemberDecl());
10328 }
10329
10330 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10331 return resolveDecl(ref, ref->getDecl());
10332 }
10333 };
10334}
10335
10336/// Given a function expression of unknown-any type, try to rebuild it
10337/// to have a function type.
10338static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10339 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10340 if (result.isInvalid()) return ExprError();
10341 return S.DefaultFunctionArrayConversion(result.take());
10342}
10343
10344namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010345 /// A visitor for rebuilding an expression of type __unknown_anytype
10346 /// into one which resolves the type directly on the referring
10347 /// expression. Strict preservation of the original source
10348 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010349 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010350 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010351
10352 Sema &S;
10353
10354 /// The current destination type.
10355 QualType DestType;
10356
10357 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10358 : S(S), DestType(castType) {}
10359
John McCall39439732011-04-09 22:50:59 +000010360 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010361 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010362 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010363 }
10364
John McCall2d2e8702011-04-11 07:02:50 +000010365 ExprResult VisitExpr(Expr *expr) {
10366 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10367 << expr->getSourceRange();
10368 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010369 }
10370
John McCall2d2e8702011-04-11 07:02:50 +000010371 ExprResult VisitCallExpr(CallExpr *call);
10372 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10373
John McCall39439732011-04-09 22:50:59 +000010374 /// Rebuild an expression which simply semantically wraps another
10375 /// expression which it shares the type and value kind of.
10376 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10377 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010378 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010379 Expr *subExpr = subResult.take();
10380 expr->setSubExpr(subExpr);
10381 expr->setType(subExpr->getType());
10382 expr->setValueKind(subExpr->getValueKind());
10383 assert(expr->getObjectKind() == OK_Ordinary);
10384 return expr;
10385 }
John McCall31996342011-04-07 08:22:57 +000010386
John McCall39439732011-04-09 22:50:59 +000010387 ExprResult VisitParenExpr(ParenExpr *paren) {
10388 return rebuildSugarExpr(paren);
10389 }
10390
10391 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10392 return rebuildSugarExpr(op);
10393 }
10394
John McCall2979fe02011-04-12 00:42:48 +000010395 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10396 const PointerType *ptr = DestType->getAs<PointerType>();
10397 if (!ptr) {
10398 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10399 << op->getSourceRange();
10400 return ExprError();
10401 }
10402 assert(op->getValueKind() == VK_RValue);
10403 assert(op->getObjectKind() == OK_Ordinary);
10404 op->setType(DestType);
10405
10406 // Build the sub-expression as if it were an object of the pointee type.
10407 DestType = ptr->getPointeeType();
10408 ExprResult subResult = Visit(op->getSubExpr());
10409 if (subResult.isInvalid()) return ExprError();
10410 op->setSubExpr(subResult.take());
10411 return op;
10412 }
10413
John McCall2d2e8702011-04-11 07:02:50 +000010414 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010415
John McCall2979fe02011-04-12 00:42:48 +000010416 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010417
John McCall2979fe02011-04-12 00:42:48 +000010418 ExprResult VisitMemberExpr(MemberExpr *mem) {
10419 return resolveDecl(mem, mem->getMemberDecl());
10420 }
John McCall39439732011-04-09 22:50:59 +000010421
10422 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010423 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010424 }
10425 };
10426}
10427
John McCall2d2e8702011-04-11 07:02:50 +000010428/// Rebuilds a call expression which yielded __unknown_anytype.
10429ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10430 Expr *callee = call->getCallee();
10431
10432 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010433 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010434 FK_FunctionPointer,
10435 FK_BlockPointer
10436 };
10437
10438 FnKind kind;
10439 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010440 if (type == S.Context.BoundMemberTy) {
10441 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10442 kind = FK_MemberFunction;
10443 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010444 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10445 type = ptr->getPointeeType();
10446 kind = FK_FunctionPointer;
10447 } else {
10448 type = type->castAs<BlockPointerType>()->getPointeeType();
10449 kind = FK_BlockPointer;
10450 }
10451 const FunctionType *fnType = type->castAs<FunctionType>();
10452
10453 // Verify that this is a legal result type of a function.
10454 if (DestType->isArrayType() || DestType->isFunctionType()) {
10455 unsigned diagID = diag::err_func_returning_array_function;
10456 if (kind == FK_BlockPointer)
10457 diagID = diag::err_block_returning_array_function;
10458
10459 S.Diag(call->getExprLoc(), diagID)
10460 << DestType->isFunctionType() << DestType;
10461 return ExprError();
10462 }
10463
10464 // Otherwise, go ahead and set DestType as the call's result.
10465 call->setType(DestType.getNonLValueExprType(S.Context));
10466 call->setValueKind(Expr::getValueKindForType(DestType));
10467 assert(call->getObjectKind() == OK_Ordinary);
10468
10469 // Rebuild the function type, replacing the result type with DestType.
10470 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10471 DestType = S.Context.getFunctionType(DestType,
10472 proto->arg_type_begin(),
10473 proto->getNumArgs(),
10474 proto->getExtProtoInfo());
10475 else
10476 DestType = S.Context.getFunctionNoProtoType(DestType,
10477 fnType->getExtInfo());
10478
10479 // Rebuild the appropriate pointer-to-function type.
10480 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010481 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010482 // Nothing to do.
10483 break;
10484
10485 case FK_FunctionPointer:
10486 DestType = S.Context.getPointerType(DestType);
10487 break;
10488
10489 case FK_BlockPointer:
10490 DestType = S.Context.getBlockPointerType(DestType);
10491 break;
10492 }
10493
10494 // Finally, we can recurse.
10495 ExprResult calleeResult = Visit(callee);
10496 if (!calleeResult.isUsable()) return ExprError();
10497 call->setCallee(calleeResult.take());
10498
10499 // Bind a temporary if necessary.
10500 return S.MaybeBindToTemporary(call);
10501}
10502
10503ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010504 ObjCMethodDecl *method = msg->getMethodDecl();
10505 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010506
John McCall2979fe02011-04-12 00:42:48 +000010507 // Verify that this is a legal result type of a call.
10508 if (DestType->isArrayType() || DestType->isFunctionType()) {
10509 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10510 << DestType->isFunctionType() << DestType;
10511 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010512 }
10513
John McCall2979fe02011-04-12 00:42:48 +000010514 assert(method->getResultType() == S.Context.UnknownAnyTy);
10515 method->setResultType(DestType);
10516
John McCall2d2e8702011-04-11 07:02:50 +000010517 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010518 msg->setType(DestType.getNonReferenceType());
10519 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010520
John McCall2979fe02011-04-12 00:42:48 +000010521 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000010522}
10523
10524ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000010525 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000010526 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000010527 assert(ice->getValueKind() == VK_RValue);
10528 assert(ice->getObjectKind() == OK_Ordinary);
10529
John McCall2979fe02011-04-12 00:42:48 +000010530 ice->setType(DestType);
10531
John McCall2d2e8702011-04-11 07:02:50 +000010532 // Rebuild the sub-expression as the pointee (function) type.
10533 DestType = DestType->castAs<PointerType>()->getPointeeType();
10534
10535 ExprResult result = Visit(ice->getSubExpr());
10536 if (!result.isUsable()) return ExprError();
10537
10538 ice->setSubExpr(result.take());
10539 return S.Owned(ice);
10540}
10541
John McCall2979fe02011-04-12 00:42:48 +000010542ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000010543 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000010544 QualType type = DestType;
10545
10546 // We know how to make this work for certain kinds of decls:
10547
10548 // - functions
John McCall2979fe02011-04-12 00:42:48 +000010549 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000010550 // This is true because FunctionDecls must always have function
10551 // type, so we can't be resolving the entire thing at once.
10552 assert(type->isFunctionType());
10553
John McCall4adb38c2011-04-27 00:36:17 +000010554 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10555 if (method->isInstance()) {
10556 valueKind = VK_RValue;
10557 type = S.Context.BoundMemberTy;
10558 }
10559
John McCall2d2e8702011-04-11 07:02:50 +000010560 // Function references aren't l-values in C.
10561 if (!S.getLangOptions().CPlusPlus)
10562 valueKind = VK_RValue;
10563
10564 // - variables
10565 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000010566 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10567 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000010568 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000010569 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10570 << decl << expr->getSourceRange();
10571 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010572 }
10573
10574 // - nothing else
10575 } else {
10576 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10577 << decl << expr->getSourceRange();
10578 return ExprError();
10579 }
10580
John McCall2979fe02011-04-12 00:42:48 +000010581 decl->setType(DestType);
10582 expr->setType(type);
10583 expr->setValueKind(valueKind);
10584 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000010585}
10586
John McCall31996342011-04-07 08:22:57 +000010587/// Check a cast of an unknown-any type. We intentionally only
10588/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010589ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10590 Expr *castExpr, CastKind &castKind,
10591 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010592 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010593 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10594 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010595
John McCall39439732011-04-09 22:50:59 +000010596 castExpr = result.take();
10597 VK = castExpr->getValueKind();
10598 castKind = CK_NoOp;
10599
10600 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010601}
10602
10603static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10604 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000010605 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010606 while (true) {
10607 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000010608 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000010609 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010610 diagID = diag::err_uncasted_call_of_unknown_any;
10611 } else {
John McCall31996342011-04-07 08:22:57 +000010612 break;
John McCall2d2e8702011-04-11 07:02:50 +000010613 }
John McCall31996342011-04-07 08:22:57 +000010614 }
10615
John McCall2d2e8702011-04-11 07:02:50 +000010616 SourceLocation loc;
10617 NamedDecl *d;
10618 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10619 loc = ref->getLocation();
10620 d = ref->getDecl();
10621 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10622 loc = mem->getMemberLoc();
10623 d = mem->getMemberDecl();
10624 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10625 diagID = diag::err_uncasted_call_of_unknown_any;
10626 loc = msg->getSelectorLoc();
10627 d = msg->getMethodDecl();
10628 assert(d && "unknown method returning __unknown_any?");
10629 } else {
10630 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10631 << e->getSourceRange();
10632 return ExprError();
10633 }
10634
10635 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010636
10637 // Never recoverable.
10638 return ExprError();
10639}
10640
John McCall36e7fe32010-10-12 00:20:44 +000010641/// Check for operands with placeholder types and complain if found.
10642/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010643ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010644 // Placeholder types are always *exactly* the appropriate builtin type.
10645 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010646
John McCall31996342011-04-07 08:22:57 +000010647 // Overloaded expressions.
10648 if (type == Context.OverloadTy)
10649 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010650 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010651 QualType(),
10652 diag::err_ovl_unresolvable);
10653
John McCall0009fcc2011-04-26 20:42:42 +000010654 // Bound member functions.
10655 if (type == Context.BoundMemberTy) {
10656 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10657 << E->getSourceRange();
10658 return ExprError();
10659 }
10660
John McCall31996342011-04-07 08:22:57 +000010661 // Expressions of unknown type.
10662 if (type == Context.UnknownAnyTy)
10663 return diagnoseUnknownAnyExpr(*this, E);
10664
10665 assert(!type->isPlaceholderType());
10666 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010667}
Richard Trieu2c850c02011-04-21 21:44:26 +000010668
10669bool Sema::CheckCaseExpression(Expr *expr) {
10670 if (expr->isTypeDependent())
10671 return true;
10672 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10673 return expr->getType()->isIntegralOrEnumerationType();
10674 return false;
10675}