blob: fbf0a986d5f95db73a9a9014969250ff1b5ad463 [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"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000072 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Douglas Gregor171c45a2009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 if (FD->isDeleted()) {
88 Diag(Loc, diag::err_deleted_function_use);
89 Diag(D->getLocation(), diag::note_unavailable_here) << true;
90 return true;
91 }
Douglas Gregorde681d42009-02-24 04:26:15 +000092 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000093
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000094 // See if this declaration is unavailable or deprecated.
95 std::string Message;
96 switch (D->getAvailability(&Message)) {
97 case AR_Available:
98 case AR_NotYetIntroduced:
99 break;
100
101 case AR_Deprecated:
102 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103 break;
104
105 case AR_Unavailable:
106 if (Message.empty()) {
107 if (!UnknownObjCClass)
108 Diag(Loc, diag::err_unavailable) << D->getDeclName();
109 else
110 Diag(Loc, diag::warn_unavailable_fwdclass_message)
111 << D->getDeclName();
112 }
113 else
114 Diag(Loc, diag::err_unavailable_message)
115 << D->getDeclName() << Message;
116 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117 break;
118 }
119
Anders Carlsson73067a02010-10-22 23:37:08 +0000120 // Warn if this is used but marked unused.
121 if (D->hasAttr<UnusedAttr>())
122 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
Douglas Gregor171c45a2009-02-18 21:56:37 +0000124 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000125}
126
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131 // FIXME: C++0x implicitly-deleted special member functions could be
132 // detected here so that we could improve diagnostics to say, e.g.,
133 // "base class 'A' had a deleted copy constructor".
134 if (FD->isDeleted())
135 return std::string();
136
137 std::string Message;
138 if (FD->getAvailability(&Message))
139 return ": " + Message;
140
141 return std::string();
142}
143
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000152 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000153
154 // FIXME: In C++0x, if any of the arguments are parameter pack
155 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Mike Stump87c57ac2009-05-16 07:39:55 +0000159 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 bool warnNotEnoughArgs = false;
163 int isMethod = 0;
164 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165 // skip over named parameters.
166 ObjCMethodDecl::param_iterator P, E = MD->param_end();
167 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168 if (nullPos)
169 --nullPos;
170 else
171 ++i;
172 }
173 warnNotEnoughArgs = (P != E || i >= NumArgs);
174 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000176 // skip over named parameters.
177 ObjCMethodDecl::param_iterator P, E = FD->param_end();
178 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179 if (nullPos)
180 --nullPos;
181 else
182 ++i;
183 }
184 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000192 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193 unsigned NumArgsInProto = Proto->getNumArgs();
194 unsigned k;
195 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196 if (nullPos)
197 --nullPos;
198 else
199 ++i;
200 }
201 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202 }
203 if (Ty->isBlockPointerType())
204 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000205 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000206 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
214 }
215 int sentinel = i;
216 while (sentinelPos > 0 && i < NumArgs-1) {
217 --sentinelPos;
218 ++i;
219 }
220 if (sentinelPos > 0) {
221 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000238 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239 Expr::NPC_ValueDependentIsNull))
240 return;
241
242 // Unfortunately, __null has type 'int'.
243 if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000247}
248
Douglas Gregor87f95b02009-02-26 21:00:50 +0000249SourceRange Sema::getExprRange(ExprTy *E) const {
250 Expr *Ex = (Expr *)E;
251 return Ex? Ex->getSourceRange() : SourceRange();
252}
253
Chris Lattner513165e2008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000266 else if (Ty->isArrayType()) {
267 // In C90 mode, arrays only promote to pointers if the array expression is
268 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269 // type 'array of type' is converted to an expression that has type 'pointer
270 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
271 // that has type 'array of type' ...". The relevant change is "an lvalue"
272 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000273 //
274 // C++ 4.2p1:
275 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276 // T" can be converted to an rvalue of type "pointer to T".
277 //
John McCall086a4642010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 }
John Wiegley01296292011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000283}
284
John Wiegley01296292011-04-08 18:41:53 +0000285ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000286 // C++ [conv.lval]p1:
287 // A glvalue of a non-function, non-array type T can be
288 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000289 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000290
John McCall27584242010-12-06 20:48:59 +0000291 QualType T = E->getType();
292 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000293
John McCall27584242010-12-06 20:48:59 +0000294 // Create a load out of an ObjCProperty l-value, if necessary.
295 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000296 ExprResult Res = ConvertPropertyForRValue(E);
297 if (Res.isInvalid())
298 return Owned(E);
299 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000300 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000301 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000302 }
John McCall27584242010-12-06 20:48:59 +0000303
304 // We don't want to throw lvalue-to-rvalue casts on top of
305 // expressions of certain types in C++.
306 if (getLangOptions().CPlusPlus &&
307 (E->getType() == Context.OverloadTy ||
308 T->isDependentType() ||
309 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000310 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000311
312 // The C standard is actually really unclear on this point, and
313 // DR106 tells us what the result should be but not why. It's
314 // generally best to say that void types just doesn't undergo
315 // lvalue-to-rvalue at all. Note that expressions of unqualified
316 // 'void' type are never l-values, but qualified void can be.
317 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000318 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000319
320 // C++ [conv.lval]p1:
321 // [...] If T is a non-class type, the type of the prvalue is the
322 // cv-unqualified version of T. Otherwise, the type of the
323 // rvalue is T.
324 //
325 // C99 6.3.2.1p2:
326 // If the lvalue has qualified type, the value has the unqualified
327 // version of the type of the lvalue; otherwise, the value has the
328 // type of the lvalue.
329 if (T.hasQualifiers())
330 T = T.getUnqualifiedType();
331
Ted Kremenekdf26df72011-03-01 18:41:00 +0000332 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000333
John Wiegley01296292011-04-08 18:41:53 +0000334 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
335 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000336}
337
John Wiegley01296292011-04-08 18:41:53 +0000338ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
339 ExprResult Res = DefaultFunctionArrayConversion(E);
340 if (Res.isInvalid())
341 return ExprError();
342 Res = DefaultLvalueConversion(Res.take());
343 if (Res.isInvalid())
344 return ExprError();
345 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000346}
347
348
Chris Lattner513165e2008-07-25 21:10:04 +0000349/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000350/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000351/// sometimes surpressed. For example, the array->pointer conversion doesn't
352/// apply if the array is an argument to the sizeof or address (&) operators.
353/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000354ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000355 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000356 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
357 if (Res.isInvalid())
358 return Owned(E);
359 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000360
361 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000362 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000363
364 // Try to perform integral promotions if the object has a theoretically
365 // promotable type.
366 if (Ty->isIntegralOrUnscopedEnumerationType()) {
367 // C99 6.3.1.1p2:
368 //
369 // The following may be used in an expression wherever an int or
370 // unsigned int may be used:
371 // - an object or expression with an integer type whose integer
372 // conversion rank is less than or equal to the rank of int
373 // and unsigned int.
374 // - A bit-field of type _Bool, int, signed int, or unsigned int.
375 //
376 // If an int can represent all values of the original type, the
377 // value is converted to an int; otherwise, it is converted to an
378 // unsigned int. These are called the integer promotions. All
379 // other types are unchanged by the integer promotions.
380
381 QualType PTy = Context.isPromotableBitField(E);
382 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000383 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
384 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000385 }
386 if (Ty->isPromotableIntegerType()) {
387 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000388 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
389 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000390 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000391 }
John Wiegley01296292011-04-08 18:41:53 +0000392 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000393}
394
Chris Lattner2ce500f2008-07-25 22:25:12 +0000395/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000396/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000397/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000398ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
399 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000400 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000401
John Wiegley01296292011-04-08 18:41:53 +0000402 ExprResult Res = UsualUnaryConversions(E);
403 if (Res.isInvalid())
404 return Owned(E);
405 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000406
Chris Lattner2ce500f2008-07-25 22:25:12 +0000407 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000408 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
410
411 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000412}
413
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000414/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
415/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000416/// interfaces passed by value.
417ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000418 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000419 ExprResult ExprRes = DefaultArgumentPromotion(E);
420 if (ExprRes.isInvalid())
421 return ExprError();
422 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000424 // __builtin_va_start takes the second argument as a "varargs" argument, but
425 // it doesn't actually do anything with it. It doesn't need to be non-pod
426 // etc.
427 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000429
John Wiegley01296292011-04-08 18:41:53 +0000430 if (E->getType()->isObjCObjectType() &&
431 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000432 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000433 << E->getType() << CT))
434 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000435
John Wiegley01296292011-04-08 18:41:53 +0000436 if (!E->getType()->isPODType() &&
437 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000438 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000439 << E->getType() << CT))
440 return ExprError();
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000441
John Wiegley01296292011-04-08 18:41:53 +0000442 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000443}
444
Chris Lattner513165e2008-07-25 21:10:04 +0000445/// UsualArithmeticConversions - Performs various conversions that are common to
446/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000447/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000448/// responsible for emitting appropriate error diagnostics.
449/// FIXME: verify the conversion rules for "complex int" are consistent with
450/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000451QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000452 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000453 if (!isCompAssign) {
454 lhsExpr = UsualUnaryConversions(lhsExpr.take());
455 if (lhsExpr.isInvalid())
456 return QualType();
457 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000458
John Wiegley01296292011-04-08 18:41:53 +0000459 rhsExpr = UsualUnaryConversions(rhsExpr.take());
460 if (rhsExpr.isInvalid())
461 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000462
Mike Stump11289f42009-09-09 15:08:12 +0000463 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000464 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000465 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000466 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000467 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000468 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000469
470 // If both types are identical, no conversion is needed.
471 if (lhs == rhs)
472 return lhs;
473
474 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
475 // The caller can deal with this (e.g. pointer + int).
476 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
477 return lhs;
478
John McCalld005ac92010-11-13 08:17:45 +0000479 // Apply unary and bitfield promotions to the LHS's type.
480 QualType lhs_unpromoted = lhs;
481 if (lhs->isPromotableIntegerType())
482 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000483 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000484 if (!LHSBitfieldPromoteTy.isNull())
485 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000486 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000487 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000488
John McCalld005ac92010-11-13 08:17:45 +0000489 // If both types are identical, no conversion is needed.
490 if (lhs == rhs)
491 return lhs;
492
493 // At this point, we have two different arithmetic types.
494
495 // Handle complex types first (C99 6.3.1.8p1).
496 bool LHSComplexFloat = lhs->isComplexType();
497 bool RHSComplexFloat = rhs->isComplexType();
498 if (LHSComplexFloat || RHSComplexFloat) {
499 // if we have an integer operand, the result is the complex type.
500
John McCallc5e62b42010-11-13 09:02:35 +0000501 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
502 if (rhs->isIntegerType()) {
503 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000504 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
505 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000506 } else {
507 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000508 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000509 }
John McCalld005ac92010-11-13 08:17:45 +0000510 return lhs;
511 }
512
John McCallc5e62b42010-11-13 09:02:35 +0000513 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
514 if (!isCompAssign) {
515 // int -> float -> _Complex float
516 if (lhs->isIntegerType()) {
517 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000518 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
519 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000520 } else {
521 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000522 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000523 }
524 }
John McCalld005ac92010-11-13 08:17:45 +0000525 return rhs;
526 }
527
528 // This handles complex/complex, complex/float, or float/complex.
529 // When both operands are complex, the shorter operand is converted to the
530 // type of the longer, and that is the type of the result. This corresponds
531 // to what is done when combining two real floating-point operands.
532 // The fun begins when size promotion occur across type domains.
533 // From H&S 6.3.4: When one operand is complex and the other is a real
534 // floating-point type, the less precise type is converted, within it's
535 // real or complex domain, to the precision of the other type. For example,
536 // when combining a "long double" with a "double _Complex", the
537 // "double _Complex" is promoted to "long double _Complex".
538 int order = Context.getFloatingTypeOrder(lhs, rhs);
539
540 // If both are complex, just cast to the more precise type.
541 if (LHSComplexFloat && RHSComplexFloat) {
542 if (order > 0) {
543 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000544 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000545 return lhs;
546
547 } else if (order < 0) {
548 // _Complex float -> _Complex double
549 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000550 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000551 return rhs;
552 }
553 return lhs;
554 }
555
556 // If just the LHS is complex, the RHS needs to be converted,
557 // and the LHS might need to be promoted.
558 if (LHSComplexFloat) {
559 if (order > 0) { // LHS is wider
560 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000561 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000562 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
563 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000564 return lhs;
565 }
566
567 // RHS is at least as wide. Find its corresponding complex type.
568 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
569
570 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000571 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000572
573 // _Complex float -> _Complex double
574 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000575 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000576
577 return result;
578 }
579
580 // Just the RHS is complex, so the LHS needs to be converted
581 // and the RHS might need to be promoted.
582 assert(RHSComplexFloat);
583
584 if (order < 0) { // RHS is wider
585 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000587 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000588 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
589 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000590 }
John McCalld005ac92010-11-13 08:17:45 +0000591 return rhs;
592 }
593
594 // LHS is at least as wide. Find its corresponding complex type.
595 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
596
597 // double -> _Complex double
598 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000599 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000600
601 // _Complex float -> _Complex double
602 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000603 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000604
605 return result;
606 }
607
608 // Now handle "real" floating types (i.e. float, double, long double).
609 bool LHSFloat = lhs->isRealFloatingType();
610 bool RHSFloat = rhs->isRealFloatingType();
611 if (LHSFloat || RHSFloat) {
612 // If we have two real floating types, convert the smaller operand
613 // to the bigger result.
614 if (LHSFloat && RHSFloat) {
615 int order = Context.getFloatingTypeOrder(lhs, rhs);
616 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000618 return lhs;
619 }
620
621 assert(order < 0 && "illegal float comparison");
622 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626
627 // If we have an integer operand, the result is the real floating type.
628 if (LHSFloat) {
629 if (rhs->isIntegerType()) {
630 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000631 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000632 return lhs;
633 }
634
635 // Convert both sides to the appropriate complex float.
636 assert(rhs->isComplexIntegerType());
637 QualType result = Context.getComplexType(lhs);
638
639 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000640 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641
642 // float -> _Complex float
643 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645
646 return result;
647 }
648
649 assert(RHSFloat);
650 if (lhs->isIntegerType()) {
651 // Convert lhs to the rhs floating point type.
652 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000653 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000654 return rhs;
655 }
656
657 // Convert both sides to the appropriate complex float.
658 assert(lhs->isComplexIntegerType());
659 QualType result = Context.getComplexType(rhs);
660
661 // _Complex int -> _Complex float
662 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000663 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000664
665 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000666 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000667
668 return result;
669 }
670
671 // Handle GCC complex int extension.
672 // FIXME: if the operands are (int, _Complex long), we currently
673 // don't promote the complex. Also, signedness?
674 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
675 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
676 if (lhsComplexInt && rhsComplexInt) {
677 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
678 rhsComplexInt->getElementType());
679 assert(order && "inequal types with equal element ordering");
680 if (order > 0) {
681 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000682 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000683 return lhs;
684 }
685
686 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000687 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000688 return rhs;
689 } else if (lhsComplexInt) {
690 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000692 return lhs;
693 } else if (rhsComplexInt) {
694 // int -> _Complex int
695 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000697 return rhs;
698 }
699
700 // Finally, we have two differing integer types.
701 // The rules for this case are in C99 6.3.1.8
702 int compare = Context.getIntegerTypeOrder(lhs, rhs);
703 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
704 rhsSigned = rhs->hasSignedIntegerRepresentation();
705 if (lhsSigned == rhsSigned) {
706 // Same signedness; use the higher-ranked type
707 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000709 return lhs;
710 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000711 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000712 return rhs;
713 } else if (compare != (lhsSigned ? 1 : -1)) {
714 // The unsigned type has greater than or equal rank to the
715 // signed type, so use the unsigned type
716 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000717 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000718 return lhs;
719 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000720 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000721 return rhs;
722 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
723 // The two types are different widths; if we are here, that
724 // means the signed type is larger than the unsigned type, so
725 // use the signed type.
726 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000727 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000728 return lhs;
729 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000730 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000731 return rhs;
732 } else {
733 // The signed type is higher-ranked than the unsigned type,
734 // but isn't actually any bigger (like unsigned int and long
735 // on most 32-bit systems). Use the unsigned type corresponding
736 // to the signed type.
737 QualType result =
738 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000740 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000742 return result;
743 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000744}
745
Chris Lattner513165e2008-07-25 21:10:04 +0000746//===----------------------------------------------------------------------===//
747// Semantic Analysis for various Expression Types
748//===----------------------------------------------------------------------===//
749
750
Steve Naroff83895f72007-09-16 03:34:24 +0000751/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000752/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
753/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
754/// multiple tokens. However, the common case is that StringToks points to one
755/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000756///
John McCalldadc5752010-08-24 06:29:42 +0000757ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000758Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000759 assert(NumStringToks && "Must have at least one string!");
760
Chris Lattner8a24e582009-01-16 18:51:42 +0000761 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000762 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000763 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000764
Chris Lattner23b7eb62007-06-15 23:05:46 +0000765 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000766 for (unsigned i = 0; i != NumStringToks; ++i)
767 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000768
Chris Lattner36fc8792008-02-11 00:02:17 +0000769 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000770 if (Literal.AnyWide)
771 StrTy = Context.getWCharType();
772 else if (Literal.Pascal)
773 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000774
775 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000776 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000777 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000778
Chris Lattner36fc8792008-02-11 00:02:17 +0000779 // Get an array type for the string, according to C99 6.4.5. This includes
780 // the nul terminator character as well as the string length for pascal
781 // strings.
782 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000783 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000784 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattner5b183d82006-11-10 05:03:26 +0000786 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000787 return Owned(StringLiteral::Create(Context, Literal.GetString(),
788 Literal.GetStringLength(),
789 Literal.AnyWide, StrTy,
790 &StringTokLocs[0],
791 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000792}
793
John McCallc63de662011-02-02 13:00:07 +0000794enum CaptureResult {
795 /// No capture is required.
796 CR_NoCapture,
797
798 /// A capture is required.
799 CR_Capture,
800
John McCall351762c2011-02-07 10:33:21 +0000801 /// A by-ref capture is required.
802 CR_CaptureByRef,
803
John McCallc63de662011-02-02 13:00:07 +0000804 /// An error occurred when trying to capture the given variable.
805 CR_Error
806};
807
808/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000809///
John McCallc63de662011-02-02 13:00:07 +0000810/// \param var - the variable referenced
811/// \param DC - the context which we couldn't capture through
812static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000813diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000814 VarDecl *var, DeclContext *DC) {
815 switch (S.ExprEvalContexts.back().Context) {
816 case Sema::Unevaluated:
817 // The argument will never be evaluated, so don't complain.
818 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000819
John McCallc63de662011-02-02 13:00:07 +0000820 case Sema::PotentiallyEvaluated:
821 case Sema::PotentiallyEvaluatedIfUsed:
822 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000823
John McCallc63de662011-02-02 13:00:07 +0000824 case Sema::PotentiallyPotentiallyEvaluated:
825 // FIXME: delay these!
826 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
John McCallc63de662011-02-02 13:00:07 +0000829 // Don't diagnose about capture if we're not actually in code right
830 // now; in general, there are more appropriate places that will
831 // diagnose this.
832 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
833
John McCall92d627e2011-03-22 23:15:50 +0000834 // Certain madnesses can happen with parameter declarations, which
835 // we want to ignore.
836 if (isa<ParmVarDecl>(var)) {
837 // - If the parameter still belongs to the translation unit, then
838 // we're actually just using one parameter in the declaration of
839 // the next. This is useful in e.g. VLAs.
840 if (isa<TranslationUnitDecl>(var->getDeclContext()))
841 return CR_NoCapture;
842
843 // - This particular madness can happen in ill-formed default
844 // arguments; claim it's okay and let downstream code handle it.
845 if (S.CurContext == var->getDeclContext()->getParent())
846 return CR_NoCapture;
847 }
John McCallc63de662011-02-02 13:00:07 +0000848
849 DeclarationName functionName;
850 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
851 functionName = fn->getDeclName();
852 // FIXME: variable from enclosing block that we couldn't capture from!
853
854 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
855 << var->getIdentifier() << functionName;
856 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
857 << var->getIdentifier();
858
859 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000860}
861
John McCall351762c2011-02-07 10:33:21 +0000862/// There is a well-formed capture at a particular scope level;
863/// propagate it through all the nested blocks.
864static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
865 const BlockDecl::Capture &capture) {
866 VarDecl *var = capture.getVariable();
867
868 // Update all the inner blocks with the capture information.
869 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
870 i != e; ++i) {
871 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
872 innerBlock->Captures.push_back(
873 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
874 /*nested*/ true, capture.getCopyExpr()));
875 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
876 }
877
878 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
879}
880
881/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000882/// given value in the current context requires a variable capture.
883///
884/// This also keeps the captures set in the BlockScopeInfo records
885/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000886static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000887 ValueDecl *value) {
888 // Only variables ever require capture.
889 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000890 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000891
892 // Fast path: variables from the current context never require capture.
893 DeclContext *DC = S.CurContext;
894 if (var->getDeclContext() == DC) return CR_NoCapture;
895
896 // Only variables with local storage require capture.
897 // FIXME: What about 'const' variables in C++?
898 if (!var->hasLocalStorage()) return CR_NoCapture;
899
900 // Otherwise, we need to capture.
901
902 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000903 do {
904 // Only blocks (and eventually C++0x closures) can capture; other
905 // scopes don't work.
906 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000907 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000908
909 BlockScopeInfo *blockScope =
910 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
911 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
912
John McCall351762c2011-02-07 10:33:21 +0000913 // Check whether we've already captured it in this block. If so,
914 // we're done.
915 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
916 return propagateCapture(S, functionScopesIndex,
917 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000918
919 functionScopesIndex--;
920 DC = cast<BlockDecl>(DC)->getDeclContext();
921 } while (var->getDeclContext() != DC);
922
John McCall351762c2011-02-07 10:33:21 +0000923 // Okay, we descended all the way to the block that defines the variable.
924 // Actually try to capture it.
925 QualType type = var->getType();
926
927 // Prohibit variably-modified types.
928 if (type->isVariablyModifiedType()) {
929 S.Diag(loc, diag::err_ref_vm_type);
930 S.Diag(var->getLocation(), diag::note_declared_at);
931 return CR_Error;
932 }
933
934 // Prohibit arrays, even in __block variables, but not references to
935 // them.
936 if (type->isArrayType()) {
937 S.Diag(loc, diag::err_ref_array_type);
938 S.Diag(var->getLocation(), diag::note_declared_at);
939 return CR_Error;
940 }
941
942 S.MarkDeclarationReferenced(loc, var);
943
944 // The BlocksAttr indicates the variable is bound by-reference.
945 bool byRef = var->hasAttr<BlocksAttr>();
946
947 // Build a copy expression.
948 Expr *copyExpr = 0;
949 if (!byRef && S.getLangOptions().CPlusPlus &&
950 !type->isDependentType() && type->isStructureOrClassType()) {
951 // According to the blocks spec, the capture of a variable from
952 // the stack requires a const copy constructor. This is not true
953 // of the copy/move done to move a __block variable to the heap.
954 type.addConst();
955
956 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
957 ExprResult result =
958 S.PerformCopyInitialization(
959 InitializedEntity::InitializeBlock(var->getLocation(),
960 type, false),
961 loc, S.Owned(declRef));
962
963 // Build a full-expression copy expression if initialization
964 // succeeded and used a non-trivial constructor. Recover from
965 // errors by pretending that the copy isn't necessary.
966 if (!result.isInvalid() &&
967 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
968 result = S.MaybeCreateExprWithCleanups(result);
969 copyExpr = result.take();
970 }
971 }
972
973 // We're currently at the declarer; go back to the closure.
974 functionScopesIndex++;
975 BlockScopeInfo *blockScope =
976 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
977
978 // Build a valid capture in this scope.
979 blockScope->Captures.push_back(
980 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
981 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
982
983 // Propagate that to inner captures if necessary.
984 return propagateCapture(S, functionScopesIndex,
985 blockScope->Captures.back());
986}
987
988static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
989 const DeclarationNameInfo &NameInfo,
990 bool byRef) {
991 assert(isa<VarDecl>(vd) && "capturing non-variable");
992
993 VarDecl *var = cast<VarDecl>(vd);
994 assert(var->hasLocalStorage() && "capturing non-local");
995 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
996
997 QualType exprType = var->getType().getNonReferenceType();
998
999 BlockDeclRefExpr *BDRE;
1000 if (!byRef) {
1001 // The variable will be bound by copy; make it const within the
1002 // closure, but record that this was done in the expression.
1003 bool constAdded = !exprType.isConstQualified();
1004 exprType.addConst();
1005
1006 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1007 NameInfo.getLoc(), false,
1008 constAdded);
1009 } else {
1010 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1011 NameInfo.getLoc(), true);
1012 }
1013
1014 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001015}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001016
John McCalldadc5752010-08-24 06:29:42 +00001017ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001018Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001019 SourceLocation Loc,
1020 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001021 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001022 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001023}
1024
John McCallf4cd4f92011-02-09 01:13:10 +00001025/// BuildDeclRefExpr - Build an expression that references a
1026/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001027ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001028Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001029 const DeclarationNameInfo &NameInfo,
1030 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001031 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001032
John McCall086a4642010-11-24 05:12:34 +00001033 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001034 SS? SS->getWithLocInContext(Context)
1035 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001036 D, NameInfo, Ty, VK);
1037
1038 // Just in case we're building an illegal pointer-to-member.
1039 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1040 E->setObjectKind(OK_BitField);
1041
1042 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001043}
1044
John McCallfeb624a2010-11-23 20:48:44 +00001045static ExprResult
1046BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1047 const CXXScopeSpec &SS, FieldDecl *Field,
1048 DeclAccessPair FoundDecl,
1049 const DeclarationNameInfo &MemberNameInfo);
1050
John McCalldadc5752010-08-24 06:29:42 +00001051ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001052Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1053 SourceLocation loc,
1054 IndirectFieldDecl *indirectField,
1055 Expr *baseObjectExpr,
1056 SourceLocation opLoc) {
1057 // First, build the expression that refers to the base object.
1058
1059 bool baseObjectIsPointer = false;
1060 Qualifiers baseQuals;
1061
1062 // Case 1: the base of the indirect field is not a field.
1063 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001064 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001065 if (baseVariable) {
1066 assert(baseVariable->getType()->isRecordType());
1067
1068 // In principle we could have a member access expression that
1069 // accesses an anonymous struct/union that's a static member of
1070 // the base object's class. However, under the current standard,
1071 // static data members cannot be anonymous structs or unions.
1072 // Supporting this is as easy as building a MemberExpr here.
1073 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1074
1075 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1076
1077 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001078 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001079 if (result.isInvalid()) return ExprError();
1080
1081 baseObjectExpr = result.take();
1082 baseObjectIsPointer = false;
1083 baseQuals = baseObjectExpr->getType().getQualifiers();
1084
1085 // Case 2: the base of the indirect field is a field and the user
1086 // wrote a member expression.
1087 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001088 // The caller provided the base object expression. Determine
1089 // whether its a pointer and whether it adds any qualifiers to the
1090 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001091 QualType objectType = baseObjectExpr->getType();
1092
1093 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1094 baseObjectIsPointer = true;
1095 objectType = ptr->getPointeeType();
1096 } else {
1097 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001098 }
John McCallf3a88602011-02-03 08:15:49 +00001099 baseQuals = objectType.getQualifiers();
1100
1101 // Case 3: the base of the indirect field is a field and we should
1102 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001103 } else {
1104 // We've found a member of an anonymous struct/union that is
1105 // inside a non-anonymous struct/union, so in a well-formed
1106 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001107 CXXMethodDecl *method = tryCaptureCXXThis();
1108 if (!method) {
1109 Diag(loc, diag::err_invalid_member_use_in_static_method)
1110 << indirectField->getDeclName();
1111 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001112 }
1113
John McCallf3a88602011-02-03 08:15:49 +00001114 // Our base object expression is "this".
1115 baseObjectExpr =
1116 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1117 /*isImplicit=*/ true);
1118 baseObjectIsPointer = true;
1119 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001120 }
1121
1122 // Build the implicit member references to the field of the
1123 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001124 Expr *result = baseObjectExpr;
1125 IndirectFieldDecl::chain_iterator
1126 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001127
John McCallf3a88602011-02-03 08:15:49 +00001128 // Build the first member access in the chain with full information.
1129 if (!baseVariable) {
1130 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001131
John McCallf3a88602011-02-03 08:15:49 +00001132 // FIXME: use the real found-decl info!
1133 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001134
John McCallf3a88602011-02-03 08:15:49 +00001135 // Make a nameInfo that properly uses the anonymous name.
1136 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001137
John McCallf3a88602011-02-03 08:15:49 +00001138 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001139 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001140 memberNameInfo).take();
1141 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001142
John McCallf3a88602011-02-03 08:15:49 +00001143 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001144 }
1145
John McCallf3a88602011-02-03 08:15:49 +00001146 // In all cases, we should now skip the first declaration in the chain.
1147 ++FI;
1148
Douglas Gregore10f36d2011-02-18 02:44:58 +00001149 while (FI != FEnd) {
1150 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001151
1152 // FIXME: these are somewhat meaningless
1153 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1154 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001155
1156 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001157 (FI == FEnd? SS : EmptySS), field,
1158 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001159 .take();
1160 }
1161
1162 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001163}
1164
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001165/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001166/// possibly a list of template arguments.
1167///
1168/// If this produces template arguments, it is permitted to call
1169/// DecomposeTemplateName.
1170///
1171/// This actually loses a lot of source location information for
1172/// non-standard name kinds; we should consider preserving that in
1173/// some way.
1174static void DecomposeUnqualifiedId(Sema &SemaRef,
1175 const UnqualifiedId &Id,
1176 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001177 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001178 const TemplateArgumentListInfo *&TemplateArgs) {
1179 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1180 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1181 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1182
1183 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1184 Id.TemplateId->getTemplateArgs(),
1185 Id.TemplateId->NumArgs);
1186 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1187 TemplateArgsPtr.release();
1188
John McCall3e56fd42010-08-23 07:28:44 +00001189 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001190 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1191 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001192 TemplateArgs = &Buffer;
1193 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001194 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001195 TemplateArgs = 0;
1196 }
1197}
1198
John McCall2d74de92009-12-01 22:10:20 +00001199/// Determines if the given class is provably not derived from all of
1200/// the prospective base classes.
1201static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1202 CXXRecordDecl *Record,
1203 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001204 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001205 return false;
1206
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001207 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001208 if (!RD) return false;
1209 Record = cast<CXXRecordDecl>(RD);
1210
John McCall2d74de92009-12-01 22:10:20 +00001211 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1212 E = Record->bases_end(); I != E; ++I) {
1213 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1214 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1215 if (!BaseRT) return false;
1216
1217 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001218 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1219 return false;
1220 }
1221
1222 return true;
1223}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001224
John McCall2d74de92009-12-01 22:10:20 +00001225enum IMAKind {
1226 /// The reference is definitely not an instance member access.
1227 IMA_Static,
1228
1229 /// The reference may be an implicit instance member access.
1230 IMA_Mixed,
1231
1232 /// The reference may be to an instance member, but it is invalid if
1233 /// so, because the context is not an instance method.
1234 IMA_Mixed_StaticContext,
1235
1236 /// The reference may be to an instance member, but it is invalid if
1237 /// so, because the context is from an unrelated class.
1238 IMA_Mixed_Unrelated,
1239
1240 /// The reference is definitely an implicit instance member access.
1241 IMA_Instance,
1242
1243 /// The reference may be to an unresolved using declaration.
1244 IMA_Unresolved,
1245
1246 /// The reference may be to an unresolved using declaration and the
1247 /// context is not an instance method.
1248 IMA_Unresolved_StaticContext,
1249
John McCall2d74de92009-12-01 22:10:20 +00001250 /// All possible referrents are instance members and the current
1251 /// context is not an instance method.
1252 IMA_Error_StaticContext,
1253
1254 /// All possible referrents are instance members of an unrelated
1255 /// class.
1256 IMA_Error_Unrelated
1257};
1258
1259/// The given lookup names class member(s) and is not being used for
1260/// an address-of-member expression. Classify the type of access
1261/// according to whether it's possible that this reference names an
1262/// instance member. This is best-effort; it is okay to
1263/// conservatively answer "yes", in which case some errors will simply
1264/// not be caught until template-instantiation.
1265static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1266 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001267 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001268
John McCall87fe5d52010-05-20 01:18:31 +00001269 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001270 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001271 (!isa<CXXMethodDecl>(DC) ||
1272 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001273
1274 if (R.isUnresolvableResult())
1275 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1276
1277 // Collect all the declaring classes of instance members we find.
1278 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001279 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001280 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001282 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001283
John McCalla8ae2222010-04-06 21:38:20 +00001284 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001285 if (dyn_cast<FieldDecl>(D))
1286 hasField = true;
1287
John McCall2d74de92009-12-01 22:10:20 +00001288 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001289 Classes.insert(R->getCanonicalDecl());
1290 }
1291 else
1292 hasNonInstance = true;
1293 }
1294
1295 // If we didn't find any instance members, it can't be an implicit
1296 // member reference.
1297 if (Classes.empty())
1298 return IMA_Static;
1299
1300 // If the current context is not an instance method, it can't be
1301 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001302 if (isStaticContext) {
1303 if (hasNonInstance)
1304 return IMA_Mixed_StaticContext;
1305
1306 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1307 // C++0x [expr.prim.general]p10:
1308 // An id-expression that denotes a non-static data member or non-static
1309 // member function of a class can only be used:
1310 // (...)
1311 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1312 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1313 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1314 if (isUnevaluatedExpression)
1315 return IMA_Mixed_StaticContext;
1316 }
1317
1318 return IMA_Error_StaticContext;
1319 }
John McCall2d74de92009-12-01 22:10:20 +00001320
1321 // If we can prove that the current context is unrelated to all the
1322 // declaring classes, it can't be an implicit member reference (in
1323 // which case it's an error if any of those members are selected).
1324 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001325 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001326 Classes))
1327 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1328
1329 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1330}
1331
1332/// Diagnose a reference to a field with no object available.
1333static void DiagnoseInstanceReference(Sema &SemaRef,
1334 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001335 NamedDecl *rep,
1336 const DeclarationNameInfo &nameInfo) {
1337 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001338 SourceRange Range(Loc);
1339 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1340
John McCallf3a88602011-02-03 08:15:49 +00001341 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001342 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1343 if (MD->isStatic()) {
1344 // "invalid use of member 'x' in static member function"
1345 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001346 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001347 return;
1348 }
1349 }
1350
1351 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001352 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001353 return;
1354 }
1355
1356 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001357}
1358
John McCalld681c392009-12-16 08:11:27 +00001359/// Diagnose an empty lookup.
1360///
1361/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001362bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1363 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001364 DeclarationName Name = R.getLookupName();
1365
John McCalld681c392009-12-16 08:11:27 +00001366 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001367 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001368 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1369 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001370 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001371 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001372 diagnostic_suggest = diag::err_undeclared_use_suggest;
1373 }
John McCalld681c392009-12-16 08:11:27 +00001374
Douglas Gregor598b08f2009-12-31 05:20:13 +00001375 // If the original lookup was an unqualified lookup, fake an
1376 // unqualified lookup. This is useful when (for example) the
1377 // original lookup would not have found something because it was a
1378 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001379 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001380 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001381 if (isa<CXXRecordDecl>(DC)) {
1382 LookupQualifiedName(R, DC);
1383
1384 if (!R.empty()) {
1385 // Don't give errors about ambiguities in this lookup.
1386 R.suppressDiagnostics();
1387
1388 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1389 bool isInstance = CurMethod &&
1390 CurMethod->isInstance() &&
1391 DC == CurMethod->getParent();
1392
1393 // Give a code modification hint to insert 'this->'.
1394 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1395 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001396 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001397 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1398 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001399 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001400 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001401 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001402 Diag(R.getNameLoc(), diagnostic) << Name
1403 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1404 QualType DepThisType = DepMethod->getThisType(Context);
1405 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1406 R.getNameLoc(), DepThisType, false);
1407 TemplateArgumentListInfo TList;
1408 if (ULE->hasExplicitTemplateArgs())
1409 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001410
Douglas Gregore16af532011-02-28 18:50:33 +00001411 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001412 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001413 CXXDependentScopeMemberExpr *DepExpr =
1414 CXXDependentScopeMemberExpr::Create(
1415 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001416 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001417 R.getLookupNameInfo(), &TList);
1418 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001419 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001420 // FIXME: we should be able to handle this case too. It is correct
1421 // to add this-> here. This is a workaround for PR7947.
1422 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001423 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001424 } else {
John McCalld681c392009-12-16 08:11:27 +00001425 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001426 }
John McCalld681c392009-12-16 08:11:27 +00001427
1428 // Do we really want to note all of these?
1429 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1430 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1431
1432 // Tell the callee to try to recover.
1433 return false;
1434 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001435
1436 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001437 }
1438 }
1439
Douglas Gregor598b08f2009-12-31 05:20:13 +00001440 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001441 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001442 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 if (!R.empty()) {
1444 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1445 if (SS.isEmpty())
1446 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1447 << FixItHint::CreateReplacement(R.getNameLoc(),
1448 R.getLookupName().getAsString());
1449 else
1450 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1451 << Name << computeDeclContext(SS, false) << R.getLookupName()
1452 << SS.getRange()
1453 << FixItHint::CreateReplacement(R.getNameLoc(),
1454 R.getLookupName().getAsString());
1455 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1456 Diag(ND->getLocation(), diag::note_previous_decl)
1457 << ND->getDeclName();
1458
1459 // Tell the callee to try to recover.
1460 return false;
1461 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001462
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001463 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1464 // FIXME: If we ended up with a typo for a type name or
1465 // Objective-C class name, we're in trouble because the parser
1466 // is in the wrong place to recover. Suggest the typo
1467 // correction, but don't make it a fix-it since we're not going
1468 // to recover well anyway.
1469 if (SS.isEmpty())
1470 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1471 else
1472 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1473 << Name << computeDeclContext(SS, false) << R.getLookupName()
1474 << SS.getRange();
1475
1476 // Don't try to recover; it won't work.
1477 return true;
1478 }
1479 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001480 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001481 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001482 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001483 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001484 else
Douglas Gregor25363982010-01-01 00:15:04 +00001485 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001486 << Name << computeDeclContext(SS, false) << Corrected
1487 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001488 return true;
1489 }
Douglas Gregor25363982010-01-01 00:15:04 +00001490 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001491 }
1492
1493 // Emit a special diagnostic for failed member lookups.
1494 // FIXME: computing the declaration context might fail here (?)
1495 if (!SS.isEmpty()) {
1496 Diag(R.getNameLoc(), diag::err_no_member)
1497 << Name << computeDeclContext(SS, false)
1498 << SS.getRange();
1499 return true;
1500 }
1501
John McCalld681c392009-12-16 08:11:27 +00001502 // Give up, we can't recover.
1503 Diag(R.getNameLoc(), diagnostic) << Name;
1504 return true;
1505}
1506
Douglas Gregor05fcf842010-11-02 20:36:02 +00001507ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1508 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001509 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1510 if (!IDecl)
1511 return 0;
1512 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1513 if (!ClassImpDecl)
1514 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001515 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001516 if (!property)
1517 return 0;
1518 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001519 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1520 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001521 return 0;
1522 return property;
1523}
1524
Douglas Gregor05fcf842010-11-02 20:36:02 +00001525bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1526 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1527 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1528 if (!IDecl)
1529 return false;
1530 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1531 if (!ClassImpDecl)
1532 return false;
1533 if (ObjCPropertyImplDecl *PIDecl
1534 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1535 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1536 PIDecl->getPropertyIvarDecl())
1537 return false;
1538
1539 return true;
1540}
1541
Fariborz Jahanian18722982010-07-17 00:59:30 +00001542static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001543 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001544 IdentifierInfo *II,
1545 SourceLocation NameLoc) {
1546 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001547 bool LookForIvars;
1548 if (Lookup.empty())
1549 LookForIvars = true;
1550 else if (CurMeth->isClassMethod())
1551 LookForIvars = false;
1552 else
1553 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001554 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1555 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001556 if (!LookForIvars)
1557 return 0;
1558
Fariborz Jahanian18722982010-07-17 00:59:30 +00001559 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1560 if (!IDecl)
1561 return 0;
1562 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001563 if (!ClassImpDecl)
1564 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001565 bool DynamicImplSeen = false;
1566 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1567 if (!property)
1568 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001569 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001570 DynamicImplSeen =
1571 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001572 // property implementation has a designated ivar. No need to assume a new
1573 // one.
1574 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1575 return 0;
1576 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001577 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001578 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1579 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001580 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001581 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001582 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001583 (Expr *)0, true);
1584 ClassImpDecl->addDecl(Ivar);
1585 IDecl->makeDeclVisibleInContext(Ivar, false);
1586 property->setPropertyIvarDecl(Ivar);
1587 return Ivar;
1588 }
1589 return 0;
1590}
1591
John McCalldadc5752010-08-24 06:29:42 +00001592ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001593 CXXScopeSpec &SS,
1594 UnqualifiedId &Id,
1595 bool HasTrailingLParen,
1596 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001597 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1598 "cannot be direct & operand and have a trailing lparen");
1599
1600 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001601 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001602
John McCall10eae182009-11-30 22:42:35 +00001603 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001604
1605 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001606 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001607 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001608 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001609
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001610 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001611 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001612 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001613
John McCalle66edc12009-11-24 19:00:30 +00001614 // C++ [temp.dep.expr]p3:
1615 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001616 // -- an identifier that was declared with a dependent type,
1617 // (note: handled after lookup)
1618 // -- a template-id that is dependent,
1619 // (note: handled in BuildTemplateIdExpr)
1620 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001621 // -- a nested-name-specifier that contains a class-name that
1622 // names a dependent type.
1623 // Determine whether this is a member of an unknown specialization;
1624 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001625 bool DependentID = false;
1626 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1627 Name.getCXXNameType()->isDependentType()) {
1628 DependentID = true;
1629 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001630 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001631 if (RequireCompleteDeclContext(SS, DC))
1632 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001633 } else {
1634 DependentID = true;
1635 }
1636 }
1637
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001638 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001640 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001641
Fariborz Jahanian86151342010-07-22 23:33:21 +00001642 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001643 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001644 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001645 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001646 // Lookup the template name again to correctly establish the context in
1647 // which it was found. This is really unfortunate as we already did the
1648 // lookup to determine that it was a template name in the first place. If
1649 // this becomes a performance hit, we can work harder to preserve those
1650 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001651 bool MemberOfUnknownSpecialization;
1652 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1653 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001654
1655 if (MemberOfUnknownSpecialization ||
1656 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1657 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1658 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001659 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001660 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001661 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001662
Douglas Gregora5226932011-02-04 13:35:07 +00001663 // If the result might be in a dependent base class, this is a dependent
1664 // id-expression.
1665 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1666 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1667 TemplateArgs);
1668
John McCalle66edc12009-11-24 19:00:30 +00001669 // If this reference is in an Objective-C method, then we need to do
1670 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001671 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001672 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001673 if (E.isInvalid())
1674 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001675
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001676 if (Expr *Ex = E.takeAs<Expr>())
1677 return Owned(Ex);
1678
1679 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001680 if (getLangOptions().ObjCDefaultSynthProperties &&
1681 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001682 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1683 if (const ObjCPropertyDecl *Property =
1684 canSynthesizeProvisionalIvar(II)) {
1685 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1686 Diag(Property->getLocation(), diag::note_property_declare);
1687 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001688 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1689 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001690 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001691 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001692 // for further use, this must be set to false if in class method.
1693 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001694 }
Chris Lattner59a25942008-03-31 00:36:02 +00001695 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001696
John McCalle66edc12009-11-24 19:00:30 +00001697 if (R.isAmbiguous())
1698 return ExprError();
1699
Douglas Gregor171c45a2009-02-18 21:56:37 +00001700 // Determine whether this name might be a candidate for
1701 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001702 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001703
John McCalle66edc12009-11-24 19:00:30 +00001704 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001705 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001706 // in C90, extension in C99, forbidden in C++).
1707 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1708 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1709 if (D) R.addDecl(D);
1710 }
1711
1712 // If this name wasn't predeclared and if this is not a function
1713 // call, diagnose the problem.
1714 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001715 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001716 return ExprError();
1717
1718 assert(!R.empty() &&
1719 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001720
1721 // If we found an Objective-C instance variable, let
1722 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001723 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001724 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1725 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001726 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001727 assert(E.isInvalid() || E.get());
1728 return move(E);
1729 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001730 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
John McCalle66edc12009-11-24 19:00:30 +00001733 // This is guaranteed from this point on.
1734 assert(!R.empty() || ADL);
1735
John McCall2d74de92009-12-01 22:10:20 +00001736 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001737 // C++ [class.mfct.non-static]p3:
1738 // When an id-expression that is not part of a class member access
1739 // syntax and not used to form a pointer to member is used in the
1740 // body of a non-static member function of class X, if name lookup
1741 // resolves the name in the id-expression to a non-static non-type
1742 // member of some class C, the id-expression is transformed into a
1743 // class member access expression using (*this) as the
1744 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001745 //
1746 // But we don't actually need to do this for '&' operands if R
1747 // resolved to a function or overloaded function set, because the
1748 // expression is ill-formed if it actually works out to be a
1749 // non-static member function:
1750 //
1751 // C++ [expr.ref]p4:
1752 // Otherwise, if E1.E2 refers to a non-static member function. . .
1753 // [t]he expression can be used only as the left-hand operand of a
1754 // member function call.
1755 //
1756 // There are other safeguards against such uses, but it's important
1757 // to get this right here so that we don't end up making a
1758 // spuriously dependent expression if we're inside a dependent
1759 // instance method.
John McCall57500772009-12-16 12:17:52 +00001760 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001761 bool MightBeImplicitMember;
1762 if (!isAddressOfOperand)
1763 MightBeImplicitMember = true;
1764 else if (!SS.isEmpty())
1765 MightBeImplicitMember = false;
1766 else if (R.isOverloadedResult())
1767 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001768 else if (R.isUnresolvableResult())
1769 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001770 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001771 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1772 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001773
1774 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001775 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001776 }
1777
John McCalle66edc12009-11-24 19:00:30 +00001778 if (TemplateArgs)
1779 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001780
John McCalle66edc12009-11-24 19:00:30 +00001781 return BuildDeclarationNameExpr(SS, R, ADL);
1782}
1783
John McCall57500772009-12-16 12:17:52 +00001784/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001785ExprResult
John McCall57500772009-12-16 12:17:52 +00001786Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1787 LookupResult &R,
1788 const TemplateArgumentListInfo *TemplateArgs) {
1789 switch (ClassifyImplicitMemberAccess(*this, R)) {
1790 case IMA_Instance:
1791 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1792
John McCall57500772009-12-16 12:17:52 +00001793 case IMA_Mixed:
1794 case IMA_Mixed_Unrelated:
1795 case IMA_Unresolved:
1796 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1797
1798 case IMA_Static:
1799 case IMA_Mixed_StaticContext:
1800 case IMA_Unresolved_StaticContext:
1801 if (TemplateArgs)
1802 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1803 return BuildDeclarationNameExpr(SS, R, false);
1804
1805 case IMA_Error_StaticContext:
1806 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001807 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1808 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001809 return ExprError();
1810 }
1811
1812 llvm_unreachable("unexpected instance member access kind");
1813 return ExprError();
1814}
1815
John McCall10eae182009-11-30 22:42:35 +00001816/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1817/// declaration name, generally during template instantiation.
1818/// There's a large number of things which don't need to be done along
1819/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001820ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001821Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001822 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001823 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001824 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001825 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001826
John McCall0b66eb32010-05-01 00:40:08 +00001827 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001828 return ExprError();
1829
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001830 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001831 LookupQualifiedName(R, DC);
1832
1833 if (R.isAmbiguous())
1834 return ExprError();
1835
1836 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001837 Diag(NameInfo.getLoc(), diag::err_no_member)
1838 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001839 return ExprError();
1840 }
1841
1842 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1843}
1844
1845/// LookupInObjCMethod - The parser has read a name in, and Sema has
1846/// detected that we're currently inside an ObjC method. Perform some
1847/// additional lookup.
1848///
1849/// Ideally, most of this would be done by lookup, but there's
1850/// actually quite a lot of extra work involved.
1851///
1852/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001853ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001854Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001855 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001856 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001857 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001858
John McCalle66edc12009-11-24 19:00:30 +00001859 // There are two cases to handle here. 1) scoped lookup could have failed,
1860 // in which case we should look for an ivar. 2) scoped lookup could have
1861 // found a decl, but that decl is outside the current instance method (i.e.
1862 // a global variable). In these two cases, we do a lookup for an ivar with
1863 // this name, if the lookup sucedes, we replace it our current decl.
1864
1865 // If we're in a class method, we don't normally want to look for
1866 // ivars. But if we don't find anything else, and there's an
1867 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001868 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001869
1870 bool LookForIvars;
1871 if (Lookup.empty())
1872 LookForIvars = true;
1873 else if (IsClassMethod)
1874 LookForIvars = false;
1875 else
1876 LookForIvars = (Lookup.isSingleResult() &&
1877 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001878 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001879 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001880 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001881 ObjCInterfaceDecl *ClassDeclared;
1882 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1883 // Diagnose using an ivar in a class method.
1884 if (IsClassMethod)
1885 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1886 << IV->getDeclName());
1887
1888 // If we're referencing an invalid decl, just return this as a silent
1889 // error node. The error diagnostic was already emitted on the decl.
1890 if (IV->isInvalidDecl())
1891 return ExprError();
1892
1893 // Check if referencing a field with __attribute__((deprecated)).
1894 if (DiagnoseUseOfDecl(IV, Loc))
1895 return ExprError();
1896
1897 // Diagnose the use of an ivar outside of the declaring class.
1898 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1899 ClassDeclared != IFace)
1900 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1901
1902 // FIXME: This should use a new expr for a direct reference, don't
1903 // turn this into Self->ivar, just return a BareIVarExpr or something.
1904 IdentifierInfo &II = Context.Idents.get("self");
1905 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001906 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001907 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001908 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001909 SelfName, false, false);
1910 if (SelfExpr.isInvalid())
1911 return ExprError();
1912
John Wiegley01296292011-04-08 18:41:53 +00001913 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1914 if (SelfExpr.isInvalid())
1915 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001916
John McCalle66edc12009-11-24 19:00:30 +00001917 MarkDeclarationReferenced(Loc, IV);
1918 return Owned(new (Context)
1919 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001920 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001921 }
Chris Lattner87313662010-04-12 05:10:17 +00001922 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001923 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001924 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001925 ObjCInterfaceDecl *ClassDeclared;
1926 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1927 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1928 IFace == ClassDeclared)
1929 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1930 }
1931 }
1932
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001933 if (Lookup.empty() && II && AllowBuiltinCreation) {
1934 // FIXME. Consolidate this with similar code in LookupName.
1935 if (unsigned BuiltinID = II->getBuiltinID()) {
1936 if (!(getLangOptions().CPlusPlus &&
1937 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1938 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1939 S, Lookup.isForRedeclaration(),
1940 Lookup.getNameLoc());
1941 if (D) Lookup.addDecl(D);
1942 }
1943 }
1944 }
John McCalle66edc12009-11-24 19:00:30 +00001945 // Sentinel value saying that we didn't do anything special.
1946 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001947}
John McCalld14a8642009-11-21 08:51:07 +00001948
John McCall16df1e52010-03-30 21:47:33 +00001949/// \brief Cast a base object to a member's actual type.
1950///
1951/// Logically this happens in three phases:
1952///
1953/// * First we cast from the base type to the naming class.
1954/// The naming class is the class into which we were looking
1955/// when we found the member; it's the qualifier type if a
1956/// qualifier was provided, and otherwise it's the base type.
1957///
1958/// * Next we cast from the naming class to the declaring class.
1959/// If the member we found was brought into a class's scope by
1960/// a using declaration, this is that class; otherwise it's
1961/// the class declaring the member.
1962///
1963/// * Finally we cast from the declaring class to the "true"
1964/// declaring class of the member. This conversion does not
1965/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001966ExprResult
1967Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001969 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001970 NamedDecl *Member) {
1971 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1972 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001973 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 QualType DestRecordType;
1976 QualType DestType;
1977 QualType FromRecordType;
1978 QualType FromType = From->getType();
1979 bool PointerConversions = false;
1980 if (isa<FieldDecl>(Member)) {
1981 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001982
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 if (FromType->getAs<PointerType>()) {
1984 DestType = Context.getPointerType(DestRecordType);
1985 FromRecordType = FromType->getPointeeType();
1986 PointerConversions = true;
1987 } else {
1988 DestType = DestRecordType;
1989 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001990 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001991 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1992 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001993 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001994
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 DestType = Method->getThisType(Context);
1996 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001997
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 if (FromType->getAs<PointerType>()) {
1999 FromRecordType = FromType->getPointeeType();
2000 PointerConversions = true;
2001 } else {
2002 FromRecordType = FromType;
2003 DestType = DestRecordType;
2004 }
2005 } else {
2006 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002007 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002009
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002010 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002011 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002012
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013 // If the unqualified types are the same, no conversion is necessary.
2014 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002015 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002016
John McCall16df1e52010-03-30 21:47:33 +00002017 SourceRange FromRange = From->getSourceRange();
2018 SourceLocation FromLoc = FromRange.getBegin();
2019
John McCall2536c6d2010-08-25 10:28:54 +00002020 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002021
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002023 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002024 // class name.
2025 //
2026 // If the member was a qualified name and the qualified referred to a
2027 // specific base subobject type, we'll cast to that intermediate type
2028 // first and then to the object in which the member is declared. That allows
2029 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2030 //
2031 // class Base { public: int x; };
2032 // class Derived1 : public Base { };
2033 // class Derived2 : public Base { };
2034 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2035 //
2036 // void VeryDerived::f() {
2037 // x = 17; // error: ambiguous base subobjects
2038 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2039 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002040 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002041 QualType QType = QualType(Qualifier->getAsType(), 0);
2042 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2043 assert(QType->isRecordType() && "lookup done with non-record type");
2044
2045 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2046
2047 // In C++98, the qualifier type doesn't actually have to be a base
2048 // type of the object type, in which case we just ignore it.
2049 // Otherwise build the appropriate casts.
2050 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002051 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002052 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002053 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002054 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002055
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002056 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002057 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002058 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2059 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002060
2061 FromType = QType;
2062 FromRecordType = QRecordType;
2063
2064 // If the qualifier type was the same as the destination type,
2065 // we're done.
2066 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002067 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002068 }
2069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002070
John McCall16df1e52010-03-30 21:47:33 +00002071 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002072
John McCall16df1e52010-03-30 21:47:33 +00002073 // If we actually found the member through a using declaration, cast
2074 // down to the using declaration's type.
2075 //
2076 // Pointer equality is fine here because only one declaration of a
2077 // class ever has member declarations.
2078 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2079 assert(isa<UsingShadowDecl>(FoundDecl));
2080 QualType URecordType = Context.getTypeDeclType(
2081 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2082
2083 // We only need to do this if the naming-class to declaring-class
2084 // conversion is non-trivial.
2085 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2086 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002087 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002088 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002089 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002090 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002091
John McCall16df1e52010-03-30 21:47:33 +00002092 QualType UType = URecordType;
2093 if (PointerConversions)
2094 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002095 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2096 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002097 FromType = UType;
2098 FromRecordType = URecordType;
2099 }
2100
2101 // We don't do access control for the conversion from the
2102 // declaring class to the true declaring class.
2103 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002104 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002105
John McCallcf142162010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002107 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2108 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002109 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002110 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002111
John Wiegley01296292011-04-08 18:41:53 +00002112 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2113 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002114}
Douglas Gregor3256d042009-06-30 15:47:41 +00002115
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002116/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002117static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002118 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002119 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002120 const DeclarationNameInfo &MemberNameInfo,
2121 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002122 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002123 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002124 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002125 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002126 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002127}
2128
John McCallfeb624a2010-11-23 20:48:44 +00002129static ExprResult
2130BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2131 const CXXScopeSpec &SS, FieldDecl *Field,
2132 DeclAccessPair FoundDecl,
2133 const DeclarationNameInfo &MemberNameInfo) {
2134 // x.a is an l-value if 'a' has a reference type. Otherwise:
2135 // x.a is an l-value/x-value/pr-value if the base is (and note
2136 // that *x is always an l-value), except that if the base isn't
2137 // an ordinary object then we must have an rvalue.
2138 ExprValueKind VK = VK_LValue;
2139 ExprObjectKind OK = OK_Ordinary;
2140 if (!IsArrow) {
2141 if (BaseExpr->getObjectKind() == OK_Ordinary)
2142 VK = BaseExpr->getValueKind();
2143 else
2144 VK = VK_RValue;
2145 }
2146 if (VK != VK_RValue && Field->isBitField())
2147 OK = OK_BitField;
2148
2149 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2150 QualType MemberType = Field->getType();
2151 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2152 MemberType = Ref->getPointeeType();
2153 VK = VK_LValue;
2154 } else {
2155 QualType BaseType = BaseExpr->getType();
2156 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2157
2158 Qualifiers BaseQuals = BaseType.getQualifiers();
2159
2160 // GC attributes are never picked up by members.
2161 BaseQuals.removeObjCGCAttr();
2162
2163 // CVR attributes from the base are picked up by members,
2164 // except that 'mutable' members don't pick up 'const'.
2165 if (Field->isMutable()) BaseQuals.removeConst();
2166
2167 Qualifiers MemberQuals
2168 = S.Context.getCanonicalType(MemberType).getQualifiers();
2169
2170 // TR 18037 does not allow fields to be declared with address spaces.
2171 assert(!MemberQuals.hasAddressSpace());
2172
2173 Qualifiers Combined = BaseQuals + MemberQuals;
2174 if (Combined != MemberQuals)
2175 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2176 }
2177
2178 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002179 ExprResult Base =
2180 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2181 FoundDecl, Field);
2182 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002183 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002184 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002185 Field, FoundDecl, MemberNameInfo,
2186 MemberType, VK, OK));
2187}
2188
John McCall2d74de92009-12-01 22:10:20 +00002189/// Builds an implicit member access expression. The current context
2190/// is known to be an instance method, and the given unqualified lookup
2191/// set is known to contain only instance members, at least one of which
2192/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002193ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002194Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2195 LookupResult &R,
2196 const TemplateArgumentListInfo *TemplateArgs,
2197 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002198 assert(!R.empty() && !R.isAmbiguous());
2199
John McCallf3a88602011-02-03 08:15:49 +00002200 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002201
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002202 // We may have found a field within an anonymous union or struct
2203 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002204 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002205 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002206 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002207
John McCallf3a88602011-02-03 08:15:49 +00002208 // If this is known to be an instance access, go ahead and build an
2209 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002210 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002211 CXXMethodDecl *method = tryCaptureCXXThis();
2212 assert(method && "didn't correctly pre-flight capture of 'this'");
2213
2214 QualType thisType = method->getThisType(Context);
2215 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002216 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002217 SourceLocation Loc = R.getNameLoc();
2218 if (SS.getRange().isValid())
2219 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002220 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002221 }
2222
John McCallf3a88602011-02-03 08:15:49 +00002223 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002224 /*OpLoc*/ SourceLocation(),
2225 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002226 SS,
2227 /*FirstQualifierInScope*/ 0,
2228 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002229}
2230
John McCalle66edc12009-11-24 19:00:30 +00002231bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002232 const LookupResult &R,
2233 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002234 // Only when used directly as the postfix-expression of a call.
2235 if (!HasTrailingLParen)
2236 return false;
2237
2238 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002239 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002240 return false;
2241
2242 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002243 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002244 return false;
2245
2246 // Turn off ADL when we find certain kinds of declarations during
2247 // normal lookup:
2248 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2249 NamedDecl *D = *I;
2250
2251 // C++0x [basic.lookup.argdep]p3:
2252 // -- a declaration of a class member
2253 // Since using decls preserve this property, we check this on the
2254 // original decl.
John McCall57500772009-12-16 12:17:52 +00002255 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002256 return false;
2257
2258 // C++0x [basic.lookup.argdep]p3:
2259 // -- a block-scope function declaration that is not a
2260 // using-declaration
2261 // NOTE: we also trigger this for function templates (in fact, we
2262 // don't check the decl type at all, since all other decl types
2263 // turn off ADL anyway).
2264 if (isa<UsingShadowDecl>(D))
2265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2266 else if (D->getDeclContext()->isFunctionOrMethod())
2267 return false;
2268
2269 // C++0x [basic.lookup.argdep]p3:
2270 // -- a declaration that is neither a function or a function
2271 // template
2272 // And also for builtin functions.
2273 if (isa<FunctionDecl>(D)) {
2274 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2275
2276 // But also builtin functions.
2277 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2278 return false;
2279 } else if (!isa<FunctionTemplateDecl>(D))
2280 return false;
2281 }
2282
2283 return true;
2284}
2285
2286
John McCalld14a8642009-11-21 08:51:07 +00002287/// Diagnoses obvious problems with the use of the given declaration
2288/// as an expression. This is only actually called for lookups that
2289/// were not overloaded, and it doesn't promise that the declaration
2290/// will in fact be used.
2291static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2292 if (isa<TypedefDecl>(D)) {
2293 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2294 return true;
2295 }
2296
2297 if (isa<ObjCInterfaceDecl>(D)) {
2298 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2299 return true;
2300 }
2301
2302 if (isa<NamespaceDecl>(D)) {
2303 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2304 return true;
2305 }
2306
2307 return false;
2308}
2309
John McCalldadc5752010-08-24 06:29:42 +00002310ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002311Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002312 LookupResult &R,
2313 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002314 // If this is a single, fully-resolved result and we don't need ADL,
2315 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002316 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002317 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2318 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002319
2320 // We only need to check the declaration if there's exactly one
2321 // result, because in the overloaded case the results can only be
2322 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002323 if (R.isSingleResult() &&
2324 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002325 return ExprError();
2326
John McCall58cc69d2010-01-27 01:50:18 +00002327 // Otherwise, just build an unresolved lookup expression. Suppress
2328 // any lookup-related diagnostics; we'll hash these out later, when
2329 // we've picked a target.
2330 R.suppressDiagnostics();
2331
John McCalld14a8642009-11-21 08:51:07 +00002332 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002333 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002334 SS.getWithLocInContext(Context),
2335 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002336 NeedsADL, R.isOverloadedResult(),
2337 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002338
2339 return Owned(ULE);
2340}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002341
John McCalld14a8642009-11-21 08:51:07 +00002342/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002343ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002344Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002345 const DeclarationNameInfo &NameInfo,
2346 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002347 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002348 assert(!isa<FunctionTemplateDecl>(D) &&
2349 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002350
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002351 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002352 if (CheckDeclInExpr(*this, Loc, D))
2353 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002354
Douglas Gregore7488b92009-12-01 16:58:18 +00002355 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2356 // Specifically diagnose references to class templates that are missing
2357 // a template argument list.
2358 Diag(Loc, diag::err_template_decl_ref)
2359 << Template << SS.getRange();
2360 Diag(Template->getLocation(), diag::note_template_decl_here);
2361 return ExprError();
2362 }
2363
2364 // Make sure that we're referring to a value.
2365 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2366 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002367 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002368 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002369 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002370 return ExprError();
2371 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002372
Douglas Gregor171c45a2009-02-18 21:56:37 +00002373 // Check whether this declaration can be used. Note that we suppress
2374 // this check when we're going to perform argument-dependent lookup
2375 // on this function name, because this might not be the function
2376 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002377 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002378 return ExprError();
2379
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002380 // Only create DeclRefExpr's for valid Decl's.
2381 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002382 return ExprError();
2383
John McCallf3a88602011-02-03 08:15:49 +00002384 // Handle members of anonymous structs and unions. If we got here,
2385 // and the reference is to a class member indirect field, then this
2386 // must be the subject of a pointer-to-member expression.
2387 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2388 if (!indirectField->isCXXClassMember())
2389 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2390 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002391
Chris Lattner2a9d9892008-10-20 05:16:36 +00002392 // If the identifier reference is inside a block, and it refers to a value
2393 // that is outside the block, create a BlockDeclRefExpr instead of a
2394 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2395 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002396 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002397 // We do not do this for things like enum constants, global variables, etc,
2398 // as they do not get snapshotted.
2399 //
John McCall351762c2011-02-07 10:33:21 +00002400 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002401 case CR_Error:
2402 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002403
John McCallc63de662011-02-02 13:00:07 +00002404 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002405 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2406 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2407
2408 case CR_CaptureByRef:
2409 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2410 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002411
2412 case CR_NoCapture: {
2413 // If this reference is not in a block or if the referenced
2414 // variable is within the block, create a normal DeclRefExpr.
2415
2416 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002417 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002418
2419 switch (D->getKind()) {
2420 // Ignore all the non-ValueDecl kinds.
2421#define ABSTRACT_DECL(kind)
2422#define VALUE(type, base)
2423#define DECL(type, base) \
2424 case Decl::type:
2425#include "clang/AST/DeclNodes.inc"
2426 llvm_unreachable("invalid value decl kind");
2427 return ExprError();
2428
2429 // These shouldn't make it here.
2430 case Decl::ObjCAtDefsField:
2431 case Decl::ObjCIvar:
2432 llvm_unreachable("forming non-member reference to ivar?");
2433 return ExprError();
2434
2435 // Enum constants are always r-values and never references.
2436 // Unresolved using declarations are dependent.
2437 case Decl::EnumConstant:
2438 case Decl::UnresolvedUsingValue:
2439 valueKind = VK_RValue;
2440 break;
2441
2442 // Fields and indirect fields that got here must be for
2443 // pointer-to-member expressions; we just call them l-values for
2444 // internal consistency, because this subexpression doesn't really
2445 // exist in the high-level semantics.
2446 case Decl::Field:
2447 case Decl::IndirectField:
2448 assert(getLangOptions().CPlusPlus &&
2449 "building reference to field in C?");
2450
2451 // These can't have reference type in well-formed programs, but
2452 // for internal consistency we do this anyway.
2453 type = type.getNonReferenceType();
2454 valueKind = VK_LValue;
2455 break;
2456
2457 // Non-type template parameters are either l-values or r-values
2458 // depending on the type.
2459 case Decl::NonTypeTemplateParm: {
2460 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2461 type = reftype->getPointeeType();
2462 valueKind = VK_LValue; // even if the parameter is an r-value reference
2463 break;
2464 }
2465
2466 // For non-references, we need to strip qualifiers just in case
2467 // the template parameter was declared as 'const int' or whatever.
2468 valueKind = VK_RValue;
2469 type = type.getUnqualifiedType();
2470 break;
2471 }
2472
2473 case Decl::Var:
2474 // In C, "extern void blah;" is valid and is an r-value.
2475 if (!getLangOptions().CPlusPlus &&
2476 !type.hasQualifiers() &&
2477 type->isVoidType()) {
2478 valueKind = VK_RValue;
2479 break;
2480 }
2481 // fallthrough
2482
2483 case Decl::ImplicitParam:
2484 case Decl::ParmVar:
2485 // These are always l-values.
2486 valueKind = VK_LValue;
2487 type = type.getNonReferenceType();
2488 break;
2489
2490 case Decl::Function: {
2491 // Functions are l-values in C++.
2492 if (getLangOptions().CPlusPlus) {
2493 valueKind = VK_LValue;
2494 break;
2495 }
2496
2497 // C99 DR 316 says that, if a function type comes from a
2498 // function definition (without a prototype), that type is only
2499 // used for checking compatibility. Therefore, when referencing
2500 // the function, we pretend that we don't have the full function
2501 // type.
2502 if (!cast<FunctionDecl>(VD)->hasPrototype())
2503 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2504 type = Context.getFunctionNoProtoType(proto->getResultType(),
2505 proto->getExtInfo());
2506
2507 // Functions are r-values in C.
2508 valueKind = VK_RValue;
2509 break;
2510 }
2511
2512 case Decl::CXXMethod:
2513 // C++ methods are l-values if static, r-values if non-static.
2514 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2515 valueKind = VK_LValue;
2516 break;
2517 }
2518 // fallthrough
2519
2520 case Decl::CXXConversion:
2521 case Decl::CXXDestructor:
2522 case Decl::CXXConstructor:
2523 valueKind = VK_RValue;
2524 break;
2525 }
2526
2527 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2528 }
2529
John McCallc63de662011-02-02 13:00:07 +00002530 }
John McCall7decc9e2010-11-18 06:31:45 +00002531
John McCall351762c2011-02-07 10:33:21 +00002532 llvm_unreachable("unknown capture result");
2533 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002534}
Chris Lattnere168f762006-11-10 05:29:30 +00002535
John McCalldadc5752010-08-24 06:29:42 +00002536ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002537 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002538 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002539
Chris Lattnere168f762006-11-10 05:29:30 +00002540 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002541 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002542 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2543 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2544 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002545 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002546
Chris Lattnera81a0272008-01-12 08:14:25 +00002547 // Pre-defined identifiers are of type char[x], where x is the length of the
2548 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002549
Anders Carlsson2fb08242009-09-08 18:24:21 +00002550 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002551 if (!currentDecl && getCurBlock())
2552 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002553 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002554 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002555 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002556 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002557
Anders Carlsson0b209a82009-09-11 01:22:35 +00002558 QualType ResTy;
2559 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2560 ResTy = Context.DependentTy;
2561 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002562 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002563
Anders Carlsson0b209a82009-09-11 01:22:35 +00002564 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002565 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002566 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2567 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002568 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002569}
2570
John McCalldadc5752010-08-24 06:29:42 +00002571ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002572 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002573 bool Invalid = false;
2574 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2575 if (Invalid)
2576 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002578 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2579 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002580 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002582
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002583 QualType Ty;
2584 if (!getLangOptions().CPlusPlus)
2585 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2586 else if (Literal.isWide())
2587 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002588 else if (Literal.isMultiChar())
2589 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002590 else
2591 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002592
Sebastian Redl20614a72009-01-20 22:23:13 +00002593 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2594 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002595 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002596}
2597
John McCalldadc5752010-08-24 06:29:42 +00002598ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002599 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002600 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2601 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002602 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002603 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002604 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002605 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002606 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002607
Chris Lattner23b7eb62007-06-15 23:05:46 +00002608 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002609 // Add padding so that NumericLiteralParser can overread by one character.
2610 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002611 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002612
Chris Lattner67ca9252007-05-21 01:08:44 +00002613 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002614 bool Invalid = false;
2615 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2616 if (Invalid)
2617 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002618
Mike Stump11289f42009-09-09 15:08:12 +00002619 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002620 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002621 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622 return ExprError();
2623
Chris Lattner1c20a172007-08-26 03:42:43 +00002624 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002625
Chris Lattner1c20a172007-08-26 03:42:43 +00002626 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002627 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002628 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002629 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002630 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002631 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002632 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002633 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002634
2635 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2636
John McCall53b93a02009-12-24 09:08:04 +00002637 using llvm::APFloat;
2638 APFloat Val(Format);
2639
2640 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002641
2642 // Overflow is always an error, but underflow is only an error if
2643 // we underflowed to zero (APFloat reports denormals as underflow).
2644 if ((result & APFloat::opOverflow) ||
2645 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002646 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002647 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002648 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002649 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002650 APFloat::getLargest(Format).toString(buffer);
2651 } else {
John McCall62abc942010-02-26 23:35:57 +00002652 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002653 APFloat::getSmallest(Format).toString(buffer);
2654 }
2655
2656 Diag(Tok.getLocation(), diagnostic)
2657 << Ty
2658 << llvm::StringRef(buffer.data(), buffer.size());
2659 }
2660
2661 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002662 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002663
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002664 if (Ty == Context.DoubleTy) {
2665 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002666 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002667 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2668 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002669 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002670 }
2671 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002672 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002673 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002674 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002675 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002676
Neil Boothac582c52007-08-29 22:00:19 +00002677 // long long is a C99 feature.
2678 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002679 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002680 Diag(Tok.getLocation(), diag::ext_longlong);
2681
Chris Lattner67ca9252007-05-21 01:08:44 +00002682 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002683 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002684
Chris Lattner67ca9252007-05-21 01:08:44 +00002685 if (Literal.GetIntegerValue(ResultVal)) {
2686 // If this value didn't fit into uintmax_t, warn and force to ull.
2687 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002688 Ty = Context.UnsignedLongLongTy;
2689 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002690 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002691 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002692 // If this value fits into a ULL, try to figure out what else it fits into
2693 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002694
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2696 // be an unsigned int.
2697 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2698
2699 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002701 if (!Literal.isLong && !Literal.isLongLong) {
2702 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002703 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002704
Chris Lattner67ca9252007-05-21 01:08:44 +00002705 // Does it fit in a unsigned int?
2706 if (ResultVal.isIntN(IntSize)) {
2707 // Does it fit in a signed int?
2708 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002709 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002710 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002711 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002712 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002713 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002714 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002715
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002719
Chris Lattner67ca9252007-05-21 01:08:44 +00002720 // Does it fit in a unsigned long?
2721 if (ResultVal.isIntN(LongSize)) {
2722 // Does it fit in a signed long?
2723 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002724 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002725 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002726 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002727 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002728 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002729 }
2730
Chris Lattner67ca9252007-05-21 01:08:44 +00002731 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002732 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002733 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002734
Chris Lattner67ca9252007-05-21 01:08:44 +00002735 // Does it fit in a unsigned long long?
2736 if (ResultVal.isIntN(LongLongSize)) {
2737 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002738 // To be compatible with MSVC, hex integer literals ending with the
2739 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002740 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2741 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002742 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002743 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002744 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002745 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002746 }
2747 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002748
Chris Lattner67ca9252007-05-21 01:08:44 +00002749 // If we still couldn't decide a type, we probably have something that
2750 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002751 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002752 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002753 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002754 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002755 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002756
Chris Lattner55258cf2008-05-09 05:59:00 +00002757 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002758 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002759 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002760 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002761 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002762
Chris Lattner1c20a172007-08-26 03:42:43 +00002763 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2764 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002765 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002766 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002767
2768 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002769}
2770
John McCalldadc5752010-08-24 06:29:42 +00002771ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002772 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002773 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002774 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002775}
2776
Steve Naroff71b59a92007-06-04 22:22:31 +00002777/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002778/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002779bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2780 SourceLocation OpLoc,
2781 SourceRange ExprRange,
2782 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002783 if (exprType->isDependentType())
2784 return false;
2785
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002786 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2787 // the result is the size of the referenced type."
2788 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2789 // result shall be the alignment of the referenced type."
2790 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2791 exprType = Ref->getPointeeType();
2792
Peter Collingbournee190dee2011-03-11 19:24:49 +00002793 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2794 // scalar or vector data type argument..."
2795 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2796 // type (C99 6.2.5p18) or void.
2797 if (ExprKind == UETT_VecStep) {
2798 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2799 exprType->isVectorType())) {
2800 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2801 << exprType << ExprRange;
2802 return true;
2803 }
2804 }
2805
Steve Naroff043d45d2007-05-15 02:32:35 +00002806 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002807 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002808 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002809 if (ExprKind == UETT_SizeOf)
2810 Diag(OpLoc, diag::ext_sizeof_function_type)
2811 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002812 return false;
2813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
Peter Collingbournee190dee2011-03-11 19:24:49 +00002815 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2816 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002817 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002818 if (ExprKind != UETT_VecStep)
2819 Diag(OpLoc, diag::ext_sizeof_void_type)
2820 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002821 return false;
2822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Chris Lattner62975a72009-04-24 00:30:45 +00002824 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002825 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002826 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002827 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002828
Chris Lattner62975a72009-04-24 00:30:45 +00002829 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002830 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002831 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002832 << exprType << (ExprKind == UETT_SizeOf)
2833 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002834 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002835 }
Mike Stump11289f42009-09-09 15:08:12 +00002836
Chris Lattner62975a72009-04-24 00:30:45 +00002837 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002838}
2839
John McCall36e7fe32010-10-12 00:20:44 +00002840static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2841 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002842 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002843
Mike Stump11289f42009-09-09 15:08:12 +00002844 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002845 if (isa<DeclRefExpr>(E))
2846 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002847
2848 // Cannot know anything else if the expression is dependent.
2849 if (E->isTypeDependent())
2850 return false;
2851
Douglas Gregor71235ec2009-05-02 02:18:30 +00002852 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002853 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002854 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002855 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002856
2857 // Alignment of a field access is always okay, so long as it isn't a
2858 // bit-field.
2859 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002860 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002861 return false;
2862
Peter Collingbournee190dee2011-03-11 19:24:49 +00002863 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2864 UETT_AlignOf);
2865}
2866
2867bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2868 SourceRange ExprRange) {
2869 E = E->IgnoreParens();
2870
2871 // Cannot know anything else if the expression is dependent.
2872 if (E->isTypeDependent())
2873 return false;
2874
2875 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2876 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002877}
2878
Douglas Gregor0950e412009-03-13 21:01:28 +00002879/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002880ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002881Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2882 SourceLocation OpLoc,
2883 UnaryExprOrTypeTrait ExprKind,
2884 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002885 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002886 return ExprError();
2887
John McCallbcd03502009-12-07 02:54:59 +00002888 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002889
Douglas Gregor0950e412009-03-13 21:01:28 +00002890 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002891 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002892 return ExprError();
2893
2894 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002895 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2896 Context.getSizeType(),
2897 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002898}
2899
2900/// \brief Build a sizeof or alignof expression given an expression
2901/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002902ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002903Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2904 UnaryExprOrTypeTrait ExprKind,
2905 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 // Verify that the operand is valid.
2907 bool isInvalid = false;
2908 if (E->isTypeDependent()) {
2909 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002910 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002911 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002912 } else if (ExprKind == UETT_VecStep) {
2913 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002914 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002915 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2916 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002917 } else if (E->getType()->isPlaceholderType()) {
2918 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2919 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002920 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002921 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002922 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2923 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002924 }
2925
2926 if (isInvalid)
2927 return ExprError();
2928
2929 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002930 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2931 Context.getSizeType(),
2932 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002933}
2934
Peter Collingbournee190dee2011-03-11 19:24:49 +00002935/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2936/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002937/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002938ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002939Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2940 UnaryExprOrTypeTrait ExprKind, bool isType,
2941 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002942 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002943 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002944
Sebastian Redl6f282892008-11-11 17:56:53 +00002945 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002946 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002947 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002948 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002949 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002950
Douglas Gregor0950e412009-03-13 21:01:28 +00002951 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002952 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002953 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2954 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002955
Douglas Gregor0950e412009-03-13 21:01:28 +00002956 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002957}
2958
John Wiegley01296292011-04-08 18:41:53 +00002959static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002960 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002961 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002962 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002963
John McCall34376a62010-12-04 03:47:34 +00002964 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002965 if (V.get()->getObjectKind() != OK_Ordinary) {
2966 V = S.DefaultLvalueConversion(V.take());
2967 if (V.isInvalid())
2968 return QualType();
2969 }
John McCall34376a62010-12-04 03:47:34 +00002970
Chris Lattnere267f5d2007-08-26 05:39:26 +00002971 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002972 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002973 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Chris Lattnere267f5d2007-08-26 05:39:26 +00002975 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002976 if (V.get()->getType()->isArithmeticType())
2977 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002978
John McCall36226622010-10-12 02:09:17 +00002979 // Test for placeholders.
John Wiegley01296292011-04-08 18:41:53 +00002980 ExprResult PR = S.CheckPlaceholderExpr(V.get(), Loc);
John McCall36226622010-10-12 02:09:17 +00002981 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002982 if (PR.get() != V.get()) {
2983 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002984 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002985 }
2986
Chris Lattnere267f5d2007-08-26 05:39:26 +00002987 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002988 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002989 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002990 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002991}
2992
2993
Chris Lattnere168f762006-11-10 05:29:30 +00002994
John McCalldadc5752010-08-24 06:29:42 +00002995ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002996Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002997 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002998 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002999 switch (Kind) {
3000 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003001 case tok::plusplus: Opc = UO_PostInc; break;
3002 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003003 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003004
John McCallb268a282010-08-23 23:25:46 +00003005 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003006}
3007
John McCall4bc41ae2010-11-18 19:01:18 +00003008/// Expressions of certain arbitrary types are forbidden by C from
3009/// having l-value type. These are:
3010/// - 'void', but not qualified void
3011/// - function types
3012///
3013/// The exact rule here is C99 6.3.2.1:
3014/// An lvalue is an expression with an object type or an incomplete
3015/// type other than void.
3016static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3017 return ((T->isVoidType() && !T.hasQualifiers()) ||
3018 T->isFunctionType());
3019}
3020
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
John McCallb268a282010-08-23 23:25:46 +00003022Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3023 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003024 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003025 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003026 if (Result.isInvalid()) return ExprError();
3027 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003028
John McCallb268a282010-08-23 23:25:46 +00003029 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Douglas Gregor40412ac2008-11-19 17:17:41 +00003031 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003032 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003033 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003034 Context.DependentTy,
3035 VK_LValue, OK_Ordinary,
3036 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003037 }
3038
Mike Stump11289f42009-09-09 15:08:12 +00003039 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003040 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003041 LHSExp->getType()->isEnumeralType() ||
3042 RHSExp->getType()->isRecordType() ||
3043 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003044 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003045 }
3046
John McCallb268a282010-08-23 23:25:46 +00003047 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003048}
3049
3050
John McCalldadc5752010-08-24 06:29:42 +00003051ExprResult
John McCallb268a282010-08-23 23:25:46 +00003052Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3053 Expr *Idx, SourceLocation RLoc) {
3054 Expr *LHSExp = Base;
3055 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003056
Chris Lattner36d572b2007-07-16 00:14:47 +00003057 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003058 if (!LHSExp->getType()->getAs<VectorType>()) {
3059 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3060 if (Result.isInvalid())
3061 return ExprError();
3062 LHSExp = Result.take();
3063 }
3064 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3065 if (Result.isInvalid())
3066 return ExprError();
3067 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003068
Chris Lattner36d572b2007-07-16 00:14:47 +00003069 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003070 ExprValueKind VK = VK_LValue;
3071 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003072
Steve Naroffc1aadb12007-03-28 21:49:40 +00003073 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003074 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003075 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003076 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003077 Expr *BaseExpr, *IndexExpr;
3078 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003079 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003083 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003086 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003087 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003088 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003089 BaseExpr = RHSExp;
3090 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003091 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003092 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003093 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003094 BaseExpr = LHSExp;
3095 IndexExpr = RHSExp;
3096 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003097 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003098 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003099 // Handle the uncommon case of "123[Ptr]".
3100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
3102 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003103 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003104 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003105 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003106 VK = LHSExp->getValueKind();
3107 if (VK != VK_RValue)
3108 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003109
Chris Lattner36d572b2007-07-16 00:14:47 +00003110 // FIXME: need to deal with const...
3111 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003112 } else if (LHSTy->isArrayType()) {
3113 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003114 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003115 // wasn't promoted because of the C90 rule that doesn't
3116 // allow promoting non-lvalue arrays. Warn, then
3117 // force the promotion here.
3118 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3119 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003120 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3121 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003122 LHSTy = LHSExp->getType();
3123
3124 BaseExpr = LHSExp;
3125 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003126 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003127 } else if (RHSTy->isArrayType()) {
3128 // Same as previous, except for 123[f().a] case
3129 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3130 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003131 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3132 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003133 RHSTy = RHSExp->getType();
3134
3135 BaseExpr = RHSExp;
3136 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003137 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003138 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003139 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3140 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003142 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003143 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003144 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3145 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003146
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003147 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003148 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3149 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003150 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3151
Douglas Gregorac1fb652009-03-24 19:52:54 +00003152 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003153 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3154 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003155 // incomplete types are not object types.
3156 if (ResultType->isFunctionType()) {
3157 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3158 << ResultType << BaseExpr->getSourceRange();
3159 return ExprError();
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003162 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3163 // GNU extension: subscripting on pointer to void
3164 Diag(LLoc, diag::ext_gnu_void_ptr)
3165 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003166
3167 // C forbids expressions of unqualified void type from being l-values.
3168 // See IsCForbiddenLValueType.
3169 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003170 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003171 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003172 PDiag(diag::err_subscript_incomplete_type)
3173 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003174 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003175
Chris Lattner62975a72009-04-24 00:30:45 +00003176 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003177 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003178 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3179 << ResultType << BaseExpr->getSourceRange();
3180 return ExprError();
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
John McCall4bc41ae2010-11-18 19:01:18 +00003183 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3184 !IsCForbiddenLValueType(Context, ResultType));
3185
Mike Stump4e1f26a2009-02-19 03:04:26 +00003186 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003187 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003188}
3189
John McCall4bc41ae2010-11-18 19:01:18 +00003190/// Check an ext-vector component access expression.
3191///
3192/// VK should be set in advance to the value kind of the base
3193/// expression.
3194static QualType
3195CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3196 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003197 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003198 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3199 // see FIXME there.
3200 //
3201 // FIXME: This logic can be greatly simplified by splitting it along
3202 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003203 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003204
Steve Narofff8fd09e2007-07-27 22:15:19 +00003205 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003206 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003207
Mike Stump4e1f26a2009-02-19 03:04:26 +00003208 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003209 // special names that indicate a subset of exactly half the elements are
3210 // to be selected.
3211 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003212
Nate Begemanbb70bf62009-01-18 01:47:54 +00003213 // This flag determines whether or not CompName has an 's' char prefix,
3214 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003215 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003216
John McCall4bc41ae2010-11-18 19:01:18 +00003217 bool HasRepeated = false;
3218 bool HasIndex[16] = {};
3219
3220 int Idx;
3221
Nate Begemanf322eab2008-05-09 06:41:27 +00003222 // Check that we've found one of the special components, or that the component
3223 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003224 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003225 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3226 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003227 } else if (!HexSwizzle &&
3228 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3229 do {
3230 if (HasIndex[Idx]) HasRepeated = true;
3231 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003232 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003233 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3234 } else {
3235 if (HexSwizzle) compStr++;
3236 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3237 if (HasIndex[Idx]) HasRepeated = true;
3238 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003239 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003240 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003241 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003242
Mike Stump4e1f26a2009-02-19 03:04:26 +00003243 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003244 // We didn't get to the end of the string. This means the component names
3245 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003246 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003247 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003248 return QualType();
3249 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003250
Nate Begemanbb70bf62009-01-18 01:47:54 +00003251 // Ensure no component accessor exceeds the width of the vector type it
3252 // operates on.
3253 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003254 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003255
3256 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003257 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003258
3259 while (*compStr) {
3260 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003261 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003262 << baseType << SourceRange(CompLoc);
3263 return QualType();
3264 }
3265 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003266 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003267
Steve Narofff8fd09e2007-07-27 22:15:19 +00003268 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003269 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003270 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003271 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003272 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003273 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003274 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003275 if (HexSwizzle)
3276 CompSize--;
3277
Steve Narofff8fd09e2007-07-27 22:15:19 +00003278 if (CompSize == 1)
3279 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003280
John McCall4bc41ae2010-11-18 19:01:18 +00003281 if (HasRepeated) VK = VK_RValue;
3282
3283 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003284 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003285 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003286 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3287 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3288 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003289 }
3290 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003291}
3292
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003293static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003294 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003295 const Selector &Sel,
3296 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003297 if (Member)
3298 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3299 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003300 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003301 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003302
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003303 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3304 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003305 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3306 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003307 return D;
3308 }
3309 return 0;
3310}
3311
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003312static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3313 IdentifierInfo *Member,
3314 const Selector &Sel,
3315 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003316 // Check protocols on qualified interfaces.
3317 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003318 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003319 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003320 if (Member)
3321 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3322 GDecl = PD;
3323 break;
3324 }
3325 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003326 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003327 GDecl = OMD;
3328 break;
3329 }
3330 }
3331 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003332 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003333 E = QIdTy->qual_end(); I != E; ++I) {
3334 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003335 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3336 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003337 if (GDecl)
3338 return GDecl;
3339 }
3340 }
3341 return GDecl;
3342}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003343
John McCalldadc5752010-08-24 06:29:42 +00003344ExprResult
John McCallb268a282010-08-23 23:25:46 +00003345Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003346 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003347 const CXXScopeSpec &SS,
3348 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003349 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003350 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003351 // Even in dependent contexts, try to diagnose base expressions with
3352 // obviously wrong types, e.g.:
3353 //
3354 // T* t;
3355 // t.f;
3356 //
3357 // In Obj-C++, however, the above expression is valid, since it could be
3358 // accessing the 'f' property if T is an Obj-C interface. The extra check
3359 // allows this, while still reporting an error if T is a struct pointer.
3360 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003361 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003362 if (PT && (!getLangOptions().ObjC1 ||
3363 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003364 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003365 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003366 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003367 return ExprError();
3368 }
3369 }
3370
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003371 assert(BaseType->isDependentType() ||
3372 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003373 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003374
3375 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3376 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003377 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003378 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003379 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003380 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003381 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003382}
3383
3384/// We know that the given qualified member reference points only to
3385/// declarations which do not belong to the static type of the base
3386/// expression. Diagnose the problem.
3387static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3388 Expr *BaseExpr,
3389 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003390 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003391 NamedDecl *rep,
3392 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003393 // If this is an implicit member access, use a different set of
3394 // diagnostics.
3395 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003396 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003397
John McCallf3a88602011-02-03 08:15:49 +00003398 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3399 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003400}
3401
3402// Check whether the declarations we found through a nested-name
3403// specifier in a member expression are actually members of the base
3404// type. The restriction here is:
3405//
3406// C++ [expr.ref]p2:
3407// ... In these cases, the id-expression shall name a
3408// member of the class or of one of its base classes.
3409//
3410// So it's perfectly legitimate for the nested-name specifier to name
3411// an unrelated class, and for us to find an overload set including
3412// decls from classes which are not superclasses, as long as the decl
3413// we actually pick through overload resolution is from a superclass.
3414bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3415 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003416 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003417 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003418 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3419 if (!BaseRT) {
3420 // We can't check this yet because the base type is still
3421 // dependent.
3422 assert(BaseType->isDependentType());
3423 return false;
3424 }
3425 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003426
3427 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003428 // If this is an implicit member reference and we find a
3429 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003430 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003431 return false;
John McCall10eae182009-11-30 22:42:35 +00003432
John McCall2d74de92009-12-01 22:10:20 +00003433 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003434 DeclContext *DC = (*I)->getDeclContext();
3435 while (DC->isTransparentContext())
3436 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003437
Douglas Gregora9c3e822010-07-28 22:27:52 +00003438 if (!DC->isRecord())
3439 continue;
3440
John McCall2d74de92009-12-01 22:10:20 +00003441 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003442 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003443
3444 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3445 return false;
3446 }
3447
John McCallf3a88602011-02-03 08:15:49 +00003448 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3449 R.getRepresentativeDecl(),
3450 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003451 return true;
3452}
3453
3454static bool
3455LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3456 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003457 SourceLocation OpLoc, CXXScopeSpec &SS,
3458 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003459 RecordDecl *RDecl = RTy->getDecl();
3460 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003461 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003462 << BaseRange))
3463 return true;
3464
John McCalle9cccd82010-06-16 08:42:20 +00003465 if (HasTemplateArgs) {
3466 // LookupTemplateName doesn't expect these both to exist simultaneously.
3467 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3468
3469 bool MOUS;
3470 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3471 return false;
3472 }
3473
John McCall2d74de92009-12-01 22:10:20 +00003474 DeclContext *DC = RDecl;
3475 if (SS.isSet()) {
3476 // If the member name was a qualified-id, look into the
3477 // nested-name-specifier.
3478 DC = SemaRef.computeDeclContext(SS, false);
3479
John McCall0b66eb32010-05-01 00:40:08 +00003480 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003481 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3482 << SS.getRange() << DC;
3483 return true;
3484 }
3485
John McCall2d74de92009-12-01 22:10:20 +00003486 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003487
John McCall2d74de92009-12-01 22:10:20 +00003488 if (!isa<TypeDecl>(DC)) {
3489 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3490 << DC << SS.getRange();
3491 return true;
John McCall10eae182009-11-30 22:42:35 +00003492 }
3493 }
3494
John McCall2d74de92009-12-01 22:10:20 +00003495 // The record definition is complete, now look up the member.
3496 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003497
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003498 if (!R.empty())
3499 return false;
3500
3501 // We didn't find anything with the given name, so try to correct
3502 // for typos.
3503 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003504 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003505 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003506 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3507 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3508 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003509 << FixItHint::CreateReplacement(R.getNameLoc(),
3510 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003511 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3512 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3513 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003514 return false;
3515 } else {
3516 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003517 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003518 }
3519
John McCall10eae182009-11-30 22:42:35 +00003520 return false;
3521}
3522
John McCalldadc5752010-08-24 06:29:42 +00003523ExprResult
John McCallb268a282010-08-23 23:25:46 +00003524Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003525 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003526 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003527 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003528 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003529 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003530 if (BaseType->isDependentType() ||
3531 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003532 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003533 IsArrow, OpLoc,
3534 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003535 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003536
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003537 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003538
John McCall2d74de92009-12-01 22:10:20 +00003539 // Implicit member accesses.
3540 if (!Base) {
3541 QualType RecordTy = BaseType;
3542 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3543 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3544 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003545 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003546 return ExprError();
3547
3548 // Explicit member accesses.
3549 } else {
John Wiegley01296292011-04-08 18:41:53 +00003550 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003551 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003552 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003553 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003554
John Wiegley01296292011-04-08 18:41:53 +00003555 if (BaseResult.isInvalid())
3556 return ExprError();
3557 Base = BaseResult.take();
3558
John McCall2d74de92009-12-01 22:10:20 +00003559 if (Result.isInvalid()) {
3560 Owned(Base);
3561 return ExprError();
3562 }
3563
3564 if (Result.get())
3565 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003566
3567 // LookupMemberExpr can modify Base, and thus change BaseType
3568 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003569 }
3570
John McCallb268a282010-08-23 23:25:46 +00003571 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003572 OpLoc, IsArrow, SS, FirstQualifierInScope,
3573 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003574}
3575
John McCalldadc5752010-08-24 06:29:42 +00003576ExprResult
John McCallb268a282010-08-23 23:25:46 +00003577Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003578 SourceLocation OpLoc, bool IsArrow,
3579 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003580 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003581 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003582 const TemplateArgumentListInfo *TemplateArgs,
3583 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003584 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003585 if (IsArrow) {
3586 assert(BaseType->isPointerType());
3587 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3588 }
John McCalla8ae2222010-04-06 21:38:20 +00003589 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003590
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003591 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3592 DeclarationName MemberName = MemberNameInfo.getName();
3593 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003594
3595 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003596 return ExprError();
3597
John McCall10eae182009-11-30 22:42:35 +00003598 if (R.empty()) {
3599 // Rederive where we looked up.
3600 DeclContext *DC = (SS.isSet()
3601 ? computeDeclContext(SS, false)
3602 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003603
John McCall10eae182009-11-30 22:42:35 +00003604 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003605 << MemberName << DC
3606 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003607 return ExprError();
3608 }
3609
John McCall38836f02010-01-15 08:34:02 +00003610 // Diagnose lookups that find only declarations from a non-base
3611 // type. This is possible for either qualified lookups (which may
3612 // have been qualified with an unrelated type) or implicit member
3613 // expressions (which were found with unqualified lookup and thus
3614 // may have come from an enclosing scope). Note that it's okay for
3615 // lookup to find declarations from a non-base type as long as those
3616 // aren't the ones picked by overload resolution.
3617 if ((SS.isSet() || !BaseExpr ||
3618 (isa<CXXThisExpr>(BaseExpr) &&
3619 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003620 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003621 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003622 return ExprError();
3623
3624 // Construct an unresolved result if we in fact got an unresolved
3625 // result.
3626 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003627 // Suppress any lookup-related diagnostics; we'll do these when we
3628 // pick a member.
3629 R.suppressDiagnostics();
3630
John McCall10eae182009-11-30 22:42:35 +00003631 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003632 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003633 BaseExpr, BaseExprType,
3634 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003635 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003636 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003637 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003638
3639 return Owned(MemExpr);
3640 }
3641
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003642 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003643 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003644 NamedDecl *MemberDecl = R.getFoundDecl();
3645
3646 // FIXME: diagnose the presence of template arguments now.
3647
3648 // If the decl being referenced had an error, return an error for this
3649 // sub-expr without emitting another error, in order to avoid cascading
3650 // error cases.
3651 if (MemberDecl->isInvalidDecl())
3652 return ExprError();
3653
John McCall2d74de92009-12-01 22:10:20 +00003654 // Handle the implicit-member-access case.
3655 if (!BaseExpr) {
3656 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003657 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003658 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003659
Douglas Gregorb15af892010-01-07 23:12:05 +00003660 SourceLocation Loc = R.getNameLoc();
3661 if (SS.getRange().isValid())
3662 Loc = SS.getRange().getBegin();
3663 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003664 }
3665
John McCall10eae182009-11-30 22:42:35 +00003666 bool ShouldCheckUse = true;
3667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3668 // Don't diagnose the use of a virtual member function unless it's
3669 // explicitly qualified.
3670 if (MD->isVirtual() && !SS.isSet())
3671 ShouldCheckUse = false;
3672 }
3673
3674 // Check the use of this member.
3675 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3676 Owned(BaseExpr);
3677 return ExprError();
3678 }
3679
John McCall34376a62010-12-04 03:47:34 +00003680 // Perform a property load on the base regardless of whether we
3681 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003682 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3683 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3684 if (Result.isInvalid())
3685 return ExprError();
3686 BaseExpr = Result.take();
3687 }
John McCall34376a62010-12-04 03:47:34 +00003688
John McCallfeb624a2010-11-23 20:48:44 +00003689 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3690 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3691 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003692
Francois Pichet783dd6e2010-11-21 06:08:52 +00003693 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3694 // We may have found a field within an anonymous union or struct
3695 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003696 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003697 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003698
John McCall10eae182009-11-30 22:42:35 +00003699 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3700 MarkDeclarationReferenced(MemberLoc, Var);
3701 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003702 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003703 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003704 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003705 }
3706
John McCall7decc9e2010-11-18 06:31:45 +00003707 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003708 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3709 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003710 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003711 MemberFn->getType(),
3712 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3713 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003714 }
John McCall7decc9e2010-11-18 06:31:45 +00003715 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003716
3717 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3718 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3719 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003720 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003721 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003722 }
3723
3724 Owned(BaseExpr);
3725
Douglas Gregor861eb802010-04-25 20:55:08 +00003726 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003727 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003728 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003729 << MemberName << BaseType << int(IsArrow);
3730 else
3731 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3732 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003733
Douglas Gregor861eb802010-04-25 20:55:08 +00003734 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3735 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003736 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003737 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003738}
3739
John McCall68fc88ec2010-12-15 16:46:44 +00003740/// Given that normal member access failed on the given expression,
3741/// and given that the expression's type involves builtin-id or
3742/// builtin-Class, decide whether substituting in the redefinition
3743/// types would be profitable. The redefinition type is whatever
3744/// this translation unit tried to typedef to id/Class; we store
3745/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00003746static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00003747 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00003748 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00003749 if (!opty) return false;
3750
3751 const ObjCObjectType *ty = opty->getObjectType();
3752
3753 QualType redef;
3754 if (ty->isObjCId()) {
3755 redef = S.Context.ObjCIdRedefinitionType;
3756 } else if (ty->isObjCClass()) {
3757 redef = S.Context.ObjCClassRedefinitionType;
3758 } else {
3759 return false;
3760 }
3761
3762 // Do the substitution as long as the redefinition type isn't just a
3763 // possibly-qualified pointer to builtin-id or builtin-Class again.
3764 opty = redef->getAs<ObjCObjectPointerType>();
3765 if (opty && !opty->getObjectType()->getInterface() != 0)
3766 return false;
3767
John Wiegley01296292011-04-08 18:41:53 +00003768 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00003769 return true;
3770}
3771
John McCall10eae182009-11-30 22:42:35 +00003772/// Look up the given member of the given non-type-dependent
3773/// expression. This can return in one of two ways:
3774/// * If it returns a sentinel null-but-valid result, the caller will
3775/// assume that lookup was performed and the results written into
3776/// the provided structure. It will take over from there.
3777/// * Otherwise, the returned expression will be produced in place of
3778/// an ordinary member expression.
3779///
3780/// The ObjCImpDecl bit is a gross hack that will need to be properly
3781/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003782ExprResult
John Wiegley01296292011-04-08 18:41:53 +00003783Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003784 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003785 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003786 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00003787 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003788
Steve Naroffeaaae462007-12-16 21:42:28 +00003789 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003790 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003791
John Wiegley01296292011-04-08 18:41:53 +00003792 if (IsArrow) {
3793 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3794 if (BaseExpr.isInvalid())
3795 return ExprError();
3796 }
3797
3798 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00003799 assert(!BaseType->isDependentType());
3800
3801 DeclarationName MemberName = R.getLookupName();
3802 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003803
John McCall68fc88ec2010-12-15 16:46:44 +00003804 // For later type-checking purposes, turn arrow accesses into dot
3805 // accesses. The only access type we support that doesn't follow
3806 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3807 // and those never use arrows, so this is unaffected.
3808 if (IsArrow) {
3809 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3810 BaseType = Ptr->getPointeeType();
3811 else if (const ObjCObjectPointerType *Ptr
3812 = BaseType->getAs<ObjCObjectPointerType>())
3813 BaseType = Ptr->getPointeeType();
3814 else if (BaseType->isRecordType()) {
3815 // Recover from arrow accesses to records, e.g.:
3816 // struct MyRecord foo;
3817 // foo->bar
3818 // This is actually well-formed in C++ if MyRecord has an
3819 // overloaded operator->, but that should have been dealt with
3820 // by now.
3821 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00003822 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00003823 << FixItHint::CreateReplacement(OpLoc, ".");
3824 IsArrow = false;
3825 } else {
3826 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00003827 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00003828 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003829 }
3830 }
3831
John McCall68fc88ec2010-12-15 16:46:44 +00003832 // Handle field access to simple records.
3833 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00003834 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00003835 RTy, OpLoc, SS, HasTemplateArgs))
3836 return ExprError();
3837
3838 // Returning valid-but-null is how we indicate to the caller that
3839 // the lookup result was filled in.
3840 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003841 }
John McCall10eae182009-11-30 22:42:35 +00003842
John McCall68fc88ec2010-12-15 16:46:44 +00003843 // Handle ivar access to Objective-C objects.
3844 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003845 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003846
3847 // There are three cases for the base type:
3848 // - builtin id (qualified or unqualified)
3849 // - builtin Class (qualified or unqualified)
3850 // - an interface
3851 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3852 if (!IDecl) {
3853 // There's an implicit 'isa' ivar on all objects.
3854 // But we only actually find it this way on objects of type 'id',
3855 // apparently.
3856 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00003857 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00003858 Context.getObjCClassType()));
3859
3860 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3861 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3862 ObjCImpDecl, HasTemplateArgs);
3863 goto fail;
3864 }
3865
3866 ObjCInterfaceDecl *ClassDeclared;
3867 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3868
3869 if (!IV) {
3870 // Attempt to correct for typos in ivar names.
3871 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3872 LookupMemberName);
3873 if (CorrectTypo(Res, 0, 0, IDecl, false,
3874 IsArrow ? CTC_ObjCIvarLookup
3875 : CTC_ObjCPropertyLookup) &&
3876 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3877 Diag(R.getNameLoc(),
3878 diag::err_typecheck_member_reference_ivar_suggest)
3879 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3880 << FixItHint::CreateReplacement(R.getNameLoc(),
3881 IV->getNameAsString());
3882 Diag(IV->getLocation(), diag::note_previous_decl)
3883 << IV->getDeclName();
3884 } else {
3885 Res.clear();
3886 Res.setLookupName(Member);
3887
3888 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3889 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00003890 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00003891 return ExprError();
3892 }
3893 }
3894
3895 // If the decl being referenced had an error, return an error for this
3896 // sub-expr without emitting another error, in order to avoid cascading
3897 // error cases.
3898 if (IV->isInvalidDecl())
3899 return ExprError();
3900
3901 // Check whether we can reference this field.
3902 if (DiagnoseUseOfDecl(IV, MemberLoc))
3903 return ExprError();
3904 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3905 IV->getAccessControl() != ObjCIvarDecl::Package) {
3906 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3907 if (ObjCMethodDecl *MD = getCurMethodDecl())
3908 ClassOfMethodDecl = MD->getClassInterface();
3909 else if (ObjCImpDecl && getCurFunctionDecl()) {
3910 // Case of a c-function declared inside an objc implementation.
3911 // FIXME: For a c-style function nested inside an objc implementation
3912 // class, there is no implementation context available, so we pass
3913 // down the context as argument to this routine. Ideally, this context
3914 // need be passed down in the AST node and somehow calculated from the
3915 // AST for a function decl.
3916 if (ObjCImplementationDecl *IMPD =
3917 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3918 ClassOfMethodDecl = IMPD->getClassInterface();
3919 else if (ObjCCategoryImplDecl* CatImplClass =
3920 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3921 ClassOfMethodDecl = CatImplClass->getClassInterface();
3922 }
3923
3924 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3925 if (ClassDeclared != IDecl ||
3926 ClassOfMethodDecl != ClassDeclared)
3927 Diag(MemberLoc, diag::error_private_ivar_access)
3928 << IV->getDeclName();
3929 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3930 // @protected
3931 Diag(MemberLoc, diag::error_protected_ivar_access)
3932 << IV->getDeclName();
3933 }
3934
3935 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00003936 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00003937 IsArrow));
3938 }
3939
3940 // Objective-C property access.
3941 const ObjCObjectPointerType *OPT;
3942 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3943 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00003944 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3945 if (BaseExpr.isInvalid())
3946 return ExprError();
3947
3948 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00003949
3950 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3951
3952 const ObjCObjectType *OT = OPT->getObjectType();
3953
3954 // id, with and without qualifiers.
3955 if (OT->isObjCId()) {
3956 // Check protocols on qualified interfaces.
3957 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3958 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3959 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3960 // Check the use of this declaration
3961 if (DiagnoseUseOfDecl(PD, MemberLoc))
3962 return ExprError();
3963
3964 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3965 VK_LValue,
3966 OK_ObjCProperty,
3967 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00003968 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00003969 }
3970
3971 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3972 // Check the use of this method.
3973 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3974 return ExprError();
3975 Selector SetterSel =
3976 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3977 PP.getSelectorTable(), Member);
3978 ObjCMethodDecl *SMD = 0;
3979 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3980 SetterSel, Context))
3981 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3982 QualType PType = OMD->getSendResultType();
3983
3984 ExprValueKind VK = VK_LValue;
3985 if (!getLangOptions().CPlusPlus &&
3986 IsCForbiddenLValueType(Context, PType))
3987 VK = VK_RValue;
3988 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3989
3990 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3991 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00003992 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00003993 }
3994 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003995 // Use of id.member can only be for a property reference. Do not
3996 // use the 'id' redefinition in this case.
3997 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003998 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3999 ObjCImpDecl, HasTemplateArgs);
4000
4001 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4002 << MemberName << BaseType);
4003 }
4004
4005 // 'Class', unqualified only.
4006 if (OT->isObjCClass()) {
4007 // Only works in a method declaration (??!).
4008 ObjCMethodDecl *MD = getCurMethodDecl();
4009 if (!MD) {
4010 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4011 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4012 ObjCImpDecl, HasTemplateArgs);
4013
4014 goto fail;
4015 }
4016
4017 // Also must look for a getter name which uses property syntax.
4018 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004019 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4020 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004021 if ((Getter = IFace->lookupClassMethod(Sel))) {
4022 // Check the use of this method.
4023 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4024 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004025 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004026 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004027 // If we found a getter then this may be a valid dot-reference, we
4028 // will look for the matching setter, in case it is needed.
4029 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004030 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4031 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004032 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4033 if (!Setter) {
4034 // If this reference is in an @implementation, also check for 'private'
4035 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004036 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004037 }
4038 // Look through local category implementations associated with the class.
4039 if (!Setter)
4040 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004041
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004042 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4043 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004044
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004045 if (Getter || Setter) {
4046 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004047
John McCall4bc41ae2010-11-18 19:01:18 +00004048 ExprValueKind VK = VK_LValue;
4049 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004050 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004051 if (!getLangOptions().CPlusPlus &&
4052 IsCForbiddenLValueType(Context, PType))
4053 VK = VK_RValue;
4054 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004055 // Get the expression type from Setter's incoming parameter.
4056 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004057 }
4058 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4059
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004060 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004061 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4062 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004063 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004064 }
John McCall68fc88ec2010-12-15 16:46:44 +00004065
4066 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4067 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4068 ObjCImpDecl, HasTemplateArgs);
4069
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004070 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004071 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004072 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004073
John McCall68fc88ec2010-12-15 16:46:44 +00004074 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004075 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004076 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004077 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004078
Chris Lattnerb63a7452008-07-21 04:28:12 +00004079 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004080 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004081 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004082 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004083 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004084 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4085 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004086 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004087 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004088
John Wiegley01296292011-04-08 18:41:53 +00004089 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004090 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004091 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004092
John McCall68fc88ec2010-12-15 16:46:44 +00004093 // Adjust builtin-sel to the appropriate redefinition type if that's
4094 // not just a pointer to builtin-sel again.
4095 if (IsArrow &&
4096 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4097 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004098 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4099 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004100 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4101 ObjCImpDecl, HasTemplateArgs);
4102 }
4103
4104 // Failure cases.
4105 fail:
4106
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004107 // Recover from dot accesses to pointers, e.g.:
4108 // type *foo;
4109 // foo.bar
4110 // This is actually well-formed in two cases:
4111 // - 'type' is an Objective C type
4112 // - 'bar' is a pseudo-destructor name which happens to refer to
4113 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004114 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004115 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4116 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004117 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004118 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004119 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004120
4121 // Recurse as an -> access.
4122 IsArrow = true;
4123 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4124 ObjCImpDecl, HasTemplateArgs);
4125 }
John McCall68fc88ec2010-12-15 16:46:44 +00004126 }
4127
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004128 // If the user is trying to apply -> or . to a function name, it's probably
4129 // because they forgot parentheses to call that function.
4130 bool TryCall = false;
4131 bool Overloaded = false;
4132 UnresolvedSet<8> AllOverloads;
John Wiegley01296292011-04-08 18:41:53 +00004133 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004134 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4135 TryCall = true;
4136 Overloaded = true;
John Wiegley01296292011-04-08 18:41:53 +00004137 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004138 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4139 AllOverloads.addDecl(Fun);
4140 TryCall = true;
4141 }
4142 }
John McCall68fc88ec2010-12-15 16:46:44 +00004143
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004144 if (TryCall) {
4145 // Plunder the overload set for something that would make the member
4146 // expression valid.
4147 UnresolvedSet<4> ViableOverloads;
4148 bool HasViableZeroArgOverload = false;
4149 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4150 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004151 // Our overload set may include TemplateDecls, which we'll ignore for the
4152 // purposes of determining whether we can issue a '()' fixit.
4153 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4154 QualType ResultTy = OverloadDecl->getResultType();
4155 if ((!IsArrow && ResultTy->isRecordType()) ||
4156 (IsArrow && ResultTy->isPointerType() &&
4157 ResultTy->getPointeeType()->isRecordType())) {
4158 ViableOverloads.addDecl(*it);
4159 if (OverloadDecl->getMinRequiredArguments() == 0) {
4160 HasViableZeroArgOverload = true;
4161 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004162 }
John McCall68fc88ec2010-12-15 16:46:44 +00004163 }
4164 }
4165
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004166 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley01296292011-04-08 18:41:53 +00004167 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004168 << (AllOverloads.size() > 1) << 0
John Wiegley01296292011-04-08 18:41:53 +00004169 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004170 int ViableOverloadCount = ViableOverloads.size();
4171 int I;
4172 for (I = 0; I < ViableOverloadCount; ++I) {
4173 // FIXME: Magic number for max shown overloads stolen from
4174 // OverloadCandidateSet::NoteCandidates.
4175 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4176 break;
4177 }
4178 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4179 diag::note_member_ref_possible_intended_overload);
4180 }
4181 if (I != ViableOverloadCount) {
John Wiegley01296292011-04-08 18:41:53 +00004182 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004183 << int(ViableOverloadCount - I);
4184 }
4185 return ExprError();
4186 }
4187 } else {
4188 // We don't have an expression that's convenient to get a Decl from, but we
4189 // can at least check if the type is "function of 0 arguments which returns
4190 // an acceptable type".
4191 const FunctionType *Fun = NULL;
4192 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4193 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4194 TryCall = true;
4195 }
4196 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4197 TryCall = true;
4198 }
John McCall68fc88ec2010-12-15 16:46:44 +00004199
4200 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004201 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4202 if (FPT->getNumArgs() == 0) {
4203 QualType ResultTy = Fun->getResultType();
4204 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4205 (IsArrow && ResultTy->isPointerType() &&
4206 ResultTy->getPointeeType()->isRecordType());
4207 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004208 }
John McCall68fc88ec2010-12-15 16:46:44 +00004209 }
4210 }
4211
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004212 if (TryCall) {
4213 // At this point, we know BaseExpr looks like it's potentially callable with
4214 // 0 arguments, and that it returns something of a reasonable type, so we
4215 // can emit a fixit and carry on pretending that BaseExpr was actually a
4216 // CallExpr.
4217 SourceLocation ParenInsertionLoc =
John Wiegley01296292011-04-08 18:41:53 +00004218 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4219 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004220 << int(Overloaded) << 1
John Wiegley01296292011-04-08 18:41:53 +00004221 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004222 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley01296292011-04-08 18:41:53 +00004223 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004224 MultiExprArg(*this, 0, 0),
4225 ParenInsertionLoc);
4226 if (NewBase.isInvalid())
4227 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004228 BaseExpr = NewBase;
4229 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004230 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4231 ObjCImpDecl, HasTemplateArgs);
4232 }
4233
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004234 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004235 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004236
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004237 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004238}
4239
John McCall10eae182009-11-30 22:42:35 +00004240/// The main callback when the parser finds something like
4241/// expression . [nested-name-specifier] identifier
4242/// expression -> [nested-name-specifier] identifier
4243/// where 'identifier' encompasses a fairly broad spectrum of
4244/// possibilities, including destructor and operator references.
4245///
4246/// \param OpKind either tok::arrow or tok::period
4247/// \param HasTrailingLParen whether the next token is '(', which
4248/// is used to diagnose mis-uses of special members that can
4249/// only be called
4250/// \param ObjCImpDecl the current ObjC @implementation decl;
4251/// this is an ugly hack around the fact that ObjC @implementations
4252/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004253ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004254 SourceLocation OpLoc,
4255 tok::TokenKind OpKind,
4256 CXXScopeSpec &SS,
4257 UnqualifiedId &Id,
4258 Decl *ObjCImpDecl,
4259 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004260 if (SS.isSet() && SS.isInvalid())
4261 return ExprError();
4262
Francois Pichet64225792011-01-18 05:04:39 +00004263 // Warn about the explicit constructor calls Microsoft extension.
4264 if (getLangOptions().Microsoft &&
4265 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4266 Diag(Id.getSourceRange().getBegin(),
4267 diag::ext_ms_explicit_constructor_call);
4268
John McCall10eae182009-11-30 22:42:35 +00004269 TemplateArgumentListInfo TemplateArgsBuffer;
4270
4271 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004272 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004273 const TemplateArgumentListInfo *TemplateArgs;
4274 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004275 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004276
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004277 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004278 bool IsArrow = (OpKind == tok::arrow);
4279
4280 NamedDecl *FirstQualifierInScope
4281 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4282 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4283
4284 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004285 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004286 if (Result.isInvalid()) return ExprError();
4287 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004288
Douglas Gregor41f90302010-04-12 20:54:26 +00004289 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4290 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004291 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004292 IsArrow, OpLoc,
4293 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004294 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004295 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004296 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004297 ExprResult BaseResult = Owned(Base);
4298 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004299 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004300 if (BaseResult.isInvalid())
4301 return ExprError();
4302 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004303
John McCalle9cccd82010-06-16 08:42:20 +00004304 if (Result.isInvalid()) {
4305 Owned(Base);
4306 return ExprError();
4307 }
John McCall10eae182009-11-30 22:42:35 +00004308
John McCalle9cccd82010-06-16 08:42:20 +00004309 if (Result.get()) {
4310 // The only way a reference to a destructor can be used is to
4311 // immediately call it, which falls into this case. If the
4312 // next token is not a '(', produce a diagnostic and build the
4313 // call now.
4314 if (!HasTrailingLParen &&
4315 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004316 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004317
John McCalle9cccd82010-06-16 08:42:20 +00004318 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004319 }
4320
John McCallb268a282010-08-23 23:25:46 +00004321 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004322 OpLoc, IsArrow, SS, FirstQualifierInScope,
4323 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004324 }
4325
4326 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004327}
4328
John McCalldadc5752010-08-24 06:29:42 +00004329ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004330 FunctionDecl *FD,
4331 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004332 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004333 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004334 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004335 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004336 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004337 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004338 return ExprError();
4339 }
4340
4341 if (Param->hasUninstantiatedDefaultArg()) {
4342 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004343
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004344 // Instantiate the expression.
4345 MultiLevelTemplateArgumentList ArgList
4346 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004347
Nico Weber44887f62010-11-29 18:19:25 +00004348 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004349 = ArgList.getInnermost();
4350 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4351 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004352
Nico Weber44887f62010-11-29 18:19:25 +00004353 ExprResult Result;
4354 {
4355 // C++ [dcl.fct.default]p5:
4356 // The names in the [default argument] expression are bound, and
4357 // the semantic constraints are checked, at the point where the
4358 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004359 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004360 Result = SubstExpr(UninstExpr, ArgList);
4361 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004362 if (Result.isInvalid())
4363 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004365 // Check the expression as an initializer for the parameter.
4366 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004367 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004368 InitializationKind Kind
4369 = InitializationKind::CreateCopy(Param->getLocation(),
4370 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4371 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004372
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004373 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4374 Result = InitSeq.Perform(*this, Entity, Kind,
4375 MultiExprArg(*this, &ResultE, 1));
4376 if (Result.isInvalid())
4377 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004378
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004379 // Build the default argument expression.
4380 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4381 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004382 }
4383
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004384 // If the default expression creates temporaries, we need to
4385 // push them to the current stack of expression temporaries so they'll
4386 // be properly destroyed.
4387 // FIXME: We should really be rebuilding the default argument with new
4388 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004389 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4390 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4391 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4392 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4393 ExprTemporaries.push_back(Temporary);
4394 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004395
4396 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004397 // Just mark all of the declarations in this potentially-evaluated expression
4398 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004399 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004400 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004401}
4402
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004403/// ConvertArgumentsForCall - Converts the arguments specified in
4404/// Args/NumArgs to the parameter types of the function FDecl with
4405/// function prototype Proto. Call is the call expression itself, and
4406/// Fn is the function expression. For a C++ member function, this
4407/// routine does not attempt to convert the object argument. Returns
4408/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004409bool
4410Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004411 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004412 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004413 Expr **Args, unsigned NumArgs,
4414 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004415 // Bail out early if calling a builtin with custom typechecking.
4416 // We don't need to do this in the
4417 if (FDecl)
4418 if (unsigned ID = FDecl->getBuiltinID())
4419 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4420 return false;
4421
Mike Stump4e1f26a2009-02-19 03:04:26 +00004422 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004423 // assignment, to the types of the corresponding parameter, ...
4424 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004425 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004426
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004427 // If too few arguments are available (and we don't have default
4428 // arguments for the remaining parameters), don't make the call.
4429 if (NumArgs < NumArgsInProto) {
4430 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4431 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004432 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004433 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004434 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004435 }
4436
4437 // If too many are passed and not variadic, error on the extras and drop
4438 // them.
4439 if (NumArgs > NumArgsInProto) {
4440 if (!Proto->isVariadic()) {
4441 Diag(Args[NumArgsInProto]->getLocStart(),
4442 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004443 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004444 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004445 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4446 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004447
4448 // Emit the location of the prototype.
4449 if (FDecl && !FDecl->getBuiltinID())
4450 Diag(FDecl->getLocStart(),
4451 diag::note_typecheck_call_too_many_args)
4452 << FDecl;
4453
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004454 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004455 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004456 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004457 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004458 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004459 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004460 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004461 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4462 if (Fn->getType()->isBlockPointerType())
4463 CallType = VariadicBlock; // Block
4464 else if (isa<MemberExpr>(Fn))
4465 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004466 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004467 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004468 if (Invalid)
4469 return true;
4470 unsigned TotalNumArgs = AllArgs.size();
4471 for (unsigned i = 0; i < TotalNumArgs; ++i)
4472 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004474 return false;
4475}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004476
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004477bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4478 FunctionDecl *FDecl,
4479 const FunctionProtoType *Proto,
4480 unsigned FirstProtoArg,
4481 Expr **Args, unsigned NumArgs,
4482 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004483 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004484 unsigned NumArgsInProto = Proto->getNumArgs();
4485 unsigned NumArgsToCheck = NumArgs;
4486 bool Invalid = false;
4487 if (NumArgs != NumArgsInProto)
4488 // Use default arguments for missing arguments
4489 NumArgsToCheck = NumArgsInProto;
4490 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004491 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004492 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004493 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004494
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004495 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004496 if (ArgIx < NumArgs) {
4497 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004498
Eli Friedman3164fb12009-03-22 22:00:50 +00004499 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4500 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004501 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004502 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004503 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004504
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004505 // Pass the argument
4506 ParmVarDecl *Param = 0;
4507 if (FDecl && i < FDecl->getNumParams())
4508 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004509
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004510 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004511 Param? InitializedEntity::InitializeParameter(Context, Param)
4512 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004513 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004514 SourceLocation(),
4515 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004516 if (ArgE.isInvalid())
4517 return true;
4518
4519 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004520 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004521 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004522
John McCalldadc5752010-08-24 06:29:42 +00004523 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004524 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004525 if (ArgExpr.isInvalid())
4526 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004527
Anders Carlsson355933d2009-08-25 03:49:14 +00004528 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004529 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004530 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004532
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004533 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004534 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004535 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004536 for (unsigned i = ArgIx; i != NumArgs; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004537 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4538 Invalid |= Arg.isInvalid();
4539 AllArgs.push_back(Arg.take());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004540 }
4541 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004542 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004543}
4544
Steve Naroff83895f72007-09-16 03:34:24 +00004545/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004546/// This provides the location of the left/right parens and a list of comma
4547/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004548ExprResult
John McCallb268a282010-08-23 23:25:46 +00004549Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004550 MultiExprArg args, SourceLocation RParenLoc,
4551 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004552 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004553
4554 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004555 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004556 if (Result.isInvalid()) return ExprError();
4557 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004558
John McCallb268a282010-08-23 23:25:46 +00004559 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004560
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004561 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004562 // If this is a pseudo-destructor expression, build the call immediately.
4563 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4564 if (NumArgs > 0) {
4565 // Pseudo-destructor calls should not have any arguments.
4566 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004567 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004568 SourceRange(Args[0]->getLocStart(),
4569 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004570
Douglas Gregorad8a3362009-09-04 17:36:40 +00004571 NumArgs = 0;
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
Douglas Gregorad8a3362009-09-04 17:36:40 +00004574 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004575 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004576 }
Mike Stump11289f42009-09-09 15:08:12 +00004577
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004578 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004579 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004580 // FIXME: Will need to cache the results of name lookup (including ADL) in
4581 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004582 bool Dependent = false;
4583 if (Fn->isTypeDependent())
4584 Dependent = true;
4585 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4586 Dependent = true;
4587
Peter Collingbourne41f85462011-02-09 21:07:24 +00004588 if (Dependent) {
4589 if (ExecConfig) {
4590 return Owned(new (Context) CUDAKernelCallExpr(
4591 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4592 Context.DependentTy, VK_RValue, RParenLoc));
4593 } else {
4594 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4595 Context.DependentTy, VK_RValue,
4596 RParenLoc));
4597 }
4598 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004599
4600 // Determine whether this is a call to an object (C++ [over.call.object]).
4601 if (Fn->getType()->isRecordType())
4602 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004603 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004604
John McCall10eae182009-11-30 22:42:35 +00004605 Expr *NakedFn = Fn->IgnoreParens();
4606
4607 // Determine whether this is a call to an unresolved member function.
4608 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4609 // If lookup was unresolved but not dependent (i.e. didn't find
4610 // an unresolved using declaration), it has to be an overloaded
4611 // function set, which means it must contain either multiple
4612 // declarations (all methods or method templates) or a single
4613 // method template.
4614 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004615 isa<FunctionTemplateDecl>(
4616 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004617 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004618
John McCall2d74de92009-12-01 22:10:20 +00004619 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004620 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004621 }
4622
Douglas Gregore254f902009-02-04 00:32:51 +00004623 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004624 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004625 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004626 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004627 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004628 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004629 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004630
Anders Carlsson61914b52009-10-03 17:40:22 +00004631 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004632 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004633 if (BO->getOpcode() == BO_PtrMemD ||
4634 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004635 if (const FunctionProtoType *FPT
4636 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004637 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004638 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004639
Douglas Gregor125fa402011-02-04 12:57:49 +00004640 // Check that the object type isn't more qualified than the
4641 // member function we're calling.
4642 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4643 Qualifiers ObjectQuals
4644 = BO->getOpcode() == BO_PtrMemD
4645 ? BO->getLHS()->getType().getQualifiers()
4646 : BO->getLHS()->getType()->getAs<PointerType>()
4647 ->getPointeeType().getQualifiers();
4648
4649 Qualifiers Difference = ObjectQuals - FuncQuals;
4650 Difference.removeObjCGCAttr();
4651 Difference.removeAddressSpace();
4652 if (Difference) {
4653 std::string QualsString = Difference.getAsString();
4654 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4655 << BO->getType().getUnqualifiedType()
4656 << QualsString
4657 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4658 }
4659
John McCallb268a282010-08-23 23:25:46 +00004660 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004661 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004662 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004663 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004664
4665 if (CheckCallReturnType(FPT->getResultType(),
4666 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004667 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004668 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004669
John McCallb268a282010-08-23 23:25:46 +00004670 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004671 RParenLoc))
4672 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004673
John McCallb268a282010-08-23 23:25:46 +00004674 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004675 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004676 }
4677 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004678 }
4679
Douglas Gregore254f902009-02-04 00:32:51 +00004680 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004681 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004682 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683
Eli Friedmane14b1992009-12-26 03:35:45 +00004684 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004685 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4686 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4687 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004688 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004689 }
4690
John McCall57500772009-12-16 12:17:52 +00004691 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004692 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4693 if (UnOp->getOpcode() == UO_AddrOf)
4694 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4695
John McCall57500772009-12-16 12:17:52 +00004696 if (isa<DeclRefExpr>(NakedFn))
4697 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4698
Peter Collingbourne41f85462011-02-09 21:07:24 +00004699 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4700 ExecConfig);
4701}
4702
4703ExprResult
4704Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4705 MultiExprArg execConfig, SourceLocation GGGLoc) {
4706 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4707 if (!ConfigDecl)
4708 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4709 << "cudaConfigureCall");
4710 QualType ConfigQTy = ConfigDecl->getType();
4711
4712 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4713 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4714
4715 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004716}
4717
John McCall31996342011-04-07 08:22:57 +00004718/// Given a function expression of unknown-any type, rebuild it to
4719/// have a type appropriate for being called with the given arguments,
4720/// yielding a value of unknown-any type.
4721static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn,
4722 Expr **args, unsigned numArgs) {
4723 // Build a simple function type exactly matching the arguments.
4724 llvm::SmallVector<QualType, 8> argTypes;
4725 argTypes.reserve(numArgs);
4726 for (unsigned i = 0; i != numArgs; ++i) {
4727 // Require all the sub-expression to not be placeholders.
4728 ExprResult result = S.CheckPlaceholderExpr(args[i], SourceLocation());
4729 if (result.isInvalid()) return ExprError();
4730 args[i] = result.take();
4731
4732 // Do l2r conversions on all the arguments.
4733 S.DefaultLvalueConversion(args[i]);
4734
4735 argTypes.push_back(args[i]->getType());
4736 }
4737
4738 // Resolve the symbol to a function type that returns an unknown-any
4739 // type. In the fully resolved expression, this cast will surround
4740 // the DeclRefExpr.
4741 FunctionProtoType::ExtProtoInfo extInfo;
4742 QualType fnType = S.Context.getFunctionType(S.Context.UnknownAnyTy,
4743 argTypes.data(), numArgs,
4744 extInfo);
4745 fn = ImplicitCastExpr::Create(S.Context, fnType,
4746 CK_ResolveUnknownAnyType,
4747 fn, /*path*/ 0,
4748 (S.getLangOptions().CPlusPlus ? VK_LValue : VK_RValue));
4749
4750 // Decay that to a pointer.
4751 fnType = S.Context.getPointerType(fnType);
4752 fn = ImplicitCastExpr::Create(S.Context, fnType,
4753 CK_FunctionToPointerDecay,
4754 fn, /*path*/ 0, VK_RValue);
4755
4756 return S.Owned(fn);
4757}
4758
John McCall57500772009-12-16 12:17:52 +00004759/// BuildResolvedCallExpr - Build a call to a resolved expression,
4760/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004761/// unary-convert to an expression of function-pointer or
4762/// block-pointer type.
4763///
4764/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004765ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004766Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4767 SourceLocation LParenLoc,
4768 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004769 SourceLocation RParenLoc,
4770 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004771 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4772
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004773 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004774 ExprResult Result = UsualUnaryConversions(Fn);
4775 if (Result.isInvalid())
4776 return ExprError();
4777 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004778
Chris Lattner08464942007-12-28 05:29:59 +00004779 // Make the call expr early, before semantic checks. This guarantees cleanup
4780 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004781 CallExpr *TheCall;
4782 if (Config) {
4783 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4784 cast<CallExpr>(Config),
4785 Args, NumArgs,
4786 Context.BoolTy,
4787 VK_RValue,
4788 RParenLoc);
4789 } else {
4790 TheCall = new (Context) CallExpr(Context, Fn,
4791 Args, NumArgs,
4792 Context.BoolTy,
4793 VK_RValue,
4794 RParenLoc);
4795 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004796
John McCallbebede42011-02-26 05:39:39 +00004797 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4798
4799 // Bail out early if calling a builtin with custom typechecking.
4800 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4801 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4802
John McCall31996342011-04-07 08:22:57 +00004803 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004804 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004805 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004806 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4807 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004808 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004809 if (FuncT == 0)
4810 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4811 << Fn->getType() << Fn->getSourceRange());
4812 } else if (const BlockPointerType *BPT =
4813 Fn->getType()->getAs<BlockPointerType>()) {
4814 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4815 } else {
John McCall31996342011-04-07 08:22:57 +00004816 // Handle calls to expressions of unknown-any type.
4817 if (Fn->getType() == Context.UnknownAnyTy) {
4818 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn, Args, NumArgs);
4819 if (rewrite.isInvalid()) return ExprError();
4820 Fn = rewrite.take();
4821 NDecl = FDecl = 0;
4822 goto retry;
4823 }
4824
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004825 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4826 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004827 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004828
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004829 if (getLangOptions().CUDA) {
4830 if (Config) {
4831 // CUDA: Kernel calls must be to global functions
4832 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4833 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4834 << FDecl->getName() << Fn->getSourceRange());
4835
4836 // CUDA: Kernel function must have 'void' return type
4837 if (!FuncT->getResultType()->isVoidType())
4838 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4839 << Fn->getType() << Fn->getSourceRange());
4840 }
4841 }
4842
Eli Friedman3164fb12009-03-22 22:00:50 +00004843 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004844 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004845 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004846 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004847 return ExprError();
4848
Chris Lattner08464942007-12-28 05:29:59 +00004849 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004850 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004851 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004852
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004853 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004854 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004855 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004856 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004857 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004858 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004859
Douglas Gregord8e97de2009-04-02 15:37:10 +00004860 if (FDecl) {
4861 // Check if we have too few/too many template arguments, based
4862 // on our knowledge of the function definition.
4863 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004864 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004865 const FunctionProtoType *Proto
4866 = Def->getType()->getAs<FunctionProtoType>();
4867 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004868 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4869 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004870 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004871
4872 // If the function we're calling isn't a function prototype, but we have
4873 // a function prototype from a prior declaratiom, use that prototype.
4874 if (!FDecl->hasPrototype())
4875 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004876 }
4877
Steve Naroff0b661582007-08-28 23:30:39 +00004878 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004879 for (unsigned i = 0; i != NumArgs; i++) {
4880 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004881
4882 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004883 InitializedEntity Entity
4884 = InitializedEntity::InitializeParameter(Context,
4885 Proto->getArgType(i));
4886 ExprResult ArgE = PerformCopyInitialization(Entity,
4887 SourceLocation(),
4888 Owned(Arg));
4889 if (ArgE.isInvalid())
4890 return true;
4891
4892 Arg = ArgE.takeAs<Expr>();
4893
4894 } else {
John Wiegley01296292011-04-08 18:41:53 +00004895 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4896
4897 if (ArgE.isInvalid())
4898 return true;
4899
4900 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004901 }
4902
Douglas Gregor83025412010-10-26 05:45:40 +00004903 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4904 Arg->getType(),
4905 PDiag(diag::err_call_incomplete_argument)
4906 << Arg->getSourceRange()))
4907 return ExprError();
4908
Chris Lattner08464942007-12-28 05:29:59 +00004909 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004910 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004911 }
Chris Lattner08464942007-12-28 05:29:59 +00004912
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004913 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4914 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004915 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4916 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004917
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004918 // Check for sentinels
4919 if (NDecl)
4920 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004921
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004922 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004923 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004924 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004925 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004926
John McCallbebede42011-02-26 05:39:39 +00004927 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004928 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004929 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004930 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004931 return ExprError();
4932 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004933
John McCallb268a282010-08-23 23:25:46 +00004934 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004935}
4936
John McCalldadc5752010-08-24 06:29:42 +00004937ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004938Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004939 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004940 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004941 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004942 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004943
4944 TypeSourceInfo *TInfo;
4945 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4946 if (!TInfo)
4947 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4948
John McCallb268a282010-08-23 23:25:46 +00004949 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004950}
4951
John McCalldadc5752010-08-24 06:29:42 +00004952ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004953Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004954 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004955 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004956
Eli Friedman37a186d2008-05-20 05:22:08 +00004957 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004958 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4959 PDiag(diag::err_illegal_decl_array_incomplete_type)
4960 << SourceRange(LParenLoc,
4961 literalExpr->getSourceRange().getEnd())))
4962 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004963 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004964 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4965 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004966 } else if (!literalType->isDependentType() &&
4967 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004968 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004969 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004970 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004971 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004972
Douglas Gregor85dabae2009-12-16 01:38:02 +00004973 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004974 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004975 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004976 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004977 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004978 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004979 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004980 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004981 &literalType);
4982 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004983 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004984 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004985
Chris Lattner79413952008-12-04 23:50:19 +00004986 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004987 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004988 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004989 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004990 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004991
John McCall7decc9e2010-11-18 06:31:45 +00004992 // In C, compound literals are l-values for some reason.
4993 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4994
John McCall5d7aa7f2010-01-19 22:33:45 +00004995 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004996 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004997}
4998
John McCalldadc5752010-08-24 06:29:42 +00004999ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005000Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005001 SourceLocation RBraceLoc) {
5002 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005003 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005004
Steve Naroff30d242c2007-09-15 18:49:24 +00005005 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005006 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005007
Ted Kremenekac034612010-04-13 23:39:13 +00005008 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5009 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005010 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005011 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005012}
5013
John McCalld7646252010-11-14 08:17:51 +00005014/// Prepares for a scalar cast, performing all the necessary stages
5015/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005016static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005017 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5018 // Also, callers should have filtered out the invalid cases with
5019 // pointers. Everything else should be possible.
5020
John Wiegley01296292011-04-08 18:41:53 +00005021 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005022 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005023 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005024
John McCall8cb679e2010-11-15 09:13:47 +00005025 switch (SrcTy->getScalarTypeKind()) {
5026 case Type::STK_MemberPointer:
5027 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005028
John McCall8cb679e2010-11-15 09:13:47 +00005029 case Type::STK_Pointer:
5030 switch (DestTy->getScalarTypeKind()) {
5031 case Type::STK_Pointer:
5032 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005033 CK_AnyPointerToObjCPointerCast :
5034 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005035 case Type::STK_Bool:
5036 return CK_PointerToBoolean;
5037 case Type::STK_Integral:
5038 return CK_PointerToIntegral;
5039 case Type::STK_Floating:
5040 case Type::STK_FloatingComplex:
5041 case Type::STK_IntegralComplex:
5042 case Type::STK_MemberPointer:
5043 llvm_unreachable("illegal cast from pointer");
5044 }
5045 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005046
John McCall8cb679e2010-11-15 09:13:47 +00005047 case Type::STK_Bool: // casting from bool is like casting from an integer
5048 case Type::STK_Integral:
5049 switch (DestTy->getScalarTypeKind()) {
5050 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005051 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005052 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005053 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005054 case Type::STK_Bool:
5055 return CK_IntegralToBoolean;
5056 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005057 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005058 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005059 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005060 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005061 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5062 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005063 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005064 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005065 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5066 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005067 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005068 case Type::STK_MemberPointer:
5069 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005070 }
5071 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005072
John McCall8cb679e2010-11-15 09:13:47 +00005073 case Type::STK_Floating:
5074 switch (DestTy->getScalarTypeKind()) {
5075 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005076 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005077 case Type::STK_Bool:
5078 return CK_FloatingToBoolean;
5079 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005080 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005081 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005082 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5083 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005084 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005085 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005086 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5087 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005088 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005089 case Type::STK_Pointer:
5090 llvm_unreachable("valid float->pointer cast?");
5091 case Type::STK_MemberPointer:
5092 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005093 }
5094 break;
5095
John McCall8cb679e2010-11-15 09:13:47 +00005096 case Type::STK_FloatingComplex:
5097 switch (DestTy->getScalarTypeKind()) {
5098 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005099 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005100 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005101 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005102 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005103 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005104 if (S.Context.hasSameType(ET, DestTy))
5105 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005106 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005107 return CK_FloatingCast;
5108 }
John McCall8cb679e2010-11-15 09:13:47 +00005109 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005110 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005111 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005112 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5113 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005114 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005115 case Type::STK_Pointer:
5116 llvm_unreachable("valid complex float->pointer cast?");
5117 case Type::STK_MemberPointer:
5118 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005119 }
5120 break;
5121
John McCall8cb679e2010-11-15 09:13:47 +00005122 case Type::STK_IntegralComplex:
5123 switch (DestTy->getScalarTypeKind()) {
5124 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005125 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005126 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005127 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005128 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005129 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005130 if (S.Context.hasSameType(ET, DestTy))
5131 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005132 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005133 return CK_IntegralCast;
5134 }
John McCall8cb679e2010-11-15 09:13:47 +00005135 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005136 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005137 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005138 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5139 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005140 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005141 case Type::STK_Pointer:
5142 llvm_unreachable("valid complex int->pointer cast?");
5143 case Type::STK_MemberPointer:
5144 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005145 }
5146 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005147 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005148
John McCalld7646252010-11-14 08:17:51 +00005149 llvm_unreachable("Unhandled scalar cast");
5150 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005151}
5152
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005153/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005154ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5155 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5156 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005157 if (castExpr->getType() == Context.UnknownAnyTy)
5158 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5159
Sebastian Redl9f831db2009-07-25 15:41:38 +00005160 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005161 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5162 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005163 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005164 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005165
John McCall7decc9e2010-11-18 06:31:45 +00005166 // We only support r-value casts in C.
5167 VK = VK_RValue;
5168
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005169 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5170 // type needs to be scalar.
5171 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005172 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005173 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5174 if (castExprRes.isInvalid())
5175 return ExprError();
5176 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005177
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005178 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005179 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005180 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005181 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005182
John Wiegley01296292011-04-08 18:41:53 +00005183 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5184 if (castExprRes.isInvalid())
5185 return ExprError();
5186 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005187
Eli Friedmane98194d2010-07-17 20:43:49 +00005188 if (RequireCompleteType(TyR.getBegin(), castType,
5189 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005190 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005191
Anders Carlssonef918ac2009-10-16 02:35:04 +00005192 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005193 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005194 (castType->isStructureType() || castType->isUnionType())) {
5195 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005196 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005197 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5198 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005199 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005200 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005201 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005202
Anders Carlsson525b76b2009-10-16 02:48:28 +00005203 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005204 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005205 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005206 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005207 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005208 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005209 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005210 castExpr->getType()) &&
5211 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005212 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5213 << castExpr->getSourceRange();
5214 break;
5215 }
5216 }
John Wiegley01296292011-04-08 18:41:53 +00005217 if (Field == FieldEnd) {
5218 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005219 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005220 return ExprError();
5221 }
John McCalle3027922010-08-25 11:45:40 +00005222 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005223 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005224 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005225
Anders Carlsson525b76b2009-10-16 02:48:28 +00005226 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005227 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005228 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005229 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005230 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005231
John McCalld7646252010-11-14 08:17:51 +00005232 // The type we're casting to is known to be a scalar or vector.
5233
5234 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005235 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005236 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005237 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005238 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005239 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005240 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005241 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005242
5243 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005244 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005245
Anton Yartsev28ccef72011-03-27 09:32:40 +00005246 if (castType->isVectorType()) {
5247 if (castType->getAs<VectorType>()->getVectorKind() ==
5248 VectorType::AltiVecVector &&
5249 (castExpr->getType()->isIntegerType() ||
5250 castExpr->getType()->isFloatingType())) {
5251 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005252 return Owned(castExpr);
5253 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5254 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005255 } else
John Wiegley01296292011-04-08 18:41:53 +00005256 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005257 }
John Wiegley01296292011-04-08 18:41:53 +00005258 if (castExpr->getType()->isVectorType()) {
5259 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5260 return ExprError();
5261 else
5262 return Owned(castExpr);
5263 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005264
John McCalld7646252010-11-14 08:17:51 +00005265 // The source and target types are both scalars, i.e.
5266 // - arithmetic types (fundamental, enum, and complex)
5267 // - all kinds of pointers
5268 // Note that member pointers were filtered out with C++, above.
5269
John Wiegley01296292011-04-08 18:41:53 +00005270 if (isa<ObjCSelectorExpr>(castExpr)) {
5271 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5272 return ExprError();
5273 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005274
John McCalld7646252010-11-14 08:17:51 +00005275 // If either type is a pointer, the other type has to be either an
5276 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005277 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005278 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005279 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005280 castExprType->isArithmeticType()) {
5281 Diag(castExpr->getLocStart(),
5282 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005283 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005284 return ExprError();
5285 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005286 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005287 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5288 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005289 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005290 return ExprError();
5291 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005292 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005293
John Wiegley01296292011-04-08 18:41:53 +00005294 castExprRes = Owned(castExpr);
5295 Kind = PrepareScalarCast(*this, castExprRes, castType);
5296 if (castExprRes.isInvalid())
5297 return ExprError();
5298 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005299
John McCalld7646252010-11-14 08:17:51 +00005300 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005301 CheckCastAlign(castExpr, castType, TyR);
5302
John Wiegley01296292011-04-08 18:41:53 +00005303 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005304}
5305
Anders Carlsson525b76b2009-10-16 02:48:28 +00005306bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005307 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005308 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309
Anders Carlssonde71adf2007-11-27 05:51:55 +00005310 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005311 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005312 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005313 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005314 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005315 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005316 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005317 } else
5318 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005319 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005320 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005321
John McCalle3027922010-08-25 11:45:40 +00005322 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005323 return false;
5324}
5325
John Wiegley01296292011-04-08 18:41:53 +00005326ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5327 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005328 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005329
Anders Carlsson43d70f82009-10-16 05:23:41 +00005330 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005331
Nate Begemanc8961a42009-06-27 22:05:55 +00005332 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5333 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005334 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005335 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5336 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005337 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005338 return ExprError();
5339 }
John McCalle3027922010-08-25 11:45:40 +00005340 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005341 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005342 }
5343
Nate Begemanbd956c42009-06-28 02:36:38 +00005344 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005345 // conversion will take place first from scalar to elt type, and then
5346 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005347 if (SrcTy->isPointerType())
5348 return Diag(R.getBegin(),
5349 diag::err_invalid_conversion_between_vector_and_scalar)
5350 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005351
5352 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005353 ExprResult CastExprRes = Owned(CastExpr);
5354 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5355 if (CastExprRes.isInvalid())
5356 return ExprError();
5357 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005358
John McCalle3027922010-08-25 11:45:40 +00005359 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005360 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005361}
5362
John McCalldadc5752010-08-24 06:29:42 +00005363ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005364Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005365 SourceLocation RParenLoc, Expr *castExpr) {
5366 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005367 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005368
John McCall97513962010-01-15 18:39:57 +00005369 TypeSourceInfo *castTInfo;
5370 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5371 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005372 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005373
Nate Begeman5ec4b312009-08-10 23:49:36 +00005374 // If the Expr being casted is a ParenListExpr, handle it specially.
5375 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005376 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005377 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005378
John McCallb268a282010-08-23 23:25:46 +00005379 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005380}
5381
John McCalldadc5752010-08-24 06:29:42 +00005382ExprResult
John McCallebe54742010-01-15 18:56:44 +00005383Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005384 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005385 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005386 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005387 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005388 ExprResult CastResult =
5389 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5390 Kind, VK, BasePath);
5391 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005392 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005393 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005394
John McCallcf142162010-08-07 06:22:56 +00005395 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005396 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005397 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005398 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005399}
5400
Nate Begeman5ec4b312009-08-10 23:49:36 +00005401/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5402/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005403ExprResult
John McCallb268a282010-08-23 23:25:46 +00005404Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005405 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5406 if (!E)
5407 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005408
John McCalldadc5752010-08-24 06:29:42 +00005409 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005410
Nate Begeman5ec4b312009-08-10 23:49:36 +00005411 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005412 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5413 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005414
John McCallb268a282010-08-23 23:25:46 +00005415 if (Result.isInvalid()) return ExprError();
5416
5417 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005418}
5419
John McCalldadc5752010-08-24 06:29:42 +00005420ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005421Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005422 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005423 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005424 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005425 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005426 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005427
Anton Yartsev28ccef72011-03-27 09:32:40 +00005428 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005429 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005430 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5431 if (PE->getNumExprs() == 0) {
5432 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5433 return ExprError();
5434 }
John Thompson781ad172010-06-30 22:55:51 +00005435 if (PE->getNumExprs() == 1) {
5436 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005437 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005438 }
5439 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005440 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005441 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005442
Anton Yartsev28ccef72011-03-27 09:32:40 +00005443 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005444 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005445 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005446 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005447 // '(...)' form of vector initialization in AltiVec: the number of
5448 // initializers must be one or must match the size of the vector.
5449 // If a single value is specified in the initializer then it will be
5450 // replicated to all the components of the vector
5451 if (Ty->getAs<VectorType>()->getVectorKind() ==
5452 VectorType::AltiVecVector) {
5453 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5454 // The number of initializers must be one or must match the size of the
5455 // vector. If a single value is specified in the initializer then it will
5456 // be replicated to all the components of the vector
5457 if (PE->getNumExprs() == 1) {
5458 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005459 ExprResult Literal = Owned(PE->getExpr(0));
5460 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5461 PrepareScalarCast(*this, Literal, ElemTy));
5462 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005463 }
5464 else if (PE->getNumExprs() < numElems) {
5465 Diag(PE->getExprLoc(),
5466 diag::err_incorrect_number_of_vector_initializers);
5467 return ExprError();
5468 }
5469 else
5470 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5471 initExprs.push_back(PE->getExpr(i));
5472 }
5473 else
5474 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5475 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005476
5477 // FIXME: This means that pretty-printing the final AST will produce curly
5478 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005479 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5480 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005481 initExprs.size(), RParenLoc);
5482 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005483 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005484 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005485 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005486 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005487 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005488 if (Result.isInvalid()) return ExprError();
5489 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005490 }
5491}
5492
John McCalldadc5752010-08-24 06:29:42 +00005493ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005494 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005495 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005496 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005497 unsigned nexprs = Val.size();
5498 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005499 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5500 Expr *expr;
5501 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5502 expr = new (Context) ParenExpr(L, R, exprs[0]);
5503 else
5504 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005505 return Owned(expr);
5506}
5507
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005508/// \brief Emit a specialized diagnostic when one expression is a null pointer
5509/// constant and the other is not a pointer.
5510bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5511 SourceLocation QuestionLoc) {
5512 Expr *NullExpr = LHS;
5513 Expr *NonPointerExpr = RHS;
5514 Expr::NullPointerConstantKind NullKind =
5515 NullExpr->isNullPointerConstant(Context,
5516 Expr::NPC_ValueDependentIsNotNull);
5517
5518 if (NullKind == Expr::NPCK_NotNull) {
5519 NullExpr = RHS;
5520 NonPointerExpr = LHS;
5521 NullKind =
5522 NullExpr->isNullPointerConstant(Context,
5523 Expr::NPC_ValueDependentIsNotNull);
5524 }
5525
5526 if (NullKind == Expr::NPCK_NotNull)
5527 return false;
5528
5529 if (NullKind == Expr::NPCK_ZeroInteger) {
5530 // In this case, check to make sure that we got here from a "NULL"
5531 // string in the source code.
5532 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005533 SourceLocation loc = NullExpr->getExprLoc();
5534 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005535 return false;
5536 }
5537
5538 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5539 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5540 << NonPointerExpr->getType() << DiagType
5541 << NonPointerExpr->getSourceRange();
5542 return true;
5543}
5544
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005545/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5546/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005547/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005548QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005549 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005550 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005551
John Wiegley01296292011-04-08 18:41:53 +00005552 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get(), QuestionLoc);
John McCall31996342011-04-07 08:22:57 +00005553 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005554 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005555
John Wiegley01296292011-04-08 18:41:53 +00005556 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get(), QuestionLoc);
John McCall31996342011-04-07 08:22:57 +00005557 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005558 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005559
Sebastian Redl1a99f442009-04-16 17:51:27 +00005560 // C++ is sufficiently different to merit its own checker.
5561 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005562 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005563
5564 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005565 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005566
John Wiegley01296292011-04-08 18:41:53 +00005567 Cond = UsualUnaryConversions(Cond.take());
5568 if (Cond.isInvalid())
5569 return QualType();
5570 LHS = UsualUnaryConversions(LHS.take());
5571 if (LHS.isInvalid())
5572 return QualType();
5573 RHS = UsualUnaryConversions(RHS.take());
5574 if (RHS.isInvalid())
5575 return QualType();
5576
5577 QualType CondTy = Cond.get()->getType();
5578 QualType LHSTy = LHS.get()->getType();
5579 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005580
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005581 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005582 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005583 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5584 // Throw an error if its not either.
5585 if (getLangOptions().OpenCL) {
5586 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005587 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005588 diag::err_typecheck_cond_expect_scalar_or_vector)
5589 << CondTy;
5590 return QualType();
5591 }
5592 }
5593 else {
John Wiegley01296292011-04-08 18:41:53 +00005594 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005595 << CondTy;
5596 return QualType();
5597 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005598 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005599
Chris Lattnere2949f42008-01-06 22:42:25 +00005600 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005601 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5602 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005603
Nate Begemanabb5a732010-09-20 22:41:17 +00005604 // OpenCL: If the condition is a vector, and both operands are scalar,
5605 // attempt to implicity convert them to the vector type to act like the
5606 // built in select.
5607 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5608 // Both operands should be of scalar type.
5609 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005610 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005611 << CondTy;
5612 return QualType();
5613 }
5614 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005615 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005616 << CondTy;
5617 return QualType();
5618 }
5619 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005620 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5621 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005622 }
5623
Chris Lattnere2949f42008-01-06 22:42:25 +00005624 // If both operands have arithmetic type, do the usual arithmetic conversions
5625 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005626 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5627 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005628 if (LHS.isInvalid() || RHS.isInvalid())
5629 return QualType();
5630 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005631 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005632
Chris Lattnere2949f42008-01-06 22:42:25 +00005633 // If both operands are the same structure or union type, the result is that
5634 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005635 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5636 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005637 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005638 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005639 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005640 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005641 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005642 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005643
Chris Lattnere2949f42008-01-06 22:42:25 +00005644 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005645 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005646 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5647 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005648 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5649 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005650 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005651 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5652 << LHS.get()->getSourceRange();
5653 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5654 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005655 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005656 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005657 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5658 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005659 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005660 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005661 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005662 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005663 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005664 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005665 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005666 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5667 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005668 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005669 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005670
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005671 // All objective-c pointer type analysis is done here.
5672 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5673 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005674 if (LHS.isInvalid() || RHS.isInvalid())
5675 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005676 if (!compositeType.isNull())
5677 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005678
5679
Steve Naroff05efa972009-07-01 14:36:47 +00005680 // Handle block pointer types.
5681 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5682 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5683 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5684 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005685 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5686 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005687 return destType;
5688 }
5689 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005690 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005691 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005692 }
Steve Naroff05efa972009-07-01 14:36:47 +00005693 // We have 2 block pointer types.
5694 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5695 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005696 return LHSTy;
5697 }
Steve Naroff05efa972009-07-01 14:36:47 +00005698 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005699 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5700 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005701
Steve Naroff05efa972009-07-01 14:36:47 +00005702 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5703 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005704 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005705 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005706 // In this situation, we assume void* type. No especially good
5707 // reason, but this is what gcc does, and we do have to pick
5708 // to get a consistent AST.
5709 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005710 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5711 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005712 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005713 }
Steve Naroff05efa972009-07-01 14:36:47 +00005714 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005715 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5716 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005717 return LHSTy;
5718 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005719
Steve Naroff05efa972009-07-01 14:36:47 +00005720 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5721 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5722 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005723 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5724 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005725
5726 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5727 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5728 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005729 QualType destPointee
5730 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005731 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005732 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005733 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005734 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005735 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005736 return destType;
5737 }
5738 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005739 QualType destPointee
5740 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005741 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005742 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005743 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005744 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005745 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005746 return destType;
5747 }
5748
5749 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5750 // Two identical pointer types are always compatible.
5751 return LHSTy;
5752 }
5753 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5754 rhptee.getUnqualifiedType())) {
5755 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005756 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005757 // In this situation, we assume void* type. No especially good
5758 // reason, but this is what gcc does, and we do have to pick
5759 // to get a consistent AST.
5760 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005761 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5762 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005763 return incompatTy;
5764 }
5765 // The pointer types are compatible.
5766 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5767 // differently qualified versions of compatible types, the result type is
5768 // a pointer to an appropriately qualified version of the *composite*
5769 // type.
5770 // FIXME: Need to calculate the composite type.
5771 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005772 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5773 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005774 return LHSTy;
5775 }
Mike Stump11289f42009-09-09 15:08:12 +00005776
John McCalle84af4e2010-11-13 01:35:44 +00005777 // GCC compatibility: soften pointer/integer mismatch. Note that
5778 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005779 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5780 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005781 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5782 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005783 return RHSTy;
5784 }
5785 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5786 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005787 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5788 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005789 return LHSTy;
5790 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005791
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005792 // Emit a better diagnostic if one of the expressions is a null pointer
5793 // constant and the other is not a pointer type. In this case, the user most
5794 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005795 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005796 return QualType();
5797
Chris Lattnere2949f42008-01-06 22:42:25 +00005798 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005799 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005800 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005801 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005802}
5803
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005804/// FindCompositeObjCPointerType - Helper method to find composite type of
5805/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005806QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005807 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005808 QualType LHSTy = LHS.get()->getType();
5809 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005810
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005811 // Handle things like Class and struct objc_class*. Here we case the result
5812 // to the pseudo-builtin, because that will be implicitly cast back to the
5813 // redefinition type if an attempt is made to access its fields.
5814 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005815 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005816 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005817 return LHSTy;
5818 }
5819 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005820 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005821 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005822 return RHSTy;
5823 }
5824 // And the same for struct objc_object* / id
5825 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005826 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005827 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005828 return LHSTy;
5829 }
5830 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005831 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005832 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005833 return RHSTy;
5834 }
5835 // And the same for struct objc_selector* / SEL
5836 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005837 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005838 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005839 return LHSTy;
5840 }
5841 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005842 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005843 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005844 return RHSTy;
5845 }
5846 // Check constraints for Objective-C object pointers types.
5847 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005848
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005849 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5850 // Two identical object pointer types are always compatible.
5851 return LHSTy;
5852 }
5853 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5854 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5855 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005856
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005857 // If both operands are interfaces and either operand can be
5858 // assigned to the other, use that type as the composite
5859 // type. This allows
5860 // xxx ? (A*) a : (B*) b
5861 // where B is a subclass of A.
5862 //
5863 // Additionally, as for assignment, if either type is 'id'
5864 // allow silent coercion. Finally, if the types are
5865 // incompatible then make sure to use 'id' as the composite
5866 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005867
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005868 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5869 // It could return the composite type.
5870 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5871 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5872 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5873 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5874 } else if ((LHSTy->isObjCQualifiedIdType() ||
5875 RHSTy->isObjCQualifiedIdType()) &&
5876 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5877 // Need to handle "id<xx>" explicitly.
5878 // GCC allows qualified id and any Objective-C type to devolve to
5879 // id. Currently localizing to here until clear this should be
5880 // part of ObjCQualifiedIdTypesAreCompatible.
5881 compositeType = Context.getObjCIdType();
5882 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5883 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005884 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005885 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5886 ;
5887 else {
5888 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5889 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005891 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005892 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5893 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005894 return incompatTy;
5895 }
5896 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005897 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5898 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005899 return compositeType;
5900 }
5901 // Check Objective-C object pointer types and 'void *'
5902 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5903 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5904 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5905 QualType destPointee
5906 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5907 QualType destType = Context.getPointerType(destPointee);
5908 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005909 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005910 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005911 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005912 return destType;
5913 }
5914 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5915 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5916 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5917 QualType destPointee
5918 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5919 QualType destType = Context.getPointerType(destPointee);
5920 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005921 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005922 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005923 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005924 return destType;
5925 }
5926 return QualType();
5927}
5928
Steve Naroff83895f72007-09-16 03:34:24 +00005929/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005930/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005931ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005932 SourceLocation ColonLoc,
5933 Expr *CondExpr, Expr *LHSExpr,
5934 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005935 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5936 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005937 OpaqueValueExpr *opaqueValue = 0;
5938 Expr *commonExpr = 0;
5939 if (LHSExpr == 0) {
5940 commonExpr = CondExpr;
5941
5942 // We usually want to apply unary conversions *before* saving, except
5943 // in the special case of a C++ l-value conditional.
5944 if (!(getLangOptions().CPlusPlus
5945 && !commonExpr->isTypeDependent()
5946 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5947 && commonExpr->isGLValue()
5948 && commonExpr->isOrdinaryOrBitFieldObject()
5949 && RHSExpr->isOrdinaryOrBitFieldObject()
5950 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005951 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5952 if (commonRes.isInvalid())
5953 return ExprError();
5954 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005955 }
5956
5957 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5958 commonExpr->getType(),
5959 commonExpr->getValueKind(),
5960 commonExpr->getObjectKind());
5961 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005962 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005963
John McCall7decc9e2010-11-18 06:31:45 +00005964 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005965 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005966 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5967 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005968 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005969 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5970 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005971 return ExprError();
5972
John McCallc07a0c72011-02-17 10:25:35 +00005973 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005974 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5975 LHS.take(), ColonLoc,
5976 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005977
5978 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005979 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5980 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005981}
5982
John McCallaba90822011-01-31 23:13:11 +00005983// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005984// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005985// routine is it effectively iqnores the qualifiers on the top level pointee.
5986// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5987// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005988static Sema::AssignConvertType
5989checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5990 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5991 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992
Steve Naroff1f4d7272007-05-11 04:00:31 +00005993 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005994 const Type *lhptee, *rhptee;
5995 Qualifiers lhq, rhq;
5996 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5997 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005998
John McCallaba90822011-01-31 23:13:11 +00005999 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006000
6001 // C99 6.5.16.1p1: This following citation is common to constraints
6002 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6003 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006004 Qualifiers lq;
6005
6006 if (!lhq.compatiblyIncludes(rhq)) {
6007 // Treat address-space mismatches as fatal. TODO: address subspaces
6008 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6009 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6010
John McCall78535952011-03-26 02:56:45 +00006011 // It's okay to add or remove GC qualifiers when converting to
6012 // and from void*.
6013 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6014 && (lhptee->isVoidType() || rhptee->isVoidType()))
6015 ; // keep old
6016
John McCall4fff8f62011-02-01 00:10:29 +00006017 // For GCC compatibility, other qualifier mismatches are treated
6018 // as still compatible in C.
6019 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6020 }
Steve Naroff3f597292007-05-11 22:18:03 +00006021
Mike Stump4e1f26a2009-02-19 03:04:26 +00006022 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6023 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006024 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006025 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006026 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006027 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006028
Chris Lattner0a788432008-01-03 22:56:36 +00006029 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006030 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006031 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006032 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006033
Chris Lattner0a788432008-01-03 22:56:36 +00006034 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006035 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006036 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006037
6038 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006039 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006040 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006041 }
John McCall4fff8f62011-02-01 00:10:29 +00006042
Mike Stump4e1f26a2009-02-19 03:04:26 +00006043 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006044 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006045 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6046 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006047 // Check if the pointee types are compatible ignoring the sign.
6048 // We explicitly check for char so that we catch "char" vs
6049 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006050 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006051 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006052 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006053 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006054
Chris Lattnerec3a1562009-10-17 20:33:28 +00006055 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006056 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006057 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006058 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006059
John McCall4fff8f62011-02-01 00:10:29 +00006060 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006061 // Types are compatible ignoring the sign. Qualifier incompatibility
6062 // takes priority over sign incompatibility because the sign
6063 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006064 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006065 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006066
John McCallaba90822011-01-31 23:13:11 +00006067 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006068 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006069
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006070 // If we are a multi-level pointer, it's possible that our issue is simply
6071 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6072 // the eventual target type is the same and the pointers have the same
6073 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006074 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006075 do {
John McCall4fff8f62011-02-01 00:10:29 +00006076 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6077 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006078 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006079
John McCall4fff8f62011-02-01 00:10:29 +00006080 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006081 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006082 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006083
Eli Friedman80160bd2009-03-22 23:59:44 +00006084 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006085 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006086 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006087 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006088}
6089
John McCallaba90822011-01-31 23:13:11 +00006090/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006091/// block pointer types are compatible or whether a block and normal pointer
6092/// are compatible. It is more restrict than comparing two function pointer
6093// types.
John McCallaba90822011-01-31 23:13:11 +00006094static Sema::AssignConvertType
6095checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6096 QualType rhsType) {
6097 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6098 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6099
Steve Naroff081c7422008-09-04 15:10:53 +00006100 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006101
Steve Naroff081c7422008-09-04 15:10:53 +00006102 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006103 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6104 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006105
John McCallaba90822011-01-31 23:13:11 +00006106 // In C++, the types have to match exactly.
6107 if (S.getLangOptions().CPlusPlus)
6108 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006109
John McCallaba90822011-01-31 23:13:11 +00006110 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006111
Steve Naroff081c7422008-09-04 15:10:53 +00006112 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006113 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6114 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006115
John McCallaba90822011-01-31 23:13:11 +00006116 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6117 return Sema::IncompatibleBlockPointer;
6118
Steve Naroff081c7422008-09-04 15:10:53 +00006119 return ConvTy;
6120}
6121
John McCallaba90822011-01-31 23:13:11 +00006122/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006123/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006124static Sema::AssignConvertType
6125checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6126 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6127 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6128
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006129 if (lhsType->isObjCBuiltinType()) {
6130 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006131 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6132 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006133 return Sema::IncompatiblePointer;
6134 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006135 }
6136 if (rhsType->isObjCBuiltinType()) {
6137 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006138 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6139 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006140 return Sema::IncompatiblePointer;
6141 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006142 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006143 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006144 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006145 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006146 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006147
John McCallaba90822011-01-31 23:13:11 +00006148 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6149 return Sema::CompatiblePointerDiscardsQualifiers;
6150
6151 if (S.Context.typesAreCompatible(lhsType, rhsType))
6152 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006153 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006154 return Sema::IncompatibleObjCQualifiedId;
6155 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006156}
6157
John McCall29600e12010-11-16 02:32:08 +00006158Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006159Sema::CheckAssignmentConstraints(SourceLocation Loc,
6160 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006161 // Fake up an opaque expression. We don't actually care about what
6162 // cast operations are required, so if CheckAssignmentConstraints
6163 // adds casts to this they'll be wasted, but fortunately that doesn't
6164 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006165 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006166 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006167 CastKind K = CK_Invalid;
6168
6169 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6170}
6171
Mike Stump4e1f26a2009-02-19 03:04:26 +00006172/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6173/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006174/// pointers. Here are some objectionable examples that GCC considers warnings:
6175///
6176/// int a, *pint;
6177/// short *pshort;
6178/// struct foo *pfoo;
6179///
6180/// pint = pshort; // warning: assignment from incompatible pointer type
6181/// a = pint; // warning: assignment makes integer from pointer without a cast
6182/// pint = a; // warning: assignment makes pointer from integer without a cast
6183/// pint = pfoo; // warning: assignment from incompatible pointer type
6184///
6185/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006186/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006187///
John McCall8cb679e2010-11-15 09:13:47 +00006188/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006189Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006190Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006191 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006192 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006193
Chris Lattnera52c2f22008-01-04 23:18:45 +00006194 // Get canonical types. We're not formatting these types, just comparing
6195 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006196 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6197 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006198
John McCalle5255932011-01-31 22:28:28 +00006199 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006200 if (lhsType == rhsType) {
6201 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006202 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006203 }
6204
Douglas Gregor6b754842008-10-28 00:22:11 +00006205 // If the left-hand side is a reference type, then we are in a
6206 // (rare!) case where we've allowed the use of references in C,
6207 // e.g., as a parameter type in a built-in function. In this case,
6208 // just make sure that the type referenced is compatible with the
6209 // right-hand side type. The caller is responsible for adjusting
6210 // lhsType so that the resulting expression does not have reference
6211 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006212 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006213 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6214 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006215 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006216 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006217 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006218 }
John McCalle5255932011-01-31 22:28:28 +00006219
Nate Begemanbd956c42009-06-28 02:36:38 +00006220 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6221 // to the same ExtVector type.
6222 if (lhsType->isExtVectorType()) {
6223 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006224 return Incompatible;
6225 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006226 // CK_VectorSplat does T -> vector T, so first cast to the
6227 // element type.
6228 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6229 if (elType != rhsType) {
6230 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006231 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006232 }
6233 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006234 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006235 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006236 }
Mike Stump11289f42009-09-09 15:08:12 +00006237
John McCalle5255932011-01-31 22:28:28 +00006238 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006239 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006240 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006241 // Allow assignments of an AltiVec vector type to an equivalent GCC
6242 // vector type and vice versa
6243 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6244 Kind = CK_BitCast;
6245 return Compatible;
6246 }
6247
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006248 // If we are allowing lax vector conversions, and LHS and RHS are both
6249 // vectors, the total size only needs to be the same. This is a bitcast;
6250 // no bits are changed but the result type is different.
6251 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006252 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006253 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006254 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006255 }
Chris Lattner881a2122008-01-04 23:32:24 +00006256 }
6257 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006258 }
Eli Friedman3360d892008-05-30 18:07:22 +00006259
John McCalle5255932011-01-31 22:28:28 +00006260 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006261 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006262 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006263 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006264 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006265 }
Eli Friedman3360d892008-05-30 18:07:22 +00006266
John McCalle5255932011-01-31 22:28:28 +00006267 // Conversions to normal pointers.
6268 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6269 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006270 if (isa<PointerType>(rhsType)) {
6271 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006272 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006273 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006274
John McCalle5255932011-01-31 22:28:28 +00006275 // int -> T*
6276 if (rhsType->isIntegerType()) {
6277 Kind = CK_IntegralToPointer; // FIXME: null?
6278 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006279 }
John McCalle5255932011-01-31 22:28:28 +00006280
6281 // C pointers are not compatible with ObjC object pointers,
6282 // with two exceptions:
6283 if (isa<ObjCObjectPointerType>(rhsType)) {
6284 // - conversions to void*
6285 if (lhsPointer->getPointeeType()->isVoidType()) {
6286 Kind = CK_AnyPointerToObjCPointerCast;
6287 return Compatible;
6288 }
6289
6290 // - conversions from 'Class' to the redefinition type
6291 if (rhsType->isObjCClassType() &&
6292 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006293 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006294 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006295 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006296
John McCalle5255932011-01-31 22:28:28 +00006297 Kind = CK_BitCast;
6298 return IncompatiblePointer;
6299 }
6300
6301 // U^ -> void*
6302 if (rhsType->getAs<BlockPointerType>()) {
6303 if (lhsPointer->getPointeeType()->isVoidType()) {
6304 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006305 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006306 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006307 }
John McCalle5255932011-01-31 22:28:28 +00006308
Steve Naroff081c7422008-09-04 15:10:53 +00006309 return Incompatible;
6310 }
6311
John McCalle5255932011-01-31 22:28:28 +00006312 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006313 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006314 // U^ -> T^
6315 if (rhsType->isBlockPointerType()) {
6316 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006317 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006318 }
6319
6320 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006321 if (rhsType->isIntegerType()) {
6322 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006323 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006324 }
6325
John McCalle5255932011-01-31 22:28:28 +00006326 // id -> T^
6327 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6328 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006329 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006330 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006331
John McCalle5255932011-01-31 22:28:28 +00006332 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006333 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006334 if (RHSPT->getPointeeType()->isVoidType()) {
6335 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006336 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006337 }
John McCall8cb679e2010-11-15 09:13:47 +00006338
Chris Lattnera52c2f22008-01-04 23:18:45 +00006339 return Incompatible;
6340 }
6341
John McCalle5255932011-01-31 22:28:28 +00006342 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006343 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006344 // A* -> B*
6345 if (rhsType->isObjCObjectPointerType()) {
6346 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006347 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006348 }
6349
6350 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006351 if (rhsType->isIntegerType()) {
6352 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006353 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006354 }
6355
John McCalle5255932011-01-31 22:28:28 +00006356 // In general, C pointers are not compatible with ObjC object pointers,
6357 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006358 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006359 // - conversions from 'void*'
6360 if (rhsType->isVoidPointerType()) {
6361 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006362 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006363 }
6364
6365 // - conversions to 'Class' from its redefinition type
6366 if (lhsType->isObjCClassType() &&
6367 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6368 Kind = CK_BitCast;
6369 return Compatible;
6370 }
6371
6372 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006373 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006374 }
John McCalle5255932011-01-31 22:28:28 +00006375
6376 // T^ -> A*
6377 if (rhsType->isBlockPointerType()) {
6378 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006379 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006380 }
6381
Steve Naroff7cae42b2009-07-10 23:34:53 +00006382 return Incompatible;
6383 }
John McCalle5255932011-01-31 22:28:28 +00006384
6385 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006386 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006387 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006388 if (lhsType == Context.BoolTy) {
6389 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006390 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006391 }
Eli Friedman3360d892008-05-30 18:07:22 +00006392
John McCalle5255932011-01-31 22:28:28 +00006393 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006394 if (lhsType->isIntegerType()) {
6395 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006396 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006398
Chris Lattnera52c2f22008-01-04 23:18:45 +00006399 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006400 }
John McCalle5255932011-01-31 22:28:28 +00006401
6402 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006403 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006404 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006405 if (lhsType == Context.BoolTy) {
6406 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006407 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006408 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006409
John McCalle5255932011-01-31 22:28:28 +00006410 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006411 if (lhsType->isIntegerType()) {
6412 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006413 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006414 }
6415
Steve Naroff7cae42b2009-07-10 23:34:53 +00006416 return Incompatible;
6417 }
Eli Friedman3360d892008-05-30 18:07:22 +00006418
John McCalle5255932011-01-31 22:28:28 +00006419 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006420 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006421 if (Context.typesAreCompatible(lhsType, rhsType)) {
6422 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006423 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006424 }
Bill Wendling216423b2007-05-30 06:30:29 +00006425 }
John McCalle5255932011-01-31 22:28:28 +00006426
Steve Naroff98cf3e92007-06-06 18:38:38 +00006427 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006428}
6429
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006430/// \brief Constructs a transparent union from an expression that is
6431/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006432static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006433 QualType UnionType, FieldDecl *Field) {
6434 // Build an initializer list that designates the appropriate member
6435 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006436 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006437 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006438 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006439 SourceLocation());
6440 Initializer->setType(UnionType);
6441 Initializer->setInitializedFieldInUnion(Field);
6442
6443 // Build a compound literal constructing a value of the transparent
6444 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006445 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006446 EResult = S.Owned(
6447 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6448 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006449}
6450
6451Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006452Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6453 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006454
Mike Stump11289f42009-09-09 15:08:12 +00006455 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006456 // transparent_union GCC extension.
6457 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006458 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006459 return Incompatible;
6460
6461 // The field to initialize within the transparent union.
6462 RecordDecl *UD = UT->getDecl();
6463 FieldDecl *InitField = 0;
6464 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006465 for (RecordDecl::field_iterator it = UD->field_begin(),
6466 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006467 it != itend; ++it) {
6468 if (it->getType()->isPointerType()) {
6469 // If the transparent union contains a pointer type, we allow:
6470 // 1) void pointer
6471 // 2) null pointer constant
6472 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006473 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006474 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006475 InitField = *it;
6476 break;
6477 }
Mike Stump11289f42009-09-09 15:08:12 +00006478
John Wiegley01296292011-04-08 18:41:53 +00006479 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006480 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006481 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006482 InitField = *it;
6483 break;
6484 }
6485 }
6486
John McCall8cb679e2010-11-15 09:13:47 +00006487 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006488 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006489 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006490 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006491 InitField = *it;
6492 break;
6493 }
6494 }
6495
6496 if (!InitField)
6497 return Incompatible;
6498
John Wiegley01296292011-04-08 18:41:53 +00006499 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006500 return Compatible;
6501}
6502
Chris Lattner9bad62c2008-01-04 18:04:52 +00006503Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006504Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006505 if (getLangOptions().CPlusPlus) {
6506 if (!lhsType->isRecordType()) {
6507 // C++ 5.17p3: If the left operand is not of class type, the
6508 // expression is implicitly converted (C++ 4) to the
6509 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006510 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6511 lhsType.getUnqualifiedType(),
6512 AA_Assigning);
6513 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006514 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006515 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006516 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006517 }
6518
6519 // FIXME: Currently, we fall through and treat C++ classes like C
6520 // structures.
John McCall34376a62010-12-04 03:47:34 +00006521 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006522
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006523 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6524 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006525 if ((lhsType->isPointerType() ||
6526 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006527 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006528 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006529 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006530 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006531 return Compatible;
6532 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
Chris Lattnere6dcd502007-10-16 02:55:40 +00006534 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006535 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006536 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006537 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006538 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006539 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006540 if (!lhsType->isReferenceType()) {
6541 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6542 if (rExpr.isInvalid())
6543 return Incompatible;
6544 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006545
John McCall8cb679e2010-11-15 09:13:47 +00006546 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006547 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006548 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006550 // C99 6.5.16.1p2: The value of the right operand is converted to the
6551 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006552 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6553 // so that we can use references in built-in functions even in C.
6554 // The getNonReferenceType() call makes sure that the resulting expression
6555 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006556 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6557 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006558 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006559}
6560
John Wiegley01296292011-04-08 18:41:53 +00006561QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006562 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006563 << lex.get()->getType() << rex.get()->getType()
6564 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006565 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006566}
6567
John Wiegley01296292011-04-08 18:41:53 +00006568QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006569 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006570 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006571 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006572 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006573 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006574 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006575
Nate Begeman191a6b12008-07-14 18:02:46 +00006576 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006577 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006578 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006579
Nate Begeman191a6b12008-07-14 18:02:46 +00006580 // Handle the case of a vector & extvector type of the same size and element
6581 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006582 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006583 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006584 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006585 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006586 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006587 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006588 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006589 return lhsType;
6590 }
6591
John Wiegley01296292011-04-08 18:41:53 +00006592 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006593 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006594 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6595 // If we are allowing lax vector conversions, and LHS and RHS are both
6596 // vectors, the total size only needs to be the same. This is a
6597 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006598 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006599 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006600 }
Eric Christophera613f562010-08-26 00:42:16 +00006601 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006602 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006603 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006604
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006605 // Handle the case of equivalent AltiVec and GCC vector types
6606 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6607 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006608 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006609 return rhsType;
6610 }
6611
Nate Begemanbd956c42009-06-28 02:36:38 +00006612 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6613 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6614 bool swapped = false;
6615 if (rhsType->isExtVectorType()) {
6616 swapped = true;
6617 std::swap(rex, lex);
6618 std::swap(rhsType, lhsType);
6619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Nate Begeman886448d2009-06-28 19:12:57 +00006621 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006622 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006623 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006624 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006625 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6626 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006627 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006628 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006629 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006630 if (swapped) std::swap(rex, lex);
6631 return lhsType;
6632 }
6633 }
6634 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6635 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006636 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6637 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006638 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006639 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006640 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006641 if (swapped) std::swap(rex, lex);
6642 return lhsType;
6643 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006644 }
6645 }
Mike Stump11289f42009-09-09 15:08:12 +00006646
Nate Begeman886448d2009-06-28 19:12:57 +00006647 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006648 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006649 << lex.get()->getType() << rex.get()->getType()
6650 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006651 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006652}
6653
Chris Lattnerfaa54172010-01-12 21:23:57 +00006654QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006655 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6656 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006657 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006658
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006659 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006660 if (lex.isInvalid() || rex.isInvalid())
6661 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006662
John Wiegley01296292011-04-08 18:41:53 +00006663 if (!lex.get()->getType()->isArithmeticType() ||
6664 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006665 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006666
Chris Lattnerfaa54172010-01-12 21:23:57 +00006667 // Check for division by zero.
6668 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006669 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6670 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6671 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006672
Chris Lattnerfaa54172010-01-12 21:23:57 +00006673 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006674}
6675
Chris Lattnerfaa54172010-01-12 21:23:57 +00006676QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006677 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6678 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6679 if (lex.get()->getType()->hasIntegerRepresentation() &&
6680 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006681 return CheckVectorOperands(Loc, lex, rex);
6682 return InvalidOperands(Loc, lex, rex);
6683 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006684
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006685 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006686 if (lex.isInvalid() || rex.isInvalid())
6687 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
John Wiegley01296292011-04-08 18:41:53 +00006689 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006690 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006691
Chris Lattnerfaa54172010-01-12 21:23:57 +00006692 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006693 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6694 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6695 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006696
Chris Lattnerfaa54172010-01-12 21:23:57 +00006697 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006698}
6699
Chris Lattnerfaa54172010-01-12 21:23:57 +00006700QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006701 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6702 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006703 QualType compType = CheckVectorOperands(Loc, lex, rex);
6704 if (CompLHSTy) *CompLHSTy = compType;
6705 return compType;
6706 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006707
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006708 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006709 if (lex.isInvalid() || rex.isInvalid())
6710 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006711
Steve Naroffe4718892007-04-27 18:30:00 +00006712 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006713 if (lex.get()->getType()->isArithmeticType() &&
6714 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006715 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006716 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006717 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006718
Eli Friedman8e122982008-05-18 18:08:51 +00006719 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006720 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006721 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006722 std::swap(PExp, IExp);
6723
Steve Naroff6b712a72009-07-14 18:25:06 +00006724 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006725
Eli Friedman8e122982008-05-18 18:08:51 +00006726 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006727 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006728
Chris Lattner12bdebb2009-04-24 23:50:08 +00006729 // Check for arithmetic on pointers to incomplete types.
6730 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006731 if (getLangOptions().CPlusPlus) {
6732 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006733 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006734 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006735 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006736
6737 // GNU extension: arithmetic on pointer to void
6738 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006739 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006740 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006741 if (getLangOptions().CPlusPlus) {
6742 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006743 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006744 return QualType();
6745 }
6746
6747 // GNU extension: arithmetic on pointer to function
6748 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006749 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006750 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006751 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006752 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006753 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006754 PExp->getType()->isObjCObjectPointerType()) &&
6755 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006756 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6757 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006758 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006759 return QualType();
6760 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006761 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006762 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006763 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6764 << PointeeTy << PExp->getSourceRange();
6765 return QualType();
6766 }
Mike Stump11289f42009-09-09 15:08:12 +00006767
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006768 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006769 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006770 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006771 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006772 if (LHSTy->isPromotableIntegerType())
6773 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006774 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006775 *CompLHSTy = LHSTy;
6776 }
Eli Friedman8e122982008-05-18 18:08:51 +00006777 return PExp->getType();
6778 }
6779 }
6780
Chris Lattner326f7572008-11-18 01:30:42 +00006781 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006782}
6783
Chris Lattner2a3569b2008-04-07 05:30:13 +00006784// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006785QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006786 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006787 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006788 QualType compType = CheckVectorOperands(Loc, lex, rex);
6789 if (CompLHSTy) *CompLHSTy = compType;
6790 return compType;
6791 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006792
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006793 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006794 if (lex.isInvalid() || rex.isInvalid())
6795 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006796
Chris Lattner4d62f422007-12-09 21:53:25 +00006797 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006798
Chris Lattner4d62f422007-12-09 21:53:25 +00006799 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006800 if (lex.get()->getType()->isArithmeticType() &&
6801 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006802 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006803 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006804 }
Mike Stump11289f42009-09-09 15:08:12 +00006805
Chris Lattner4d62f422007-12-09 21:53:25 +00006806 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006807 if (lex.get()->getType()->isAnyPointerType()) {
6808 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006809
Douglas Gregorac1fb652009-03-24 19:52:54 +00006810 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006811
Douglas Gregorac1fb652009-03-24 19:52:54 +00006812 bool ComplainAboutVoid = false;
6813 Expr *ComplainAboutFunc = 0;
6814 if (lpointee->isVoidType()) {
6815 if (getLangOptions().CPlusPlus) {
6816 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006817 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006818 return QualType();
6819 }
6820
6821 // GNU C extension: arithmetic on pointer to void
6822 ComplainAboutVoid = true;
6823 } else if (lpointee->isFunctionType()) {
6824 if (getLangOptions().CPlusPlus) {
6825 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006826 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006827 return QualType();
6828 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006829
6830 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00006831 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006832 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006833 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006834 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006835 << lex.get()->getSourceRange()
6836 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006837 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006838
Chris Lattner12bdebb2009-04-24 23:50:08 +00006839 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006840 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006841 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006842 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006843 return QualType();
6844 }
Mike Stump11289f42009-09-09 15:08:12 +00006845
Chris Lattner4d62f422007-12-09 21:53:25 +00006846 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006847 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006848 if (ComplainAboutVoid)
6849 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006850 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006851 if (ComplainAboutFunc)
6852 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006853 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006854 << ComplainAboutFunc->getSourceRange();
6855
John Wiegley01296292011-04-08 18:41:53 +00006856 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6857 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006858 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006859
Chris Lattner4d62f422007-12-09 21:53:25 +00006860 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00006861 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006862 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006863
Douglas Gregorac1fb652009-03-24 19:52:54 +00006864 // RHS must be a completely-type object type.
6865 // Handle the GNU void* extension.
6866 if (rpointee->isVoidType()) {
6867 if (getLangOptions().CPlusPlus) {
6868 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006869 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006870 return QualType();
6871 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006872
Douglas Gregorac1fb652009-03-24 19:52:54 +00006873 ComplainAboutVoid = true;
6874 } else if (rpointee->isFunctionType()) {
6875 if (getLangOptions().CPlusPlus) {
6876 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006877 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006878 return QualType();
6879 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006880
6881 // GNU extension: arithmetic on pointer to function
6882 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00006883 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006884 } else if (!rpointee->isDependentType() &&
6885 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006886 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006887 << rex.get()->getSourceRange()
6888 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006889 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006890
Eli Friedman168fe152009-05-16 13:54:38 +00006891 if (getLangOptions().CPlusPlus) {
6892 // Pointee types must be the same: C++ [expr.add]
6893 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6894 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006895 << lex.get()->getType() << rex.get()->getType()
6896 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006897 return QualType();
6898 }
6899 } else {
6900 // Pointee types must be compatible C99 6.5.6p3
6901 if (!Context.typesAreCompatible(
6902 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6903 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6904 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006905 << lex.get()->getType() << rex.get()->getType()
6906 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006907 return QualType();
6908 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006909 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006910
Douglas Gregorac1fb652009-03-24 19:52:54 +00006911 if (ComplainAboutVoid)
6912 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006913 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006914 if (ComplainAboutFunc)
6915 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006916 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006917 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006918
John Wiegley01296292011-04-08 18:41:53 +00006919 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006920 return Context.getPointerDiffType();
6921 }
6922 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006923
Chris Lattner326f7572008-11-18 01:30:42 +00006924 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006925}
6926
Douglas Gregor0bf31402010-10-08 23:50:27 +00006927static bool isScopedEnumerationType(QualType T) {
6928 if (const EnumType *ET = dyn_cast<EnumType>(T))
6929 return ET->getDecl()->isScoped();
6930 return false;
6931}
6932
John Wiegley01296292011-04-08 18:41:53 +00006933static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006934 SourceLocation Loc, unsigned Opc,
6935 QualType LHSTy) {
6936 llvm::APSInt Right;
6937 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00006938 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006939 return;
6940
6941 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006942 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006943 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006944 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006945 return;
6946 }
6947 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006948 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006949 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006950 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006951 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006952 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006953 return;
6954 }
6955 if (Opc != BO_Shl)
6956 return;
6957
6958 // When left shifting an ICE which is signed, we can check for overflow which
6959 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6960 // integers have defined behavior modulo one more than the maximum value
6961 // representable in the result type, so never warn for those.
6962 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00006963 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006964 LHSTy->hasUnsignedIntegerRepresentation())
6965 return;
6966 llvm::APInt ResultBits =
6967 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6968 if (LeftBits.uge(ResultBits))
6969 return;
6970 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6971 Result = Result.shl(Right);
6972
6973 // If we are only missing a sign bit, this is less likely to result in actual
6974 // bugs -- if the result is cast back to an unsigned type, it will have the
6975 // expected value. Thus we place this behind a different warning that can be
6976 // turned off separately if needed.
6977 if (LeftBits == ResultBits - 1) {
6978 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6979 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006980 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006981 return;
6982 }
6983
6984 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6985 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006986 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006987}
6988
Chris Lattner2a3569b2008-04-07 05:30:13 +00006989// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00006990QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006991 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006992 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006993 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6994 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006995 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006996
Douglas Gregor0bf31402010-10-08 23:50:27 +00006997 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6998 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006999 if (isScopedEnumerationType(lex.get()->getType()) ||
7000 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007001 return InvalidOperands(Loc, lex, rex);
7002 }
7003
Nate Begemane46ee9a2009-10-25 02:26:48 +00007004 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007005 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007006 return CheckVectorOperands(Loc, lex, rex);
7007
Chris Lattner5c11c412007-12-12 05:47:28 +00007008 // Shifts don't perform usual arithmetic conversions, they just do integer
7009 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007010
John McCall57cdd882010-12-16 19:28:59 +00007011 // For the LHS, do usual unary conversions, but then reset them away
7012 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007013 ExprResult old_lex = lex;
7014 lex = UsualUnaryConversions(lex.take());
7015 if (lex.isInvalid())
7016 return QualType();
7017 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007018 if (isCompAssign) lex = old_lex;
7019
7020 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007021 rex = UsualUnaryConversions(rex.take());
7022 if (rex.isInvalid())
7023 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007024
Ryan Flynnf53fab82009-08-07 16:20:20 +00007025 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007026 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007027
Chris Lattner5c11c412007-12-12 05:47:28 +00007028 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007029 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007030}
7031
Chandler Carruth17773fc2010-07-10 12:30:03 +00007032static bool IsWithinTemplateSpecialization(Decl *D) {
7033 if (DeclContext *DC = D->getDeclContext()) {
7034 if (isa<ClassTemplateSpecializationDecl>(DC))
7035 return true;
7036 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7037 return FD->isFunctionTemplateSpecialization();
7038 }
7039 return false;
7040}
7041
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007042// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007043QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007044 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007045 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007046
Chris Lattner9a152e22009-12-05 05:40:13 +00007047 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007048 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007049 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007050
John Wiegley01296292011-04-08 18:41:53 +00007051 QualType lType = lex.get()->getType();
7052 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007053
John Wiegley01296292011-04-08 18:41:53 +00007054 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7055 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007056 QualType LHSStrippedType = LHSStripped->getType();
7057 QualType RHSStrippedType = RHSStripped->getType();
7058
Douglas Gregor1beec452011-03-12 01:48:56 +00007059
7060
Chandler Carruth712563b2011-02-17 08:37:06 +00007061 // Two different enums will raise a warning when compared.
7062 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7063 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7064 if (LHSEnumType->getDecl()->getIdentifier() &&
7065 RHSEnumType->getDecl()->getIdentifier() &&
7066 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7067 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7068 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007069 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007070 }
7071 }
7072 }
7073
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007074 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007075 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007076 !lex.get()->getLocStart().isMacroID() &&
7077 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007078 // For non-floating point types, check for self-comparisons of the form
7079 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7080 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007081 //
7082 // NOTE: Don't warn about comparison expressions resulting from macro
7083 // expansion. Also don't warn about comparisons which are only self
7084 // comparisons within a template specialization. The warnings should catch
7085 // obvious cases in the definition of the template anyways. The idea is to
7086 // warn when the typed comparison operator will always evaluate to the same
7087 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007088 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007089 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007090 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007091 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007092 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007093 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007094 << (Opc == BO_EQ
7095 || Opc == BO_LE
7096 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007097 } else if (lType->isArrayType() && rType->isArrayType() &&
7098 !DRL->getDecl()->getType()->isReferenceType() &&
7099 !DRR->getDecl()->getType()->isReferenceType()) {
7100 // what is it always going to eval to?
7101 char always_evals_to;
7102 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007103 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007104 always_evals_to = 0; // false
7105 break;
John McCalle3027922010-08-25 11:45:40 +00007106 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007107 always_evals_to = 1; // true
7108 break;
7109 default:
7110 // best we can say is 'a constant'
7111 always_evals_to = 2; // e.g. array1 <= array2
7112 break;
7113 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007114 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007115 << 1 // array
7116 << always_evals_to);
7117 }
7118 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007119 }
Mike Stump11289f42009-09-09 15:08:12 +00007120
Chris Lattner222b8bd2009-03-08 19:39:53 +00007121 if (isa<CastExpr>(LHSStripped))
7122 LHSStripped = LHSStripped->IgnoreParenCasts();
7123 if (isa<CastExpr>(RHSStripped))
7124 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007125
Chris Lattner222b8bd2009-03-08 19:39:53 +00007126 // Warn about comparisons against a string constant (unless the other
7127 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007128 Expr *literalString = 0;
7129 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007130 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007131 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007132 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007133 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007134 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007135 } else if ((isa<StringLiteral>(RHSStripped) ||
7136 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007137 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007138 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007139 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007140 literalStringStripped = RHSStripped;
7141 }
7142
7143 if (literalString) {
7144 std::string resultComparison;
7145 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007146 case BO_LT: resultComparison = ") < 0"; break;
7147 case BO_GT: resultComparison = ") > 0"; break;
7148 case BO_LE: resultComparison = ") <= 0"; break;
7149 case BO_GE: resultComparison = ") >= 0"; break;
7150 case BO_EQ: resultComparison = ") == 0"; break;
7151 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007152 default: assert(false && "Invalid comparison operator");
7153 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007154
Ted Kremenek3427fac2011-02-23 01:52:04 +00007155 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007156 PDiag(diag::warn_stringcompare)
7157 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007158 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007159 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Douglas Gregorec170db2010-06-08 19:50:34 +00007162 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007163 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007164 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007165 if (lex.isInvalid() || rex.isInvalid())
7166 return QualType();
7167 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007168 else {
John Wiegley01296292011-04-08 18:41:53 +00007169 lex = UsualUnaryConversions(lex.take());
7170 if (lex.isInvalid())
7171 return QualType();
7172
7173 rex = UsualUnaryConversions(rex.take());
7174 if (rex.isInvalid())
7175 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007176 }
7177
John Wiegley01296292011-04-08 18:41:53 +00007178 lType = lex.get()->getType();
7179 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007180
Douglas Gregorca63811b2008-11-19 03:25:36 +00007181 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007182 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007183
Chris Lattnerb620c342007-08-26 01:18:55 +00007184 if (isRelational) {
7185 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007186 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007187 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007188 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007189 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007190 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007191
Chris Lattnerb620c342007-08-26 01:18:55 +00007192 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007193 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007194 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007195
John Wiegley01296292011-04-08 18:41:53 +00007196 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007197 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007198 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007199 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007200
Douglas Gregorf267edd2010-06-15 21:38:40 +00007201 // All of the following pointer-related warnings are GCC extensions, except
7202 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007203 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007204 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007205 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007206 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007207 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007208
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007209 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007210 if (LCanPointeeTy == RCanPointeeTy)
7211 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007212 if (!isRelational &&
7213 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7214 // Valid unless comparison between non-null pointer and function pointer
7215 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007216 // In a SFINAE context, we treat this as a hard error to maintain
7217 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007218 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7219 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007220 Diag(Loc,
7221 isSFINAEContext()?
7222 diag::err_typecheck_comparison_of_fptr_to_void
7223 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007224 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007225
7226 if (isSFINAEContext())
7227 return QualType();
7228
John Wiegley01296292011-04-08 18:41:53 +00007229 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007230 return ResultTy;
7231 }
7232 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007233
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007234 // C++ [expr.rel]p2:
7235 // [...] Pointer conversions (4.10) and qualification
7236 // conversions (4.4) are performed on pointer operands (or on
7237 // a pointer operand and a null pointer constant) to bring
7238 // them to their composite pointer type. [...]
7239 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007240 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007241 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007242 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007243 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007244 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007245 if (T.isNull()) {
7246 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007247 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007248 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007249 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007250 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007251 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007252 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007253 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007254 }
7255
John Wiegley01296292011-04-08 18:41:53 +00007256 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7257 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007258 return ResultTy;
7259 }
Eli Friedman16c209612009-08-23 00:27:47 +00007260 // C99 6.5.9p2 and C99 6.5.8p2
7261 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7262 RCanPointeeTy.getUnqualifiedType())) {
7263 // Valid unless a relational comparison of function pointers
7264 if (isRelational && LCanPointeeTy->isFunctionType()) {
7265 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007266 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007267 }
7268 } else if (!isRelational &&
7269 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7270 // Valid unless comparison between non-null pointer and function pointer
7271 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7272 && !LHSIsNull && !RHSIsNull) {
7273 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007274 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007275 }
7276 } else {
7277 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007278 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007279 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007280 }
John McCall7684dde2011-03-11 04:25:25 +00007281 if (LCanPointeeTy != RCanPointeeTy) {
7282 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007283 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007284 else
John Wiegley01296292011-04-08 18:41:53 +00007285 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007286 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007287 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007288 }
Mike Stump11289f42009-09-09 15:08:12 +00007289
Sebastian Redl576fd422009-05-10 18:38:11 +00007290 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007291 // Comparison of nullptr_t with itself.
7292 if (lType->isNullPtrType() && rType->isNullPtrType())
7293 return ResultTy;
7294
Mike Stump11289f42009-09-09 15:08:12 +00007295 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007296 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007297 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007298 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007299 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007300 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007301 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007302 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007303 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007304 return ResultTy;
7305 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007306 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007307 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007308 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007309 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007310 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007311 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007312 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007313 return ResultTy;
7314 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007315
7316 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007317 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007318 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7319 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007320 // In addition, pointers to members can be compared, or a pointer to
7321 // member and a null pointer constant. Pointer to member conversions
7322 // (4.11) and qualification conversions (4.4) are performed to bring
7323 // them to a common type. If one operand is a null pointer constant,
7324 // the common type is the type of the other operand. Otherwise, the
7325 // common type is a pointer to member type similar (4.4) to the type
7326 // of one of the operands, with a cv-qualification signature (4.4)
7327 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007328 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007329 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007330 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007331 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007332 if (T.isNull()) {
7333 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007334 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007335 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007336 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007337 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007338 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007339 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007340 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007341 }
Mike Stump11289f42009-09-09 15:08:12 +00007342
John Wiegley01296292011-04-08 18:41:53 +00007343 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7344 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007345 return ResultTy;
7346 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007347
7348 // Handle scoped enumeration types specifically, since they don't promote
7349 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007350 if (lex.get()->getType()->isEnumeralType() &&
7351 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007352 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007353 }
Mike Stump11289f42009-09-09 15:08:12 +00007354
Steve Naroff081c7422008-09-04 15:10:53 +00007355 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007356 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007357 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7358 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007359
Steve Naroff081c7422008-09-04 15:10:53 +00007360 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007361 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007362 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007363 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007364 }
John Wiegley01296292011-04-08 18:41:53 +00007365 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007366 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007367 }
John Wiegley01296292011-04-08 18:41:53 +00007368
Steve Naroffe18f94c2008-09-28 01:11:11 +00007369 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007370 if (!isRelational
7371 && ((lType->isBlockPointerType() && rType->isPointerType())
7372 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007373 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007374 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007375 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007376 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007377 ->getPointeeType()->isVoidType())))
7378 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007379 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007380 }
John McCall7684dde2011-03-11 04:25:25 +00007381 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007382 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007383 else
John Wiegley01296292011-04-08 18:41:53 +00007384 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007385 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007386 }
Steve Naroff081c7422008-09-04 15:10:53 +00007387
John McCall7684dde2011-03-11 04:25:25 +00007388 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7389 const PointerType *LPT = lType->getAs<PointerType>();
7390 const PointerType *RPT = rType->getAs<PointerType>();
7391 if (LPT || RPT) {
7392 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7393 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007394
Steve Naroff753567f2008-11-17 19:49:16 +00007395 if (!LPtrToVoid && !RPtrToVoid &&
7396 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007397 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007398 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007399 }
John McCall7684dde2011-03-11 04:25:25 +00007400 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007401 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007402 else
John Wiegley01296292011-04-08 18:41:53 +00007403 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007404 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007405 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007406 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007407 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007408 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007409 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007410 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007411 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007412 else
John Wiegley01296292011-04-08 18:41:53 +00007413 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007414 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007415 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007416 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007417 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7418 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007419 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007420 bool isError = false;
7421 if ((LHSIsNull && lType->isIntegerType()) ||
7422 (RHSIsNull && rType->isIntegerType())) {
7423 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007424 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007425 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007426 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007427 else if (getLangOptions().CPlusPlus) {
7428 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7429 isError = true;
7430 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007431 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007432
Chris Lattnerd99bd522009-08-23 00:03:44 +00007433 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007434 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007435 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007436 if (isError)
7437 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007438 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007439
7440 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007441 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007442 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007443 else
John Wiegley01296292011-04-08 18:41:53 +00007444 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007445 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007446 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007447 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007448
Steve Naroff4b191572008-09-04 16:56:14 +00007449 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007450 if (!isRelational && RHSIsNull
7451 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007452 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007453 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007454 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007455 if (!isRelational && LHSIsNull
7456 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007457 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007458 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007459 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007460
Chris Lattner326f7572008-11-18 01:30:42 +00007461 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007462}
7463
Nate Begeman191a6b12008-07-14 18:02:46 +00007464/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007465/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007466/// like a scalar comparison, a vector comparison produces a vector of integer
7467/// types.
John Wiegley01296292011-04-08 18:41:53 +00007468QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007469 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007470 bool isRelational) {
7471 // Check to make sure we're operating on vectors of the same type and width,
7472 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007473 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007474 if (vType.isNull())
7475 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007476
John Wiegley01296292011-04-08 18:41:53 +00007477 QualType lType = lex.get()->getType();
7478 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007479
Anton Yartsev530deb92011-03-27 15:36:07 +00007480 // If AltiVec, the comparison results in a numeric type, i.e.
7481 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007482 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007483 return Context.getLogicalOperationType();
7484
Nate Begeman191a6b12008-07-14 18:02:46 +00007485 // For non-floating point types, check for self-comparisons of the form
7486 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7487 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007488 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007489 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7490 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007491 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007492 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007493 PDiag(diag::warn_comparison_always)
7494 << 0 // self-
7495 << 2 // "a constant"
7496 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007497 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007498
Nate Begeman191a6b12008-07-14 18:02:46 +00007499 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007500 if (!isRelational && lType->hasFloatingRepresentation()) {
7501 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007502 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007503 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007504
Nate Begeman191a6b12008-07-14 18:02:46 +00007505 // Return the type for the comparison, which is the same as vector type for
7506 // integer vectors, or an integer type of identical size and number of
7507 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007508 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007509 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007510
John McCall9dd450b2009-09-21 23:43:11 +00007511 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007512 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007513 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007514 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007515 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007516 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7517
Mike Stump4e1f26a2009-02-19 03:04:26 +00007518 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007519 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007520 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7521}
7522
Steve Naroff218bc2b2007-05-04 21:54:46 +00007523inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007524 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7525 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7526 if (lex.get()->getType()->hasIntegerRepresentation() &&
7527 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007528 return CheckVectorOperands(Loc, lex, rex);
7529
7530 return InvalidOperands(Loc, lex, rex);
7531 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007532
John Wiegley01296292011-04-08 18:41:53 +00007533 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7534 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7535 if (lexResult.isInvalid() || rexResult.isInvalid())
7536 return QualType();
7537 lex = lexResult.take();
7538 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007539
John Wiegley01296292011-04-08 18:41:53 +00007540 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7541 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007542 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007543 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007544}
7545
Steve Naroff218bc2b2007-05-04 21:54:46 +00007546inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007547 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007548
7549 // Diagnose cases where the user write a logical and/or but probably meant a
7550 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7551 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007552 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7553 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007554 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007555 !Loc.isMacroID()) {
7556 // If the RHS can be constant folded, and if it constant folds to something
7557 // that isn't 0 or 1 (which indicate a potential logical operation that
7558 // happened to fold to true/false) then warn.
7559 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007560 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007561 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7562 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007563 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007564 << (Opc == BO_LAnd ? "&&" : "||")
7565 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007566 }
7567 }
Chris Lattner8406c512010-07-13 19:41:32 +00007568
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007569 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007570 lex = UsualUnaryConversions(lex.take());
7571 if (lex.isInvalid())
7572 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007573
John Wiegley01296292011-04-08 18:41:53 +00007574 rex = UsualUnaryConversions(rex.take());
7575 if (rex.isInvalid())
7576 return QualType();
7577
7578 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007579 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007580
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007581 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007582 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007583
John McCall4a2429a2010-06-04 00:29:51 +00007584 // The following is safe because we only use this method for
7585 // non-overloadable operands.
7586
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007587 // C++ [expr.log.and]p1
7588 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007589 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007590 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7591 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007592 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007593 lex = move(lexRes);
7594
7595 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7596 if (rexRes.isInvalid())
7597 return InvalidOperands(Loc, lex, rex);
7598 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007599
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007600 // C++ [expr.log.and]p2
7601 // C++ [expr.log.or]p2
7602 // The result is a bool.
7603 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007604}
7605
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007606/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7607/// is a read-only property; return true if so. A readonly property expression
7608/// depends on various declarations and thus must be treated specially.
7609///
Mike Stump11289f42009-09-09 15:08:12 +00007610static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007611 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7612 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007613 if (PropExpr->isImplicitProperty()) return false;
7614
7615 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7616 QualType BaseType = PropExpr->isSuperReceiver() ?
7617 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007618 PropExpr->getBase()->getType();
7619
John McCallb7bd14f2010-12-02 01:19:52 +00007620 if (const ObjCObjectPointerType *OPT =
7621 BaseType->getAsObjCInterfacePointerType())
7622 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7623 if (S.isPropertyReadonly(PDecl, IFace))
7624 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007625 }
7626 return false;
7627}
7628
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007629static bool IsConstProperty(Expr *E, Sema &S) {
7630 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7631 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7632 if (PropExpr->isImplicitProperty()) return false;
7633
7634 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7635 QualType T = PDecl->getType();
7636 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007637 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007638 CanQualType CT = S.Context.getCanonicalType(T);
7639 return CT.isConstQualified();
7640 }
7641 return false;
7642}
7643
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007644static bool IsReadonlyMessage(Expr *E, Sema &S) {
7645 if (E->getStmtClass() != Expr::MemberExprClass)
7646 return false;
7647 const MemberExpr *ME = cast<MemberExpr>(E);
7648 NamedDecl *Member = ME->getMemberDecl();
7649 if (isa<FieldDecl>(Member)) {
7650 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7651 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7652 return false;
7653 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7654 }
7655 return false;
7656}
7657
Chris Lattner30bd3272008-11-18 01:22:49 +00007658/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7659/// emit an error and return true. If so, return false.
7660static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007661 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007662 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007663 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007664 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7665 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007666 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7667 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007668 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7669 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007670 if (IsLV == Expr::MLV_Valid)
7671 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007672
Chris Lattner30bd3272008-11-18 01:22:49 +00007673 unsigned Diag = 0;
7674 bool NeedType = false;
7675 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007676 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007677 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007678 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7679 NeedType = true;
7680 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007681 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007682 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7683 NeedType = true;
7684 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007685 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007686 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7687 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007688 case Expr::MLV_Valid:
7689 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007690 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007691 case Expr::MLV_MemberFunction:
7692 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007693 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7694 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007695 case Expr::MLV_IncompleteType:
7696 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007697 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007698 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007699 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007700 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007701 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7702 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007703 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007704 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7705 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007706 case Expr::MLV_ReadonlyProperty:
7707 Diag = diag::error_readonly_property_assignment;
7708 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007709 case Expr::MLV_NoSetterProperty:
7710 Diag = diag::error_nosetter_property_assignment;
7711 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007712 case Expr::MLV_InvalidMessageExpression:
7713 Diag = diag::error_readonly_message_assignment;
7714 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007715 case Expr::MLV_SubObjCPropertySetting:
7716 Diag = diag::error_no_subobject_property_setting;
7717 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007718 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007719
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007720 SourceRange Assign;
7721 if (Loc != OrigLoc)
7722 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007723 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007724 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007725 else
Mike Stump11289f42009-09-09 15:08:12 +00007726 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007727 return true;
7728}
7729
7730
7731
7732// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007733QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007734 SourceLocation Loc,
7735 QualType CompoundType) {
7736 // Verify that LHS is a modifiable lvalue, and emit error if not.
7737 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007738 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007739
7740 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007741 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007742 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007743 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007744 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007745 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007746 if (LHS->getObjectKind() == OK_ObjCProperty) {
7747 ExprResult LHSResult = Owned(LHS);
7748 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7749 if (LHSResult.isInvalid())
7750 return QualType();
7751 LHS = LHSResult.take();
7752 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007753 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007754 if (RHS.isInvalid())
7755 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007756 // Special case of NSObject attributes on c-style pointer types.
7757 if (ConvTy == IncompatiblePointer &&
7758 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007759 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007760 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007761 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007762 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007763
John McCall7decc9e2010-11-18 06:31:45 +00007764 if (ConvTy == Compatible &&
7765 getLangOptions().ObjCNonFragileABI &&
7766 LHSType->isObjCObjectType())
7767 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7768 << LHSType;
7769
Chris Lattnerea714382008-08-21 18:04:13 +00007770 // If the RHS is a unary plus or minus, check to see if they = and + are
7771 // right next to each other. If so, the user may have typo'd "x =+ 4"
7772 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007773 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007774 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7775 RHSCheck = ICE->getSubExpr();
7776 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007777 if ((UO->getOpcode() == UO_Plus ||
7778 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007779 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007780 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007781 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7782 // And there is a space or other character before the subexpr of the
7783 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007784 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7785 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007786 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007787 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007788 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007789 }
Chris Lattnerea714382008-08-21 18:04:13 +00007790 }
7791 } else {
7792 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007793 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007794 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007795
Chris Lattner326f7572008-11-18 01:30:42 +00007796 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007797 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007798 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007799
Chris Lattner39561062010-07-07 06:14:23 +00007800
7801 // Check to see if the destination operand is a dereferenced null pointer. If
7802 // so, and if not volatile-qualified, this is undefined behavior that the
7803 // optimizer will delete, so warn about it. People sometimes try to use this
7804 // to get a deterministic trap and are surprised by clang's behavior. This
7805 // only handles the pattern "*null = whatever", which is a very syntactic
7806 // check.
7807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007808 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007809 UO->getSubExpr()->IgnoreParenCasts()->
7810 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7811 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007812 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7813 PDiag(diag::warn_indirection_through_null)
7814 << UO->getSubExpr()->getSourceRange());
7815 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7816 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007817 }
7818
Ted Kremenek64699be2011-02-16 01:57:07 +00007819 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007820 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007821
Steve Naroff98cf3e92007-06-06 18:38:38 +00007822 // C99 6.5.16p3: The type of an assignment expression is the type of the
7823 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007824 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007825 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7826 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007827 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007828 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007829 return (getLangOptions().CPlusPlus
7830 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007831}
7832
Chris Lattner326f7572008-11-18 01:30:42 +00007833// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007834static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007835 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007836 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007837
John Wiegley01296292011-04-08 18:41:53 +00007838 LHS = S.CheckPlaceholderExpr(LHS.take(), Loc);
7839 RHS = S.CheckPlaceholderExpr(RHS.take(), Loc);
7840 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007841 return QualType();
7842
John McCall73d36182010-10-12 07:14:40 +00007843 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7844 // operands, but not unary promotions.
7845 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007846
John McCall34376a62010-12-04 03:47:34 +00007847 // So we treat the LHS as a ignored value, and in C++ we allow the
7848 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007849 LHS = S.IgnoredValueConversions(LHS.take());
7850 if (LHS.isInvalid())
7851 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007852
7853 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007854 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7855 if (RHS.isInvalid())
7856 return QualType();
7857 if (!RHS.get()->getType()->isVoidType())
7858 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007859 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007860
John Wiegley01296292011-04-08 18:41:53 +00007861 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007862}
7863
Steve Naroff7a5af782007-07-13 16:58:59 +00007864/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7865/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007866static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7867 ExprValueKind &VK,
7868 SourceLocation OpLoc,
7869 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007870 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007871 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007872
Chris Lattner6b0cf142008-11-21 07:05:48 +00007873 QualType ResType = Op->getType();
7874 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007875
John McCall4bc41ae2010-11-18 19:01:18 +00007876 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007877 // Decrement of bool is not allowed.
7878 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007879 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007880 return QualType();
7881 }
7882 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007883 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007884 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007885 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007886 } else if (ResType->isAnyPointerType()) {
7887 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007888
Chris Lattner6b0cf142008-11-21 07:05:48 +00007889 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007890 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007891 if (S.getLangOptions().CPlusPlus) {
7892 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007893 << Op->getSourceRange();
7894 return QualType();
7895 }
7896
7897 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007898 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007899 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007900 if (S.getLangOptions().CPlusPlus) {
7901 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007902 << Op->getType() << Op->getSourceRange();
7903 return QualType();
7904 }
7905
John McCall4bc41ae2010-11-18 19:01:18 +00007906 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007907 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007908 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7909 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007910 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007911 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007912 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007913 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007914 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7915 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007916 << PointeeTy << Op->getSourceRange();
7917 return QualType();
7918 }
Eli Friedman090addd2010-01-03 00:20:48 +00007919 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007920 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007921 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007922 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007923 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007924 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007925 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007926 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7927 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007928 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7929 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007930 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007931 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007932 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007933 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007934 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007935 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007936 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007937 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007938 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007939 // In C++, a prefix increment is the same type as the operand. Otherwise
7940 // (in C or with postfix), the increment is the unqualified type of the
7941 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007942 if (isPrefix && S.getLangOptions().CPlusPlus) {
7943 VK = VK_LValue;
7944 return ResType;
7945 } else {
7946 VK = VK_RValue;
7947 return ResType.getUnqualifiedType();
7948 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007949}
7950
John Wiegley01296292011-04-08 18:41:53 +00007951ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007952 assert(E->getValueKind() == VK_LValue &&
7953 E->getObjectKind() == OK_ObjCProperty);
7954 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7955
7956 ExprValueKind VK = VK_RValue;
7957 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007958 if (const ObjCMethodDecl *GetterMethod =
7959 PRE->getImplicitPropertyGetter()) {
7960 QualType Result = GetterMethod->getResultType();
7961 VK = Expr::getValueKindForType(Result);
7962 }
7963 else {
7964 Diag(PRE->getLocation(), diag::err_getter_not_found)
7965 << PRE->getBase()->getType();
7966 }
John McCall34376a62010-12-04 03:47:34 +00007967 }
7968
7969 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7970 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007971
7972 ExprResult Result = MaybeBindToTemporary(E);
7973 if (!Result.isInvalid())
7974 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007975
7976 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007977}
7978
John Wiegley01296292011-04-08 18:41:53 +00007979void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
7980 assert(LHS.get()->getValueKind() == VK_LValue &&
7981 LHS.get()->getObjectKind() == OK_ObjCProperty);
7982 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007983
John Wiegley01296292011-04-08 18:41:53 +00007984 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007985 // If using property-dot syntax notation for assignment, and there is a
7986 // setter, RHS expression is being passed to the setter argument. So,
7987 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007988 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007989 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7990 LHSTy = (*P)->getType();
7991
7992 // Otherwise, if the getter returns an l-value, just call that.
7993 } else {
John Wiegley01296292011-04-08 18:41:53 +00007994 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007995 ExprValueKind VK = Expr::getValueKindForType(Result);
7996 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007997 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7998 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007999 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008000 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008001 }
John McCall34376a62010-12-04 03:47:34 +00008002 }
8003
8004 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008005 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008006 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008007 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008008 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008009 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008010 }
8011}
8012
8013
Anders Carlsson806700f2008-02-01 07:15:58 +00008014/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008015/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008016/// where the declaration is needed for type checking. We only need to
8017/// handle cases when the expression references a function designator
8018/// or is an lvalue. Here are some examples:
8019/// - &(x) => x
8020/// - &*****f => f for f a function designator.
8021/// - &s.xx => s
8022/// - &s.zz[1].yy -> s, if zz is an array
8023/// - *(x + 1) -> x, if x is an array
8024/// - &"123"[2] -> 0
8025/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008026static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008027 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008028 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008029 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008030 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008031 // If this is an arrow operator, the address is an offset from
8032 // the base's value, so the object the base refers to is
8033 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008034 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008035 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008036 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008037 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008038 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008039 // FIXME: This code shouldn't be necessary! We should catch the implicit
8040 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008041 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8042 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8043 if (ICE->getSubExpr()->getType()->isArrayType())
8044 return getPrimaryDecl(ICE->getSubExpr());
8045 }
8046 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008047 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008048 case Stmt::UnaryOperatorClass: {
8049 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008050
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008051 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008052 case UO_Real:
8053 case UO_Imag:
8054 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008055 return getPrimaryDecl(UO->getSubExpr());
8056 default:
8057 return 0;
8058 }
8059 }
Steve Naroff47500512007-04-19 23:00:49 +00008060 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008061 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008062 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008063 // If the result of an implicit cast is an l-value, we care about
8064 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008065 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008066 default:
8067 return 0;
8068 }
8069}
8070
8071/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008072/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008073/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008074/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008075/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008076/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008077/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008078static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8079 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008080 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008081 return S.Context.DependentTy;
8082 if (OrigOp->getType() == S.Context.OverloadTy)
8083 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00008084
John McCall4bc41ae2010-11-18 19:01:18 +00008085 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008086 if (PR.isInvalid()) return QualType();
8087 OrigOp = PR.take();
8088
John McCall8d08b9b2010-08-27 09:08:28 +00008089 // Make sure to ignore parentheses in subsequent checks
8090 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008091
John McCall4bc41ae2010-11-18 19:01:18 +00008092 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008093 // Implement C99-only parts of addressof rules.
8094 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008095 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008096 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8097 // (assuming the deref expression is valid).
8098 return uOp->getSubExpr()->getType();
8099 }
8100 // Technically, there should be a check for array subscript
8101 // expressions here, but the result of one is always an lvalue anyway.
8102 }
John McCallf3a88602011-02-03 08:15:49 +00008103 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008104 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008105
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008106 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008107 bool sfinae = S.isSFINAEContext();
8108 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8109 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008110 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008111 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008112 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008113 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008114 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008115 } else if (lval == Expr::LV_MemberFunction) {
8116 // If it's an instance method, make a member pointer.
8117 // The expression must have exactly the form &A::foo.
8118
8119 // If the underlying expression isn't a decl ref, give up.
8120 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008121 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008122 << OrigOp->getSourceRange();
8123 return QualType();
8124 }
8125 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8126 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8127
8128 // The id-expression was parenthesized.
8129 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008130 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008131 << OrigOp->getSourceRange();
8132
8133 // The method was named without a qualifier.
8134 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008135 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008136 << op->getSourceRange();
8137 }
8138
John McCall4bc41ae2010-11-18 19:01:18 +00008139 return S.Context.getMemberPointerType(op->getType(),
8140 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008141 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008142 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008143 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008144 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008145 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008146 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008147 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008148 return QualType();
8149 }
John McCall086a4642010-11-24 05:12:34 +00008150 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008151 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008152 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008153 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008154 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008155 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008156 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008157 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008158 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008159 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008160 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008161 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008162 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008163 << "property expression" << op->getSourceRange();
8164 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008165 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008166 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008167 // with the register storage-class specifier.
8168 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008169 // in C++ it is not error to take address of a register
8170 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008171 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008172 !S.getLangOptions().CPlusPlus) {
8173 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008174 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008175 return QualType();
8176 }
John McCalld14a8642009-11-21 08:51:07 +00008177 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008178 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008179 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008180 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008181 // Could be a pointer to member, though, if there is an explicit
8182 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008183 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008184 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008185 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008186 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008187 S.Diag(OpLoc,
8188 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008189 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008190 return QualType();
8191 }
Mike Stump11289f42009-09-09 15:08:12 +00008192
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008193 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8194 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008195 return S.Context.getMemberPointerType(op->getType(),
8196 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008197 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008198 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008199 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008200 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008201 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008202
Eli Friedmance7f9002009-05-16 23:27:50 +00008203 if (lval == Expr::LV_IncompleteVoidType) {
8204 // Taking the address of a void variable is technically illegal, but we
8205 // allow it in cases which are otherwise valid.
8206 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008207 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008208 }
8209
Steve Naroff47500512007-04-19 23:00:49 +00008210 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008211 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008212 return S.Context.getObjCObjectPointerType(op->getType());
8213 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008214}
8215
Chris Lattner9156f1b2010-07-05 19:17:26 +00008216/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008217static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8218 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008219 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008220 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008221
John Wiegley01296292011-04-08 18:41:53 +00008222 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8223 if (ConvResult.isInvalid())
8224 return QualType();
8225 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008226 QualType OpTy = Op->getType();
8227 QualType Result;
8228
8229 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8230 // is an incomplete type or void. It would be possible to warn about
8231 // dereferencing a void pointer, but it's completely well-defined, and such a
8232 // warning is unlikely to catch any mistakes.
8233 if (const PointerType *PT = OpTy->getAs<PointerType>())
8234 Result = PT->getPointeeType();
8235 else if (const ObjCObjectPointerType *OPT =
8236 OpTy->getAs<ObjCObjectPointerType>())
8237 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008238 else {
John McCall4bc41ae2010-11-18 19:01:18 +00008239 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008240 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008241 if (PR.take() != Op)
8242 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008243 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008244
Chris Lattner9156f1b2010-07-05 19:17:26 +00008245 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008246 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008247 << OpTy << Op->getSourceRange();
8248 return QualType();
8249 }
John McCall4bc41ae2010-11-18 19:01:18 +00008250
8251 // Dereferences are usually l-values...
8252 VK = VK_LValue;
8253
8254 // ...except that certain expressions are never l-values in C.
8255 if (!S.getLangOptions().CPlusPlus &&
8256 IsCForbiddenLValueType(S.Context, Result))
8257 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008258
8259 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008260}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008261
John McCalle3027922010-08-25 11:45:40 +00008262static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008263 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008264 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008265 switch (Kind) {
8266 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008267 case tok::periodstar: Opc = BO_PtrMemD; break;
8268 case tok::arrowstar: Opc = BO_PtrMemI; break;
8269 case tok::star: Opc = BO_Mul; break;
8270 case tok::slash: Opc = BO_Div; break;
8271 case tok::percent: Opc = BO_Rem; break;
8272 case tok::plus: Opc = BO_Add; break;
8273 case tok::minus: Opc = BO_Sub; break;
8274 case tok::lessless: Opc = BO_Shl; break;
8275 case tok::greatergreater: Opc = BO_Shr; break;
8276 case tok::lessequal: Opc = BO_LE; break;
8277 case tok::less: Opc = BO_LT; break;
8278 case tok::greaterequal: Opc = BO_GE; break;
8279 case tok::greater: Opc = BO_GT; break;
8280 case tok::exclaimequal: Opc = BO_NE; break;
8281 case tok::equalequal: Opc = BO_EQ; break;
8282 case tok::amp: Opc = BO_And; break;
8283 case tok::caret: Opc = BO_Xor; break;
8284 case tok::pipe: Opc = BO_Or; break;
8285 case tok::ampamp: Opc = BO_LAnd; break;
8286 case tok::pipepipe: Opc = BO_LOr; break;
8287 case tok::equal: Opc = BO_Assign; break;
8288 case tok::starequal: Opc = BO_MulAssign; break;
8289 case tok::slashequal: Opc = BO_DivAssign; break;
8290 case tok::percentequal: Opc = BO_RemAssign; break;
8291 case tok::plusequal: Opc = BO_AddAssign; break;
8292 case tok::minusequal: Opc = BO_SubAssign; break;
8293 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8294 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8295 case tok::ampequal: Opc = BO_AndAssign; break;
8296 case tok::caretequal: Opc = BO_XorAssign; break;
8297 case tok::pipeequal: Opc = BO_OrAssign; break;
8298 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008299 }
8300 return Opc;
8301}
8302
John McCalle3027922010-08-25 11:45:40 +00008303static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008304 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008305 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008306 switch (Kind) {
8307 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008308 case tok::plusplus: Opc = UO_PreInc; break;
8309 case tok::minusminus: Opc = UO_PreDec; break;
8310 case tok::amp: Opc = UO_AddrOf; break;
8311 case tok::star: Opc = UO_Deref; break;
8312 case tok::plus: Opc = UO_Plus; break;
8313 case tok::minus: Opc = UO_Minus; break;
8314 case tok::tilde: Opc = UO_Not; break;
8315 case tok::exclaim: Opc = UO_LNot; break;
8316 case tok::kw___real: Opc = UO_Real; break;
8317 case tok::kw___imag: Opc = UO_Imag; break;
8318 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008319 }
8320 return Opc;
8321}
8322
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008323/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8324/// This warning is only emitted for builtin assignment operations. It is also
8325/// suppressed in the event of macro expansions.
8326static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8327 SourceLocation OpLoc) {
8328 if (!S.ActiveTemplateInstantiations.empty())
8329 return;
8330 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8331 return;
8332 lhs = lhs->IgnoreParenImpCasts();
8333 rhs = rhs->IgnoreParenImpCasts();
8334 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8335 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8336 if (!LeftDeclRef || !RightDeclRef ||
8337 LeftDeclRef->getLocation().isMacroID() ||
8338 RightDeclRef->getLocation().isMacroID())
8339 return;
8340 const ValueDecl *LeftDecl =
8341 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8342 const ValueDecl *RightDecl =
8343 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8344 if (LeftDecl != RightDecl)
8345 return;
8346 if (LeftDecl->getType().isVolatileQualified())
8347 return;
8348 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8349 if (RefTy->getPointeeType().isVolatileQualified())
8350 return;
8351
8352 S.Diag(OpLoc, diag::warn_self_assignment)
8353 << LeftDeclRef->getType()
8354 << lhs->getSourceRange() << rhs->getSourceRange();
8355}
8356
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008357/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8358/// operator @p Opc at location @c TokLoc. This routine only supports
8359/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008360ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008361 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008362 Expr *lhsExpr, Expr *rhsExpr) {
8363 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008364 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008365 // The following two variables are used for compound assignment operators
8366 QualType CompLHSTy; // Type of LHS after promotions for computation
8367 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008368 ExprValueKind VK = VK_RValue;
8369 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008370
Douglas Gregor1beec452011-03-12 01:48:56 +00008371 // Check if a 'foo<int>' involved in a binary op, identifies a single
8372 // function unambiguously (i.e. an lvalue ala 13.4)
8373 // But since an assignment can trigger target based overload, exclude it in
8374 // our blind search. i.e:
8375 // template<class T> void f(); template<class T, class U> void f(U);
8376 // f<int> == 0; // resolve f<int> blindly
8377 // void (*p)(int); p = f<int>; // resolve f<int> using target
8378 if (Opc != BO_Assign) {
John Wiegley01296292011-04-08 18:41:53 +00008379 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get(), OpLoc);
John McCall31996342011-04-07 08:22:57 +00008380 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008381 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008382
John Wiegley01296292011-04-08 18:41:53 +00008383 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get(), OpLoc);
John McCall31996342011-04-07 08:22:57 +00008384 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008385 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008386 }
8387
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008388 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008389 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008390 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008391 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008392 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8393 VK = lhs.get()->getValueKind();
8394 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008395 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008396 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008397 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008398 break;
John McCalle3027922010-08-25 11:45:40 +00008399 case BO_PtrMemD:
8400 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008401 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008402 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008403 break;
John McCalle3027922010-08-25 11:45:40 +00008404 case BO_Mul:
8405 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008406 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008407 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008408 break;
John McCalle3027922010-08-25 11:45:40 +00008409 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008410 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8411 break;
John McCalle3027922010-08-25 11:45:40 +00008412 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008413 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8414 break;
John McCalle3027922010-08-25 11:45:40 +00008415 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008416 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8417 break;
John McCalle3027922010-08-25 11:45:40 +00008418 case BO_Shl:
8419 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008420 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008421 break;
John McCalle3027922010-08-25 11:45:40 +00008422 case BO_LE:
8423 case BO_LT:
8424 case BO_GE:
8425 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008426 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008427 break;
John McCalle3027922010-08-25 11:45:40 +00008428 case BO_EQ:
8429 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008430 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008431 break;
John McCalle3027922010-08-25 11:45:40 +00008432 case BO_And:
8433 case BO_Xor:
8434 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008435 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8436 break;
John McCalle3027922010-08-25 11:45:40 +00008437 case BO_LAnd:
8438 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008439 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008440 break;
John McCalle3027922010-08-25 11:45:40 +00008441 case BO_MulAssign:
8442 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008443 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008444 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008445 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008446 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8447 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008448 break;
John McCalle3027922010-08-25 11:45:40 +00008449 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008450 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8451 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008452 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8453 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008454 break;
John McCalle3027922010-08-25 11:45:40 +00008455 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008456 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008457 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8458 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008459 break;
John McCalle3027922010-08-25 11:45:40 +00008460 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008461 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008462 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8463 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008464 break;
John McCalle3027922010-08-25 11:45:40 +00008465 case BO_ShlAssign:
8466 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008467 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008468 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008469 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8470 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008471 break;
John McCalle3027922010-08-25 11:45:40 +00008472 case BO_AndAssign:
8473 case BO_XorAssign:
8474 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008475 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8476 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008477 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8478 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008479 break;
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008481 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008482 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8483 VK = rhs.get()->getValueKind();
8484 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008485 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008486 break;
8487 }
John Wiegley01296292011-04-08 18:41:53 +00008488 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008489 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008490 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008491 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8492 ResultTy, VK, OK, OpLoc));
8493 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008494 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008495 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008496 }
John Wiegley01296292011-04-08 18:41:53 +00008497 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8498 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008499 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008500}
8501
Sebastian Redl44615072009-10-27 12:10:02 +00008502/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8503/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008504static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8505 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008506 const PartialDiagnostic &FirstNote,
8507 SourceRange FirstParenRange,
8508 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008509 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008510 Self.Diag(Loc, PD);
8511
8512 if (!FirstNote.getDiagID())
8513 return;
8514
8515 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8516 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8517 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008518 return;
8519 }
8520
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008521 Self.Diag(Loc, FirstNote)
8522 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008523 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008524
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008525 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008526 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008527
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008528 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8529 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8530 // We can't display the parentheses, so just dig the
8531 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008532 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008533 return;
8534 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008535
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008536 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008537 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8538 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008539}
8540
Sebastian Redl44615072009-10-27 12:10:02 +00008541/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8542/// operators are mixed in a way that suggests that the programmer forgot that
8543/// comparison operators have higher precedence. The most typical example of
8544/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008545static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008546 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008547 typedef BinaryOperator BinOp;
8548 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8549 rhsopc = static_cast<BinOp::Opcode>(-1);
8550 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008551 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008552 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008553 rhsopc = BO->getOpcode();
8554
8555 // Subs are not binary operators.
8556 if (lhsopc == -1 && rhsopc == -1)
8557 return;
8558
8559 // Bitwise operations are sometimes used as eager logical ops.
8560 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008561 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8562 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008563 return;
8564
Sebastian Redl44615072009-10-27 12:10:02 +00008565 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008566 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008567 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008568 << SourceRange(lhs->getLocStart(), OpLoc)
8569 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008570 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008571 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008572 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8573 Self.PDiag(diag::note_precedence_bitwise_silence)
8574 << BinOp::getOpcodeStr(lhsopc),
8575 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008576 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008577 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008578 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008579 << SourceRange(OpLoc, rhs->getLocEnd())
8580 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008581 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008582 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008583 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8584 Self.PDiag(diag::note_precedence_bitwise_silence)
8585 << BinOp::getOpcodeStr(rhsopc),
8586 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008587}
8588
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008589/// \brief It accepts a '&&' expr that is inside a '||' one.
8590/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8591/// in parentheses.
8592static void
8593EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8594 Expr *E) {
8595 assert(isa<BinaryOperator>(E) &&
8596 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8597 SuggestParentheses(Self, OpLoc,
8598 Self.PDiag(diag::warn_logical_and_in_logical_or)
8599 << E->getSourceRange(),
8600 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8601 E->getSourceRange(),
8602 Self.PDiag(0), SourceRange());
8603}
8604
8605/// \brief Returns true if the given expression can be evaluated as a constant
8606/// 'true'.
8607static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8608 bool Res;
8609 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8610}
8611
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008612/// \brief Returns true if the given expression can be evaluated as a constant
8613/// 'false'.
8614static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8615 bool Res;
8616 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8617}
8618
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008619/// \brief Look for '&&' in the left hand of a '||' expr.
8620static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008621 Expr *OrLHS, Expr *OrRHS) {
8622 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008623 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008624 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8625 if (EvaluatesAsFalse(S, OrRHS))
8626 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008627 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8628 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8629 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8630 } else if (Bop->getOpcode() == BO_LOr) {
8631 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8632 // If it's "a || b && 1 || c" we didn't warn earlier for
8633 // "a || b && 1", but warn now.
8634 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8635 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8636 }
8637 }
8638 }
8639}
8640
8641/// \brief Look for '&&' in the right hand of a '||' expr.
8642static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008643 Expr *OrLHS, Expr *OrRHS) {
8644 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008645 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008646 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8647 if (EvaluatesAsFalse(S, OrLHS))
8648 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008649 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8650 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8651 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008652 }
8653 }
8654}
8655
Sebastian Redl43028242009-10-26 15:24:15 +00008656/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008657/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008658static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008659 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008660 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008661 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008662 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8663
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008664 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8665 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008666 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008667 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8668 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008669 }
Sebastian Redl43028242009-10-26 15:24:15 +00008670}
8671
Steve Naroff218bc2b2007-05-04 21:54:46 +00008672// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008673ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008674 tok::TokenKind Kind,
8675 Expr *lhs, Expr *rhs) {
8676 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008677 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8678 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008679
Sebastian Redl43028242009-10-26 15:24:15 +00008680 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8681 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8682
Douglas Gregor5287f092009-11-05 00:51:44 +00008683 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8684}
8685
John McCalldadc5752010-08-24 06:29:42 +00008686ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008687 BinaryOperatorKind Opc,
8688 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008689 if (getLangOptions().CPlusPlus) {
8690 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008691
John McCall622114c2010-12-06 05:26:58 +00008692 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8693 UseBuiltinOperator = false;
8694 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8695 UseBuiltinOperator = true;
8696 } else {
8697 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8698 !rhs->getType()->isOverloadableType();
8699 }
8700
8701 if (!UseBuiltinOperator) {
8702 // Find all of the overloaded operators visible from this
8703 // point. We perform both an operator-name lookup from the local
8704 // scope and an argument-dependent lookup based on the types of
8705 // the arguments.
8706 UnresolvedSet<16> Functions;
8707 OverloadedOperatorKind OverOp
8708 = BinaryOperator::getOverloadedOperator(Opc);
8709 if (S && OverOp != OO_None)
8710 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8711 Functions);
8712
8713 // Build the (potentially-overloaded, potentially-dependent)
8714 // binary operation.
8715 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8716 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008717 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008718
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008719 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008720 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008721}
8722
John McCalldadc5752010-08-24 06:29:42 +00008723ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008724 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008725 Expr *InputExpr) {
8726 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008727 ExprValueKind VK = VK_RValue;
8728 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008729 QualType resultType;
8730 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008731 case UO_PreInc:
8732 case UO_PreDec:
8733 case UO_PostInc:
8734 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008735 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008736 Opc == UO_PreInc ||
8737 Opc == UO_PostInc,
8738 Opc == UO_PreInc ||
8739 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008740 break;
John McCalle3027922010-08-25 11:45:40 +00008741 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008742 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008743 break;
John McCall31996342011-04-07 08:22:57 +00008744 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008745 ExprResult resolved = CheckPlaceholderExpr(Input.get(), OpLoc);
John McCall31996342011-04-07 08:22:57 +00008746 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008747 Input = move(resolved);
8748 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8749 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008750 break;
John McCall31996342011-04-07 08:22:57 +00008751 }
John McCalle3027922010-08-25 11:45:40 +00008752 case UO_Plus:
8753 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008754 Input = UsualUnaryConversions(Input.take());
8755 if (Input.isInvalid()) return ExprError();
8756 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008757 if (resultType->isDependentType())
8758 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008759 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8760 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008761 break;
8762 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8763 resultType->isEnumeralType())
8764 break;
8765 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008766 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008767 resultType->isPointerType())
8768 break;
John McCall36226622010-10-12 02:09:17 +00008769 else if (resultType->isPlaceholderType()) {
John Wiegley01296292011-04-08 18:41:53 +00008770 Input = CheckPlaceholderExpr(Input.take(), OpLoc);
8771 if (Input.isInvalid()) return ExprError();
8772 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008773 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008774
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008775 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008776 << resultType << Input.get()->getSourceRange());
8777
John McCalle3027922010-08-25 11:45:40 +00008778 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008779 Input = UsualUnaryConversions(Input.take());
8780 if (Input.isInvalid()) return ExprError();
8781 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008782 if (resultType->isDependentType())
8783 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008784 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8785 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8786 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008787 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008788 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008789 else if (resultType->hasIntegerRepresentation())
8790 break;
8791 else if (resultType->isPlaceholderType()) {
John Wiegley01296292011-04-08 18:41:53 +00008792 Input = CheckPlaceholderExpr(Input.take(), OpLoc);
8793 if (Input.isInvalid()) return ExprError();
8794 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008795 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008796 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008797 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008798 }
Steve Naroff35d85152007-05-07 00:24:15 +00008799 break;
John Wiegley01296292011-04-08 18:41:53 +00008800
John McCalle3027922010-08-25 11:45:40 +00008801 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008802 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008803 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8804 if (Input.isInvalid()) return ExprError();
8805 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008806 if (resultType->isDependentType())
8807 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008808 if (resultType->isScalarType()) {
8809 // C99 6.5.3.3p1: ok, fallthrough;
8810 if (Context.getLangOptions().CPlusPlus) {
8811 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8812 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008813 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8814 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008815 }
John McCall36226622010-10-12 02:09:17 +00008816 } else if (resultType->isPlaceholderType()) {
John Wiegley01296292011-04-08 18:41:53 +00008817 Input = CheckPlaceholderExpr(Input.take(), OpLoc);
8818 if (Input.isInvalid()) return ExprError();
8819 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008820 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008821 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008822 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008823 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008824
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008825 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008826 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008827 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008828 break;
John McCalle3027922010-08-25 11:45:40 +00008829 case UO_Real:
8830 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008831 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008832 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008833 if (Input.isInvalid()) return ExprError();
8834 if (Input.get()->getValueKind() != VK_RValue &&
8835 Input.get()->getObjectKind() == OK_Ordinary)
8836 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008837 break;
John McCalle3027922010-08-25 11:45:40 +00008838 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008839 resultType = Input.get()->getType();
8840 VK = Input.get()->getValueKind();
8841 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008842 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008843 }
John Wiegley01296292011-04-08 18:41:53 +00008844 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008845 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008846
John Wiegley01296292011-04-08 18:41:53 +00008847 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008848 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008849}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008850
John McCalldadc5752010-08-24 06:29:42 +00008851ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008852 UnaryOperatorKind Opc,
8853 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008854 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008855 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008856 // Find all of the overloaded operators visible from this
8857 // point. We perform both an operator-name lookup from the local
8858 // scope and an argument-dependent lookup based on the types of
8859 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008860 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008861 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008862 if (S && OverOp != OO_None)
8863 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8864 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008865
John McCallb268a282010-08-23 23:25:46 +00008866 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008867 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008868
John McCallb268a282010-08-23 23:25:46 +00008869 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008870}
8871
Douglas Gregor5287f092009-11-05 00:51:44 +00008872// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008873ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008874 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008875 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008876}
8877
Steve Naroff66356bd2007-09-16 14:56:35 +00008878/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008879ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008880 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008881 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008882 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008883 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008884 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008885}
8886
John McCalldadc5752010-08-24 06:29:42 +00008887ExprResult
John McCallb268a282010-08-23 23:25:46 +00008888Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008889 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008890 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8891 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8892
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008893 bool isFileScope
8894 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008895 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008896 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008897
Chris Lattner366727f2007-07-24 16:58:17 +00008898 // FIXME: there are a variety of strange constraints to enforce here, for
8899 // example, it is not possible to goto into a stmt expression apparently.
8900 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008901
Chris Lattner366727f2007-07-24 16:58:17 +00008902 // If there are sub stmts in the compound stmt, take the type of the last one
8903 // as the type of the stmtexpr.
8904 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008905 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008906 if (!Compound->body_empty()) {
8907 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008908 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008909 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008910 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8911 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008912 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008913 }
John Wiegley01296292011-04-08 18:41:53 +00008914 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008915 // Do function/array conversion on the last expression, but not
8916 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008917 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8918 if (LastExpr.isInvalid())
8919 return ExprError();
8920 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008921
John Wiegley01296292011-04-08 18:41:53 +00008922 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8923 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008924 InitializedEntity::InitializeResult(LPLoc,
8925 Ty,
8926 false),
8927 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00008928 LastExpr);
8929 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008930 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008931 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008932 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008933 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008934 else
John Wiegley01296292011-04-08 18:41:53 +00008935 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008936 StmtExprMayBindToTemp = true;
8937 }
8938 }
8939 }
Chris Lattner944d3062008-07-26 19:51:01 +00008940 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008941
Eli Friedmanba961a92009-03-23 00:24:07 +00008942 // FIXME: Check that expression type is complete/non-abstract; statement
8943 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008944 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8945 if (StmtExprMayBindToTemp)
8946 return MaybeBindToTemporary(ResStmtExpr);
8947 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008948}
Steve Naroff78864672007-08-01 22:05:33 +00008949
John McCalldadc5752010-08-24 06:29:42 +00008950ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008951 TypeSourceInfo *TInfo,
8952 OffsetOfComponent *CompPtr,
8953 unsigned NumComponents,
8954 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008955 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008956 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008957 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008958
Chris Lattnerf17bd422007-08-30 17:45:32 +00008959 // We must have at least one component that refers to the type, and the first
8960 // one is known to be a field designator. Verify that the ArgTy represents
8961 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008962 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008963 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8964 << ArgTy << TypeRange);
8965
8966 // Type must be complete per C99 7.17p3 because a declaring a variable
8967 // with an incomplete type would be ill-formed.
8968 if (!Dependent
8969 && RequireCompleteType(BuiltinLoc, ArgTy,
8970 PDiag(diag::err_offsetof_incomplete_type)
8971 << TypeRange))
8972 return ExprError();
8973
Chris Lattner78502cf2007-08-31 21:49:13 +00008974 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8975 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008976 // FIXME: This diagnostic isn't actually visible because the location is in
8977 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008978 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008979 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8980 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008981
8982 bool DidWarnAboutNonPOD = false;
8983 QualType CurrentType = ArgTy;
8984 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8985 llvm::SmallVector<OffsetOfNode, 4> Comps;
8986 llvm::SmallVector<Expr*, 4> Exprs;
8987 for (unsigned i = 0; i != NumComponents; ++i) {
8988 const OffsetOfComponent &OC = CompPtr[i];
8989 if (OC.isBrackets) {
8990 // Offset of an array sub-field. TODO: Should we allow vector elements?
8991 if (!CurrentType->isDependentType()) {
8992 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8993 if(!AT)
8994 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8995 << CurrentType);
8996 CurrentType = AT->getElementType();
8997 } else
8998 CurrentType = Context.DependentTy;
8999
9000 // The expression must be an integral expression.
9001 // FIXME: An integral constant expression?
9002 Expr *Idx = static_cast<Expr*>(OC.U.E);
9003 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9004 !Idx->getType()->isIntegerType())
9005 return ExprError(Diag(Idx->getLocStart(),
9006 diag::err_typecheck_subscript_not_integer)
9007 << Idx->getSourceRange());
9008
9009 // Record this array index.
9010 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9011 Exprs.push_back(Idx);
9012 continue;
9013 }
9014
9015 // Offset of a field.
9016 if (CurrentType->isDependentType()) {
9017 // We have the offset of a field, but we can't look into the dependent
9018 // type. Just record the identifier of the field.
9019 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9020 CurrentType = Context.DependentTy;
9021 continue;
9022 }
9023
9024 // We need to have a complete type to look into.
9025 if (RequireCompleteType(OC.LocStart, CurrentType,
9026 diag::err_offsetof_incomplete_type))
9027 return ExprError();
9028
9029 // Look for the designated field.
9030 const RecordType *RC = CurrentType->getAs<RecordType>();
9031 if (!RC)
9032 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9033 << CurrentType);
9034 RecordDecl *RD = RC->getDecl();
9035
9036 // C++ [lib.support.types]p5:
9037 // The macro offsetof accepts a restricted set of type arguments in this
9038 // International Standard. type shall be a POD structure or a POD union
9039 // (clause 9).
9040 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9041 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009042 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009043 PDiag(diag::warn_offsetof_non_pod_type)
9044 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9045 << CurrentType))
9046 DidWarnAboutNonPOD = true;
9047 }
9048
9049 // Look for the field.
9050 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9051 LookupQualifiedName(R, RD);
9052 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009053 IndirectFieldDecl *IndirectMemberDecl = 0;
9054 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009055 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009056 MemberDecl = IndirectMemberDecl->getAnonField();
9057 }
9058
Douglas Gregor882211c2010-04-28 22:16:22 +00009059 if (!MemberDecl)
9060 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9061 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9062 OC.LocEnd));
9063
Douglas Gregor10982ea2010-04-28 22:36:06 +00009064 // C99 7.17p3:
9065 // (If the specified member is a bit-field, the behavior is undefined.)
9066 //
9067 // We diagnose this as an error.
9068 if (MemberDecl->getBitWidth()) {
9069 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9070 << MemberDecl->getDeclName()
9071 << SourceRange(BuiltinLoc, RParenLoc);
9072 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9073 return ExprError();
9074 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009075
9076 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009077 if (IndirectMemberDecl)
9078 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009079
Douglas Gregord1702062010-04-29 00:18:15 +00009080 // If the member was found in a base class, introduce OffsetOfNodes for
9081 // the base class indirections.
9082 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9083 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009084 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009085 CXXBasePath &Path = Paths.front();
9086 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9087 B != BEnd; ++B)
9088 Comps.push_back(OffsetOfNode(B->Base));
9089 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009090
Francois Pichet783dd6e2010-11-21 06:08:52 +00009091 if (IndirectMemberDecl) {
9092 for (IndirectFieldDecl::chain_iterator FI =
9093 IndirectMemberDecl->chain_begin(),
9094 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9095 assert(isa<FieldDecl>(*FI));
9096 Comps.push_back(OffsetOfNode(OC.LocStart,
9097 cast<FieldDecl>(*FI), OC.LocEnd));
9098 }
9099 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009100 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009101
Douglas Gregor882211c2010-04-28 22:16:22 +00009102 CurrentType = MemberDecl->getType().getNonReferenceType();
9103 }
9104
9105 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9106 TInfo, Comps.data(), Comps.size(),
9107 Exprs.data(), Exprs.size(), RParenLoc));
9108}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009109
John McCalldadc5752010-08-24 06:29:42 +00009110ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009111 SourceLocation BuiltinLoc,
9112 SourceLocation TypeLoc,
9113 ParsedType argty,
9114 OffsetOfComponent *CompPtr,
9115 unsigned NumComponents,
9116 SourceLocation RPLoc) {
9117
Douglas Gregor882211c2010-04-28 22:16:22 +00009118 TypeSourceInfo *ArgTInfo;
9119 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9120 if (ArgTy.isNull())
9121 return ExprError();
9122
Eli Friedman06dcfd92010-08-05 10:15:45 +00009123 if (!ArgTInfo)
9124 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9125
9126 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9127 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009128}
9129
9130
John McCalldadc5752010-08-24 06:29:42 +00009131ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009132 Expr *CondExpr,
9133 Expr *LHSExpr, Expr *RHSExpr,
9134 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009135 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9136
John McCall7decc9e2010-11-18 06:31:45 +00009137 ExprValueKind VK = VK_RValue;
9138 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009139 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009140 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009141 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009142 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009143 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009144 } else {
9145 // The conditional expression is required to be a constant expression.
9146 llvm::APSInt condEval(32);
9147 SourceLocation ExpLoc;
9148 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009149 return ExprError(Diag(ExpLoc,
9150 diag::err_typecheck_choose_expr_requires_constant)
9151 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009152
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009153 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009154 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9155
9156 resType = ActiveExpr->getType();
9157 ValueDependent = ActiveExpr->isValueDependent();
9158 VK = ActiveExpr->getValueKind();
9159 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009160 }
9161
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009162 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009163 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009164 resType->isDependentType(),
9165 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009166}
9167
Steve Naroffc540d662008-09-03 18:15:37 +00009168//===----------------------------------------------------------------------===//
9169// Clang Extensions.
9170//===----------------------------------------------------------------------===//
9171
9172/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009173void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009174 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9175 PushBlockScope(BlockScope, Block);
9176 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009177 if (BlockScope)
9178 PushDeclContext(BlockScope, Block);
9179 else
9180 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009181}
9182
Mike Stump82f071f2009-02-04 22:31:32 +00009183void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009184 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009185 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009186 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009187
John McCall8cb7bdf2010-06-04 23:28:52 +00009188 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009189 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009190
John McCall3882ace2011-01-05 12:14:39 +00009191 // GetTypeForDeclarator always produces a function type for a block
9192 // literal signature. Furthermore, it is always a FunctionProtoType
9193 // unless the function was written with a typedef.
9194 assert(T->isFunctionType() &&
9195 "GetTypeForDeclarator made a non-function block signature");
9196
9197 // Look for an explicit signature in that function type.
9198 FunctionProtoTypeLoc ExplicitSignature;
9199
9200 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9201 if (isa<FunctionProtoTypeLoc>(tmp)) {
9202 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9203
9204 // Check whether that explicit signature was synthesized by
9205 // GetTypeForDeclarator. If so, don't save that as part of the
9206 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009207 if (ExplicitSignature.getLocalRangeBegin() ==
9208 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009209 // This would be much cheaper if we stored TypeLocs instead of
9210 // TypeSourceInfos.
9211 TypeLoc Result = ExplicitSignature.getResultLoc();
9212 unsigned Size = Result.getFullDataSize();
9213 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9214 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9215
9216 ExplicitSignature = FunctionProtoTypeLoc();
9217 }
John McCalla3ccba02010-06-04 11:21:44 +00009218 }
Mike Stump11289f42009-09-09 15:08:12 +00009219
John McCall3882ace2011-01-05 12:14:39 +00009220 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9221 CurBlock->FunctionType = T;
9222
9223 const FunctionType *Fn = T->getAs<FunctionType>();
9224 QualType RetTy = Fn->getResultType();
9225 bool isVariadic =
9226 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9227
John McCall8e346702010-06-04 19:02:56 +00009228 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009229
John McCalla3ccba02010-06-04 11:21:44 +00009230 // Don't allow returning a objc interface by value.
9231 if (RetTy->isObjCObjectType()) {
9232 Diag(ParamInfo.getSourceRange().getBegin(),
9233 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9234 return;
9235 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009236
John McCalla3ccba02010-06-04 11:21:44 +00009237 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009238 // return type. TODO: what should we do with declarators like:
9239 // ^ * { ... }
9240 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009241 if (RetTy != Context.DependentTy)
9242 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009243
John McCalla3ccba02010-06-04 11:21:44 +00009244 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009245 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009246 if (ExplicitSignature) {
9247 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9248 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009249 if (Param->getIdentifier() == 0 &&
9250 !Param->isImplicit() &&
9251 !Param->isInvalidDecl() &&
9252 !getLangOptions().CPlusPlus)
9253 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009254 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009255 }
John McCalla3ccba02010-06-04 11:21:44 +00009256
9257 // Fake up parameter variables if we have a typedef, like
9258 // ^ fntype { ... }
9259 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9260 for (FunctionProtoType::arg_type_iterator
9261 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9262 ParmVarDecl *Param =
9263 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9264 ParamInfo.getSourceRange().getBegin(),
9265 *I);
John McCall8e346702010-06-04 19:02:56 +00009266 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009267 }
Steve Naroffc540d662008-09-03 18:15:37 +00009268 }
John McCalla3ccba02010-06-04 11:21:44 +00009269
John McCall8e346702010-06-04 19:02:56 +00009270 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009271 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009272 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009273 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9274 CurBlock->TheDecl->param_end(),
9275 /*CheckParameterNames=*/false);
9276 }
9277
John McCalla3ccba02010-06-04 11:21:44 +00009278 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009279 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009280
John McCall8e346702010-06-04 19:02:56 +00009281 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009282 Diag(ParamInfo.getAttributes()->getLoc(),
9283 diag::warn_attribute_sentinel_not_variadic) << 1;
9284 // FIXME: remove the attribute.
9285 }
9286
9287 // Put the parameter variables in scope. We can bail out immediately
9288 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009289 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009290 return;
9291
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009292 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009293 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9294 (*AI)->setOwningFunction(CurBlock->TheDecl);
9295
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009296 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009297 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009298 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009299
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009300 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009301 }
John McCallf7b2fb52010-01-22 00:28:27 +00009302 }
Steve Naroffc540d662008-09-03 18:15:37 +00009303}
9304
9305/// ActOnBlockError - If there is an error parsing a block, this callback
9306/// is invoked to pop the information about the block from the action impl.
9307void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009308 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009309 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009310 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009311}
9312
9313/// ActOnBlockStmtExpr - This is called when the body of a block statement
9314/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009315ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009316 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009317 // If blocks are disabled, emit an error.
9318 if (!LangOpts.Blocks)
9319 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009320
Douglas Gregor9a28e842010-03-01 23:15:13 +00009321 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009322
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009323 PopDeclContext();
9324
Steve Naroffc540d662008-09-03 18:15:37 +00009325 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009326 if (!BSI->ReturnType.isNull())
9327 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009328
Mike Stump3bf1ab42009-07-28 22:04:01 +00009329 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009330 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009331
John McCallc63de662011-02-02 13:00:07 +00009332 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009333 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9334 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009335
John McCall8e346702010-06-04 19:02:56 +00009336 // If the user wrote a function type in some form, try to use that.
9337 if (!BSI->FunctionType.isNull()) {
9338 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9339
9340 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9341 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9342
9343 // Turn protoless block types into nullary block types.
9344 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009345 FunctionProtoType::ExtProtoInfo EPI;
9346 EPI.ExtInfo = Ext;
9347 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009348
9349 // Otherwise, if we don't need to change anything about the function type,
9350 // preserve its sugar structure.
9351 } else if (FTy->getResultType() == RetTy &&
9352 (!NoReturn || FTy->getNoReturnAttr())) {
9353 BlockTy = BSI->FunctionType;
9354
9355 // Otherwise, make the minimal modifications to the function type.
9356 } else {
9357 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009358 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9359 EPI.TypeQuals = 0; // FIXME: silently?
9360 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009361 BlockTy = Context.getFunctionType(RetTy,
9362 FPT->arg_type_begin(),
9363 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009364 EPI);
John McCall8e346702010-06-04 19:02:56 +00009365 }
9366
9367 // If we don't have a function type, just build one from nothing.
9368 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009369 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009370 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009371 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009372 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009373
John McCall8e346702010-06-04 19:02:56 +00009374 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9375 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009376 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009377
Chris Lattner45542ea2009-04-19 05:28:12 +00009378 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009379 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009380 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009381
Chris Lattner60f84492011-02-17 23:58:47 +00009382 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009383
John McCallc63de662011-02-02 13:00:07 +00009384 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009385
Ted Kremenek1767a272011-02-23 01:51:48 +00009386 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9387 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009388 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009389}
9390
John McCalldadc5752010-08-24 06:29:42 +00009391ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009392 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009393 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009394 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009395 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009396 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009397}
9398
John McCalldadc5752010-08-24 06:29:42 +00009399ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009400 Expr *E, TypeSourceInfo *TInfo,
9401 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009402 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009403
Eli Friedman121ba0c2008-08-09 23:32:40 +00009404 // Get the va_list type
9405 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009406 if (VaListType->isArrayType()) {
9407 // Deal with implicit array decay; for example, on x86-64,
9408 // va_list is an array, but it's supposed to decay to
9409 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009410 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009411 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009412 ExprResult Result = UsualUnaryConversions(E);
9413 if (Result.isInvalid())
9414 return ExprError();
9415 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009416 } else {
9417 // Otherwise, the va_list argument must be an l-value because
9418 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009419 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009420 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009421 return ExprError();
9422 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009423
Douglas Gregorad3150c2009-05-19 23:10:31 +00009424 if (!E->isTypeDependent() &&
9425 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009426 return ExprError(Diag(E->getLocStart(),
9427 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009428 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009429 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009430
Eli Friedmanba961a92009-03-23 00:24:07 +00009431 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009432 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009433
Abramo Bagnara27db2392010-08-10 10:06:15 +00009434 QualType T = TInfo->getType().getNonLValueExprType(Context);
9435 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009436}
9437
John McCalldadc5752010-08-24 06:29:42 +00009438ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009439 // The type of __null will be int or long, depending on the size of
9440 // pointers on the target.
9441 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009442 unsigned pw = Context.Target.getPointerWidth(0);
9443 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009444 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009445 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009446 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009447 else if (pw == Context.Target.getLongLongWidth())
9448 Ty = Context.LongLongTy;
9449 else {
9450 assert(!"I don't know size of pointer!");
9451 Ty = Context.IntTy;
9452 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009453
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009454 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009455}
9456
Alexis Huntc46382e2010-04-28 23:02:27 +00009457static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009458 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009459 if (!SemaRef.getLangOptions().ObjC1)
9460 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009461
Anders Carlssonace5d072009-11-10 04:46:30 +00009462 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9463 if (!PT)
9464 return;
9465
9466 // Check if the destination is of type 'id'.
9467 if (!PT->isObjCIdType()) {
9468 // Check if the destination is the 'NSString' interface.
9469 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9470 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9471 return;
9472 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009473
Anders Carlssonace5d072009-11-10 04:46:30 +00009474 // Strip off any parens and casts.
9475 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9476 if (!SL || SL->isWide())
9477 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009478
Douglas Gregora771f462010-03-31 17:46:05 +00009479 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009480}
9481
Chris Lattner9bad62c2008-01-04 18:04:52 +00009482bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9483 SourceLocation Loc,
9484 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009485 Expr *SrcExpr, AssignmentAction Action,
9486 bool *Complained) {
9487 if (Complained)
9488 *Complained = false;
9489
Chris Lattner9bad62c2008-01-04 18:04:52 +00009490 // Decode the result (notice that AST's are still created for extensions).
9491 bool isInvalid = false;
9492 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009493 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009494
Chris Lattner9bad62c2008-01-04 18:04:52 +00009495 switch (ConvTy) {
9496 default: assert(0 && "Unknown conversion type");
9497 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009498 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009499 DiagKind = diag::ext_typecheck_convert_pointer_int;
9500 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009501 case IntToPointer:
9502 DiagKind = diag::ext_typecheck_convert_int_pointer;
9503 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009504 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009505 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009506 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9507 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009508 case IncompatiblePointerSign:
9509 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9510 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009511 case FunctionVoidPointer:
9512 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9513 break;
John McCall4fff8f62011-02-01 00:10:29 +00009514 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009515 // Perform array-to-pointer decay if necessary.
9516 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9517
John McCall4fff8f62011-02-01 00:10:29 +00009518 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9519 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9520 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9521 DiagKind = diag::err_typecheck_incompatible_address_space;
9522 break;
9523 }
9524
9525 llvm_unreachable("unknown error case for discarding qualifiers!");
9526 // fallthrough
9527 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009528 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009529 // If the qualifiers lost were because we were applying the
9530 // (deprecated) C++ conversion from a string literal to a char*
9531 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9532 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009533 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009534 // bit of refactoring (so that the second argument is an
9535 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009536 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009537 // C++ semantics.
9538 if (getLangOptions().CPlusPlus &&
9539 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9540 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009541 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9542 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009543 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009544 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009545 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009546 case IntToBlockPointer:
9547 DiagKind = diag::err_int_to_block_pointer;
9548 break;
9549 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009550 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009551 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009552 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009553 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009554 // it can give a more specific diagnostic.
9555 DiagKind = diag::warn_incompatible_qualified_id;
9556 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009557 case IncompatibleVectors:
9558 DiagKind = diag::warn_incompatible_vectors;
9559 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009560 case Incompatible:
9561 DiagKind = diag::err_typecheck_convert_incompatible;
9562 isInvalid = true;
9563 break;
9564 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009565
Douglas Gregorc68e1402010-04-09 00:35:39 +00009566 QualType FirstType, SecondType;
9567 switch (Action) {
9568 case AA_Assigning:
9569 case AA_Initializing:
9570 // The destination type comes first.
9571 FirstType = DstType;
9572 SecondType = SrcType;
9573 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009574
Douglas Gregorc68e1402010-04-09 00:35:39 +00009575 case AA_Returning:
9576 case AA_Passing:
9577 case AA_Converting:
9578 case AA_Sending:
9579 case AA_Casting:
9580 // The source type comes first.
9581 FirstType = SrcType;
9582 SecondType = DstType;
9583 break;
9584 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009585
Douglas Gregorc68e1402010-04-09 00:35:39 +00009586 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009587 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009588 if (Complained)
9589 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009590 return isInvalid;
9591}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009592
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009593bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009594 llvm::APSInt ICEResult;
9595 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9596 if (Result)
9597 *Result = ICEResult;
9598 return false;
9599 }
9600
Anders Carlssone54e8a12008-11-30 19:50:32 +00009601 Expr::EvalResult EvalResult;
9602
Mike Stump4e1f26a2009-02-19 03:04:26 +00009603 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009604 EvalResult.HasSideEffects) {
9605 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9606
9607 if (EvalResult.Diag) {
9608 // We only show the note if it's not the usual "invalid subexpression"
9609 // or if it's actually in a subexpression.
9610 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9611 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9612 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9613 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009614
Anders Carlssone54e8a12008-11-30 19:50:32 +00009615 return true;
9616 }
9617
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009618 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9619 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009620
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009621 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009622 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9623 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009624 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009625
Anders Carlssone54e8a12008-11-30 19:50:32 +00009626 if (Result)
9627 *Result = EvalResult.Val.getInt();
9628 return false;
9629}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009630
Douglas Gregorff790f12009-11-26 00:44:06 +00009631void
Mike Stump11289f42009-09-09 15:08:12 +00009632Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009633 ExprEvalContexts.push_back(
9634 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009635}
9636
Mike Stump11289f42009-09-09 15:08:12 +00009637void
Douglas Gregorff790f12009-11-26 00:44:06 +00009638Sema::PopExpressionEvaluationContext() {
9639 // Pop the current expression evaluation context off the stack.
9640 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9641 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009642
Douglas Gregorfab31f42009-12-12 07:57:52 +00009643 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9644 if (Rec.PotentiallyReferenced) {
9645 // Mark any remaining declarations in the current position of the stack
9646 // as "referenced". If they were not meant to be referenced, semantic
9647 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009648 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009649 I = Rec.PotentiallyReferenced->begin(),
9650 IEnd = Rec.PotentiallyReferenced->end();
9651 I != IEnd; ++I)
9652 MarkDeclarationReferenced(I->first, I->second);
9653 }
9654
9655 if (Rec.PotentiallyDiagnosed) {
9656 // Emit any pending diagnostics.
9657 for (PotentiallyEmittedDiagnostics::iterator
9658 I = Rec.PotentiallyDiagnosed->begin(),
9659 IEnd = Rec.PotentiallyDiagnosed->end();
9660 I != IEnd; ++I)
9661 Diag(I->first, I->second);
9662 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009663 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009664
9665 // When are coming out of an unevaluated context, clear out any
9666 // temporaries that we may have created as part of the evaluation of
9667 // the expression in that context: they aren't relevant because they
9668 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009669 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009670 ExprTemporaries.size() > Rec.NumTemporaries)
9671 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9672 ExprTemporaries.end());
9673
9674 // Destroy the popped expression evaluation record.
9675 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009676}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009677
9678/// \brief Note that the given declaration was referenced in the source code.
9679///
9680/// This routine should be invoke whenever a given declaration is referenced
9681/// in the source code, and where that reference occurred. If this declaration
9682/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9683/// C99 6.9p3), then the declaration will be marked as used.
9684///
9685/// \param Loc the location where the declaration was referenced.
9686///
9687/// \param D the declaration that has been referenced by the source code.
9688void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9689 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009690
Douglas Gregorebada0772010-06-17 23:14:26 +00009691 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009692 return;
Mike Stump11289f42009-09-09 15:08:12 +00009693
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009694 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9695 // template or not. The reason for this is that unevaluated expressions
9696 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9697 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009698 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009699 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009700 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009701 return;
9702 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009703
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009704 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9705 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009706
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009707 // Do not mark anything as "used" within a dependent context; wait for
9708 // an instantiation.
9709 if (CurContext->isDependentContext())
9710 return;
Mike Stump11289f42009-09-09 15:08:12 +00009711
Douglas Gregorff790f12009-11-26 00:44:06 +00009712 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009713 case Unevaluated:
9714 // We are in an expression that is not potentially evaluated; do nothing.
9715 return;
Mike Stump11289f42009-09-09 15:08:12 +00009716
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009717 case PotentiallyEvaluated:
9718 // We are in a potentially-evaluated expression, so this declaration is
9719 // "used"; handle this below.
9720 break;
Mike Stump11289f42009-09-09 15:08:12 +00009721
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009722 case PotentiallyPotentiallyEvaluated:
9723 // We are in an expression that may be potentially evaluated; queue this
9724 // declaration reference until we know whether the expression is
9725 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009726 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009727 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009728
9729 case PotentiallyEvaluatedIfUsed:
9730 // Referenced declarations will only be used if the construct in the
9731 // containing expression is used.
9732 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009733 }
Mike Stump11289f42009-09-09 15:08:12 +00009734
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009735 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009736 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009737 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009738 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009739 if (Constructor->getParent()->hasTrivialConstructor())
9740 return;
9741 if (!Constructor->isUsed(false))
9742 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009743 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009744 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009745 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009746 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9747 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009748
Douglas Gregor88d292c2010-05-13 16:44:06 +00009749 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009750 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009751 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009752 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009753 if (Destructor->isVirtual())
9754 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009755 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9756 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9757 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009758 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009759 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009760 } else if (MethodDecl->isVirtual())
9761 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009762 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009763 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009764 // Recursive functions should be marked when used from another function.
9765 if (CurContext == Function) return;
9766
Mike Stump11289f42009-09-09 15:08:12 +00009767 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009768 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009769 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009770 bool AlreadyInstantiated = false;
9771 if (FunctionTemplateSpecializationInfo *SpecInfo
9772 = Function->getTemplateSpecializationInfo()) {
9773 if (SpecInfo->getPointOfInstantiation().isInvalid())
9774 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009775 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009776 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009777 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009778 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009779 = Function->getMemberSpecializationInfo()) {
9780 if (MSInfo->getPointOfInstantiation().isInvalid())
9781 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009782 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009783 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009784 AlreadyInstantiated = true;
9785 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009786
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009787 if (!AlreadyInstantiated) {
9788 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9789 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9790 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9791 Loc));
9792 else
Chandler Carruth54080172010-08-25 08:44:16 +00009793 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009794 }
John McCall83779672011-02-19 02:53:41 +00009795 } else {
9796 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009797 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9798 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009799 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009800 MarkDeclarationReferenced(Loc, *i);
9801 }
John McCall83779672011-02-19 02:53:41 +00009802 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009803
John McCall83779672011-02-19 02:53:41 +00009804 // Keep track of used but undefined functions.
9805 if (!Function->isPure() && !Function->hasBody() &&
9806 Function->getLinkage() != ExternalLinkage) {
9807 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9808 if (old.isInvalid()) old = Loc;
9809 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009810
John McCall83779672011-02-19 02:53:41 +00009811 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009812 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009813 }
Mike Stump11289f42009-09-09 15:08:12 +00009814
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009815 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009816 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009817 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009818 Var->getInstantiatedFromStaticDataMember()) {
9819 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9820 assert(MSInfo && "Missing member specialization information?");
9821 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9822 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9823 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009824 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009825 }
9826 }
Mike Stump11289f42009-09-09 15:08:12 +00009827
John McCall15dd4042011-02-21 19:25:48 +00009828 // Keep track of used but undefined variables. We make a hole in
9829 // the warning for static const data members with in-line
9830 // initializers.
John McCall83779672011-02-19 02:53:41 +00009831 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009832 && Var->getLinkage() != ExternalLinkage
9833 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009834 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9835 if (old.isInvalid()) old = Loc;
9836 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009837
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009838 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009839 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009840 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009841}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009842
Douglas Gregor5597ab42010-05-07 23:12:07 +00009843namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009844 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009845 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009846 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009847 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9848 Sema &S;
9849 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009850
Douglas Gregor5597ab42010-05-07 23:12:07 +00009851 public:
9852 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009853
Douglas Gregor5597ab42010-05-07 23:12:07 +00009854 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009855
9856 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9857 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009858 };
9859}
9860
Chandler Carruthaf80f662010-06-09 08:17:30 +00009861bool MarkReferencedDecls::TraverseTemplateArgument(
9862 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009863 if (Arg.getKind() == TemplateArgument::Declaration) {
9864 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9865 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009866
9867 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009868}
9869
Chandler Carruthaf80f662010-06-09 08:17:30 +00009870bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009871 if (ClassTemplateSpecializationDecl *Spec
9872 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9873 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009874 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009875 }
9876
Chandler Carruthc65667c2010-06-10 10:31:57 +00009877 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009878}
9879
9880void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9881 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009882 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009883}
9884
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009885namespace {
9886 /// \brief Helper class that marks all of the declarations referenced by
9887 /// potentially-evaluated subexpressions as "referenced".
9888 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9889 Sema &S;
9890
9891 public:
9892 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9893
9894 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9895
9896 void VisitDeclRefExpr(DeclRefExpr *E) {
9897 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9898 }
9899
9900 void VisitMemberExpr(MemberExpr *E) {
9901 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009902 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009903 }
9904
9905 void VisitCXXNewExpr(CXXNewExpr *E) {
9906 if (E->getConstructor())
9907 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9908 if (E->getOperatorNew())
9909 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9910 if (E->getOperatorDelete())
9911 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009912 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009913 }
9914
9915 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9916 if (E->getOperatorDelete())
9917 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009918 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9919 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9920 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9921 S.MarkDeclarationReferenced(E->getLocStart(),
9922 S.LookupDestructor(Record));
9923 }
9924
Douglas Gregor32b3de52010-09-11 23:32:50 +00009925 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009926 }
9927
9928 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9929 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009930 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009931 }
9932
9933 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9934 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9935 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009936
9937 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9938 Visit(E->getExpr());
9939 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009940 };
9941}
9942
9943/// \brief Mark any declarations that appear within this expression or any
9944/// potentially-evaluated subexpressions as "referenced".
9945void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9946 EvaluatedExprMarker(*this).Visit(E);
9947}
9948
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009949/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9950/// of the program being compiled.
9951///
9952/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009953/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009954/// possibility that the code will actually be executable. Code in sizeof()
9955/// expressions, code used only during overload resolution, etc., are not
9956/// potentially evaluated. This routine will suppress such diagnostics or,
9957/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009958/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009959/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009960///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009961/// This routine should be used for all diagnostics that describe the run-time
9962/// behavior of a program, such as passing a non-POD value through an ellipsis.
9963/// Failure to do so will likely result in spurious diagnostics or failures
9964/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009965bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009966 const PartialDiagnostic &PD) {
9967 switch (ExprEvalContexts.back().Context ) {
9968 case Unevaluated:
9969 // The argument will never be evaluated, so don't complain.
9970 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009971
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009972 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009973 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009974 if (stmt && getCurFunctionOrMethodDecl()) {
9975 FunctionScopes.back()->PossiblyUnreachableDiags.
9976 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9977 }
9978 else
9979 Diag(Loc, PD);
9980
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009981 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009982
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009983 case PotentiallyPotentiallyEvaluated:
9984 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9985 break;
9986 }
9987
9988 return false;
9989}
9990
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009991bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9992 CallExpr *CE, FunctionDecl *FD) {
9993 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9994 return false;
9995
9996 PartialDiagnostic Note =
9997 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9998 << FD->getDeclName() : PDiag();
9999 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010000
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010001 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010002 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010003 PDiag(diag::err_call_function_incomplete_return)
10004 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010005 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010006 << CE->getSourceRange(),
10007 std::make_pair(NoteLoc, Note)))
10008 return true;
10009
10010 return false;
10011}
10012
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010013// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010014// will prevent this condition from triggering, which is what we want.
10015void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10016 SourceLocation Loc;
10017
John McCall0506e4a2009-11-11 02:41:58 +000010018 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010019 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010020
John McCalld5707ab2009-10-12 21:59:07 +000010021 if (isa<BinaryOperator>(E)) {
10022 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010023 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010024 return;
10025
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010026 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10027
John McCallb0e419e2009-11-12 00:06:05 +000010028 // Greylist some idioms by putting them into a warning subcategory.
10029 if (ObjCMessageExpr *ME
10030 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10031 Selector Sel = ME->getSelector();
10032
John McCallb0e419e2009-11-12 00:06:05 +000010033 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010034 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010035 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10036
10037 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010038 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010039 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10040 }
John McCall0506e4a2009-11-11 02:41:58 +000010041
John McCalld5707ab2009-10-12 21:59:07 +000010042 Loc = Op->getOperatorLoc();
10043 } else if (isa<CXXOperatorCallExpr>(E)) {
10044 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010045 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010046 return;
10047
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010048 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010049 Loc = Op->getOperatorLoc();
10050 } else {
10051 // Not an assignment.
10052 return;
10053 }
10054
John McCalld5707ab2009-10-12 21:59:07 +000010055 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +000010056 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010057
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010058 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010059
10060 if (IsOrAssign)
10061 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10062 << FixItHint::CreateReplacement(Loc, "!=");
10063 else
10064 Diag(Loc, diag::note_condition_assign_to_comparison)
10065 << FixItHint::CreateReplacement(Loc, "==");
10066
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010067 Diag(Loc, diag::note_condition_assign_silence)
10068 << FixItHint::CreateInsertion(Open, "(")
10069 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +000010070}
10071
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010072/// \brief Redundant parentheses over an equality comparison can indicate
10073/// that the user intended an assignment used as condition.
10074void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010075 // Don't warn if the parens came from a macro.
10076 SourceLocation parenLoc = parenE->getLocStart();
10077 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10078 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010079 // Don't warn for dependent expressions.
10080 if (parenE->isTypeDependent())
10081 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010082
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010083 Expr *E = parenE->IgnoreParens();
10084
10085 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010086 if (opE->getOpcode() == BO_EQ &&
10087 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10088 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010089 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010090
Ted Kremenekae022092011-02-02 02:20:30 +000010091 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10092 Diag(Loc, diag::note_equality_comparison_to_assign)
10093 << FixItHint::CreateReplacement(Loc, "=");
10094 Diag(Loc, diag::note_equality_comparison_silence)
10095 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10096 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010097 }
10098}
10099
John Wiegley01296292011-04-08 18:41:53 +000010100ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010101 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010102 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10103 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010104
10105 if (!E->isTypeDependent()) {
John Wiegley01296292011-04-08 18:41:53 +000010106 if (E->isBoundMemberFunction(Context)) {
10107 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010108 << E->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +000010109 return ExprError();
10110 }
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010111
John McCall34376a62010-12-04 03:47:34 +000010112 if (getLangOptions().CPlusPlus)
10113 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10114
John Wiegley01296292011-04-08 18:41:53 +000010115 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10116 if (ERes.isInvalid())
10117 return ExprError();
10118 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010119
10120 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010121 if (!T->isScalarType()) { // C99 6.8.4.1p1
10122 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10123 << T << E->getSourceRange();
10124 return ExprError();
10125 }
John McCalld5707ab2009-10-12 21:59:07 +000010126 }
10127
John Wiegley01296292011-04-08 18:41:53 +000010128 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010129}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010130
John McCalldadc5752010-08-24 06:29:42 +000010131ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10132 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010133 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010134 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010135
10136 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010137}
John McCall36e7fe32010-10-12 00:20:44 +000010138
John McCall31996342011-04-07 08:22:57 +000010139namespace {
10140 struct RebuildUnknownAnyExpr
10141 : StmtVisitor<RebuildUnknownAnyExpr, Expr*> {
10142
10143 Sema &S;
10144
10145 /// The current destination type.
10146 QualType DestType;
10147
10148 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10149 : S(S), DestType(castType) {}
10150
10151 Expr *VisitStmt(Stmt *S) {
10152 llvm_unreachable("unexpected expression kind!");
10153 return 0;
10154 }
10155
10156 Expr *VisitCallExpr(CallExpr *call) {
10157 call->setCallee(Visit(call->getCallee()));
10158 return call;
10159 }
10160
10161 Expr *VisitParenExpr(ParenExpr *paren) {
10162 paren->setSubExpr(Visit(paren->getSubExpr()));
10163 return paren;
10164 }
10165
10166 Expr *VisitUnaryExtension(UnaryOperator *op) {
10167 op->setSubExpr(Visit(op->getSubExpr()));
10168 return op;
10169 }
10170
10171 Expr *VisitImplicitCastExpr(ImplicitCastExpr *ice) {
10172 // If this isn't an inner resolution, just recurse down.
10173 if (ice->getCastKind() != CK_ResolveUnknownAnyType) {
10174 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
10175 ice->setSubExpr(Visit(ice->getSubExpr()));
10176 return ice;
10177 }
10178
10179 QualType type = ice->getType();
10180 assert(type.getUnqualifiedType() == type);
10181
10182 // The only time it should be possible for this to appear
10183 // internally to an unknown-any expression is when handling a call.
10184 const FunctionProtoType *proto = type->castAs<FunctionProtoType>();
10185 DestType = S.Context.getFunctionType(DestType,
10186 proto->arg_type_begin(),
10187 proto->getNumArgs(),
10188 proto->getExtProtoInfo());
10189
10190 // Strip the resolve cast when recursively rebuilding.
10191 return Visit(ice->getSubExpr());
10192 }
10193
10194 Expr *VisitDeclRefExpr(DeclRefExpr *ref) {
10195 ExprValueKind valueKind = VK_LValue;
10196 if (!S.getLangOptions().CPlusPlus && DestType->isFunctionType())
10197 valueKind = VK_RValue;
10198
10199 return ImplicitCastExpr::Create(S.Context, DestType,
10200 CK_ResolveUnknownAnyType,
10201 ref, 0, valueKind);
10202 }
10203 };
10204}
10205
10206/// Check a cast of an unknown-any type. We intentionally only
10207/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010208ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10209 Expr *castExpr, CastKind &castKind,
10210 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010211 VK = Expr::getValueKindForType(castType);
10212
10213 // Rewrite the casted expression from scratch.
10214 castExpr = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10215
10216 return CheckCastTypes(typeRange, castType, castExpr, castKind, VK, path);
10217}
10218
10219static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10220 Expr *orig = e;
10221 while (true) {
10222 e = e->IgnoreParenImpCasts();
10223 if (CallExpr *call = dyn_cast<CallExpr>(e))
10224 e = call->getCallee();
10225 else
10226 break;
10227 }
10228
10229 assert(isa<DeclRefExpr>(e) && "unexpected form of unknown-any expression");
10230 DeclRefExpr *ref = cast<DeclRefExpr>(e);
10231 S.Diag(ref->getLocation(), diag::err_bad_use_of_unknown_any)
10232 << ref->getDecl() << orig->getSourceRange();
10233
10234 // Never recoverable.
10235 return ExprError();
10236}
10237
John McCall36e7fe32010-10-12 00:20:44 +000010238/// Check for operands with placeholder types and complain if found.
10239/// Returns true if there was an error and no recovery was possible.
10240ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
John McCall31996342011-04-07 08:22:57 +000010241 // Placeholder types are always *exactly* the appropriate builtin type.
10242 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010243
John McCall31996342011-04-07 08:22:57 +000010244 // Overloaded expressions.
10245 if (type == Context.OverloadTy)
10246 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010247 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010248 QualType(),
10249 diag::err_ovl_unresolvable);
10250
10251 // Expressions of unknown type.
10252 if (type == Context.UnknownAnyTy)
10253 return diagnoseUnknownAnyExpr(*this, E);
10254
10255 assert(!type->isPlaceholderType());
10256 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010257}