blob: 55155efa696290772d3df7cbad93bb746786e42f [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).
259void Sema::DefaultFunctionArrayConversion(Expr *&E) {
260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000264 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000265 CK_FunctionToPointerDecay);
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())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000279 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000280 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 }
Chris Lattner513165e2008-07-25 21:10:04 +0000282}
283
John McCall27584242010-12-06 20:48:59 +0000284void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-12-01 04:43:34 +0000285 // C++ [conv.lval]p1:
286 // A glvalue of a non-function, non-array type T can be
287 // converted to a prvalue.
John McCall27584242010-12-06 20:48:59 +0000288 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000289
John McCall27584242010-12-06 20:48:59 +0000290 QualType T = E->getType();
291 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000292
John McCall27584242010-12-06 20:48:59 +0000293 // Create a load out of an ObjCProperty l-value, if necessary.
294 if (E->getObjectKind() == OK_ObjCProperty) {
295 ConvertPropertyForRValue(E);
296 if (!E->isGLValue())
John McCall34376a62010-12-04 03:47:34 +0000297 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000298 }
John McCall27584242010-12-06 20:48:59 +0000299
300 // We don't want to throw lvalue-to-rvalue casts on top of
301 // expressions of certain types in C++.
302 if (getLangOptions().CPlusPlus &&
303 (E->getType() == Context.OverloadTy ||
304 T->isDependentType() ||
305 T->isRecordType()))
306 return;
307
308 // The C standard is actually really unclear on this point, and
309 // DR106 tells us what the result should be but not why. It's
310 // generally best to say that void types just doesn't undergo
311 // lvalue-to-rvalue at all. Note that expressions of unqualified
312 // 'void' type are never l-values, but qualified void can be.
313 if (T->isVoidType())
314 return;
315
316 // C++ [conv.lval]p1:
317 // [...] If T is a non-class type, the type of the prvalue is the
318 // cv-unqualified version of T. Otherwise, the type of the
319 // rvalue is T.
320 //
321 // C99 6.3.2.1p2:
322 // If the lvalue has qualified type, the value has the unqualified
323 // version of the type of the lvalue; otherwise, the value has the
324 // type of the lvalue.
325 if (T.hasQualifiers())
326 T = T.getUnqualifiedType();
327
Ted Kremenekdf26df72011-03-01 18:41:00 +0000328 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000329
John McCall27584242010-12-06 20:48:59 +0000330 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
331 E, 0, VK_RValue);
332}
333
334void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
335 DefaultFunctionArrayConversion(E);
336 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000337}
338
339
Chris Lattner513165e2008-07-25 21:10:04 +0000340/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000341/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000342/// sometimes surpressed. For example, the array->pointer conversion doesn't
343/// apply if the array is an argument to the sizeof or address (&) operators.
344/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000345Expr *Sema::UsualUnaryConversions(Expr *&E) {
346 // First, convert to an r-value.
347 DefaultFunctionArrayLvalueConversion(E);
348
349 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000350 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000351
352 // Try to perform integral promotions if the object has a theoretically
353 // promotable type.
354 if (Ty->isIntegralOrUnscopedEnumerationType()) {
355 // C99 6.3.1.1p2:
356 //
357 // The following may be used in an expression wherever an int or
358 // unsigned int may be used:
359 // - an object or expression with an integer type whose integer
360 // conversion rank is less than or equal to the rank of int
361 // and unsigned int.
362 // - A bit-field of type _Bool, int, signed int, or unsigned int.
363 //
364 // If an int can represent all values of the original type, the
365 // value is converted to an int; otherwise, it is converted to an
366 // unsigned int. These are called the integer promotions. All
367 // other types are unchanged by the integer promotions.
368
369 QualType PTy = Context.isPromotableBitField(E);
370 if (!PTy.isNull()) {
371 ImpCastExprToType(E, PTy, CK_IntegralCast);
372 return E;
373 }
374 if (Ty->isPromotableIntegerType()) {
375 QualType PT = Context.getPromotedIntegerType(Ty);
376 ImpCastExprToType(E, PT, CK_IntegralCast);
377 return E;
378 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000379 }
380
John McCallf3735e02010-12-01 04:43:34 +0000381 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000382}
383
Chris Lattner2ce500f2008-07-25 22:25:12 +0000384/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000385/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000386/// double. All other argument types are converted by UsualUnaryConversions().
387void Sema::DefaultArgumentPromotion(Expr *&Expr) {
388 QualType Ty = Expr->getType();
389 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000390
John McCall9bc26772010-12-06 18:36:11 +0000391 UsualUnaryConversions(Expr);
392
Chris Lattner2ce500f2008-07-25 22:25:12 +0000393 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000394 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000395 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000396}
397
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000398/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
399/// will warn if the resulting type is not a POD type, and rejects ObjC
400/// interfaces passed by value. This returns true if the argument type is
401/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000402bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
403 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000404 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000406 // __builtin_va_start takes the second argument as a "varargs" argument, but
407 // it doesn't actually do anything with it. It doesn't need to be non-pod
408 // etc.
409 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
410 return false;
411
John McCall8b07ec22010-05-15 11:32:37 +0000412 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000413 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000414 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
415 << Expr->getType() << CT))
416 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000417
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000418 if (!Expr->getType()->isPODType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000419 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000420 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
421 << Expr->getType() << CT))
422 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000423
424 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000425}
426
Chris Lattner513165e2008-07-25 21:10:04 +0000427/// UsualArithmeticConversions - Performs various conversions that are common to
428/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000429/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000430/// responsible for emitting appropriate error diagnostics.
431/// FIXME: verify the conversion rules for "complex int" are consistent with
432/// GCC.
433QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
434 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000435 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000436 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000437
438 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000439
Mike Stump11289f42009-09-09 15:08:12 +0000440 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000441 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000442 QualType lhs =
443 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000445 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000446
447 // If both types are identical, no conversion is needed.
448 if (lhs == rhs)
449 return lhs;
450
451 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
452 // The caller can deal with this (e.g. pointer + int).
453 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
454 return lhs;
455
John McCalld005ac92010-11-13 08:17:45 +0000456 // Apply unary and bitfield promotions to the LHS's type.
457 QualType lhs_unpromoted = lhs;
458 if (lhs->isPromotableIntegerType())
459 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000460 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000461 if (!LHSBitfieldPromoteTy.isNull())
462 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000463 if (lhs != lhs_unpromoted && !isCompAssign)
464 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000465
John McCalld005ac92010-11-13 08:17:45 +0000466 // If both types are identical, no conversion is needed.
467 if (lhs == rhs)
468 return lhs;
469
470 // At this point, we have two different arithmetic types.
471
472 // Handle complex types first (C99 6.3.1.8p1).
473 bool LHSComplexFloat = lhs->isComplexType();
474 bool RHSComplexFloat = rhs->isComplexType();
475 if (LHSComplexFloat || RHSComplexFloat) {
476 // if we have an integer operand, the result is the complex type.
477
John McCallc5e62b42010-11-13 09:02:35 +0000478 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
479 if (rhs->isIntegerType()) {
480 QualType fp = cast<ComplexType>(lhs)->getElementType();
481 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
482 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
483 } else {
484 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000485 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000486 }
John McCalld005ac92010-11-13 08:17:45 +0000487 return lhs;
488 }
489
John McCallc5e62b42010-11-13 09:02:35 +0000490 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
491 if (!isCompAssign) {
492 // int -> float -> _Complex float
493 if (lhs->isIntegerType()) {
494 QualType fp = cast<ComplexType>(rhs)->getElementType();
495 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
496 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
497 } else {
498 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000499 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000500 }
501 }
John McCalld005ac92010-11-13 08:17:45 +0000502 return rhs;
503 }
504
505 // This handles complex/complex, complex/float, or float/complex.
506 // When both operands are complex, the shorter operand is converted to the
507 // type of the longer, and that is the type of the result. This corresponds
508 // to what is done when combining two real floating-point operands.
509 // The fun begins when size promotion occur across type domains.
510 // From H&S 6.3.4: When one operand is complex and the other is a real
511 // floating-point type, the less precise type is converted, within it's
512 // real or complex domain, to the precision of the other type. For example,
513 // when combining a "long double" with a "double _Complex", the
514 // "double _Complex" is promoted to "long double _Complex".
515 int order = Context.getFloatingTypeOrder(lhs, rhs);
516
517 // If both are complex, just cast to the more precise type.
518 if (LHSComplexFloat && RHSComplexFloat) {
519 if (order > 0) {
520 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000521 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000522 return lhs;
523
524 } else if (order < 0) {
525 // _Complex float -> _Complex double
526 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000527 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000528 return rhs;
529 }
530 return lhs;
531 }
532
533 // If just the LHS is complex, the RHS needs to be converted,
534 // and the LHS might need to be promoted.
535 if (LHSComplexFloat) {
536 if (order > 0) { // LHS is wider
537 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000538 QualType fp = cast<ComplexType>(lhs)->getElementType();
539 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
540 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000541 return lhs;
542 }
543
544 // RHS is at least as wide. Find its corresponding complex type.
545 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
546
547 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000548 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000549
550 // _Complex float -> _Complex double
551 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000552 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000553
554 return result;
555 }
556
557 // Just the RHS is complex, so the LHS needs to be converted
558 // and the RHS might need to be promoted.
559 assert(RHSComplexFloat);
560
561 if (order < 0) { // RHS is wider
562 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000563 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000564 QualType fp = cast<ComplexType>(rhs)->getElementType();
565 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000566 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
567 }
John McCalld005ac92010-11-13 08:17:45 +0000568 return rhs;
569 }
570
571 // LHS is at least as wide. Find its corresponding complex type.
572 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
573
574 // double -> _Complex double
575 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000576 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000577
578 // _Complex float -> _Complex double
579 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000580 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000581
582 return result;
583 }
584
585 // Now handle "real" floating types (i.e. float, double, long double).
586 bool LHSFloat = lhs->isRealFloatingType();
587 bool RHSFloat = rhs->isRealFloatingType();
588 if (LHSFloat || RHSFloat) {
589 // If we have two real floating types, convert the smaller operand
590 // to the bigger result.
591 if (LHSFloat && RHSFloat) {
592 int order = Context.getFloatingTypeOrder(lhs, rhs);
593 if (order > 0) {
594 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
595 return lhs;
596 }
597
598 assert(order < 0 && "illegal float comparison");
599 if (!isCompAssign)
600 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
601 return rhs;
602 }
603
604 // If we have an integer operand, the result is the real floating type.
605 if (LHSFloat) {
606 if (rhs->isIntegerType()) {
607 // Convert rhs to the lhs floating point type.
608 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
609 return lhs;
610 }
611
612 // Convert both sides to the appropriate complex float.
613 assert(rhs->isComplexIntegerType());
614 QualType result = Context.getComplexType(lhs);
615
616 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000617 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000618
619 // float -> _Complex float
620 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000621 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000622
623 return result;
624 }
625
626 assert(RHSFloat);
627 if (lhs->isIntegerType()) {
628 // Convert lhs to the rhs floating point type.
629 if (!isCompAssign)
630 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
631 return rhs;
632 }
633
634 // Convert both sides to the appropriate complex float.
635 assert(lhs->isComplexIntegerType());
636 QualType result = Context.getComplexType(rhs);
637
638 // _Complex int -> _Complex float
639 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000640 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641
642 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000643 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000644
645 return result;
646 }
647
648 // Handle GCC complex int extension.
649 // FIXME: if the operands are (int, _Complex long), we currently
650 // don't promote the complex. Also, signedness?
651 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
652 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
653 if (lhsComplexInt && rhsComplexInt) {
654 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
655 rhsComplexInt->getElementType());
656 assert(order && "inequal types with equal element ordering");
657 if (order > 0) {
658 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000659 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000660 return lhs;
661 }
662
663 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000665 return rhs;
666 } else if (lhsComplexInt) {
667 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000668 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000669 return lhs;
670 } else if (rhsComplexInt) {
671 // int -> _Complex int
672 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000674 return rhs;
675 }
676
677 // Finally, we have two differing integer types.
678 // The rules for this case are in C99 6.3.1.8
679 int compare = Context.getIntegerTypeOrder(lhs, rhs);
680 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
681 rhsSigned = rhs->hasSignedIntegerRepresentation();
682 if (lhsSigned == rhsSigned) {
683 // Same signedness; use the higher-ranked type
684 if (compare >= 0) {
685 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
686 return lhs;
687 } else if (!isCompAssign)
688 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
689 return rhs;
690 } else if (compare != (lhsSigned ? 1 : -1)) {
691 // The unsigned type has greater than or equal rank to the
692 // signed type, so use the unsigned type
693 if (rhsSigned) {
694 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
695 return lhs;
696 } else if (!isCompAssign)
697 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
698 return rhs;
699 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
700 // The two types are different widths; if we are here, that
701 // means the signed type is larger than the unsigned type, so
702 // use the signed type.
703 if (lhsSigned) {
704 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
705 return lhs;
706 } else if (!isCompAssign)
707 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
708 return rhs;
709 } else {
710 // The signed type is higher-ranked than the unsigned type,
711 // but isn't actually any bigger (like unsigned int and long
712 // on most 32-bit systems). Use the unsigned type corresponding
713 // to the signed type.
714 QualType result =
715 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
716 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
717 if (!isCompAssign)
718 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
719 return result;
720 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000721}
722
Chris Lattner513165e2008-07-25 21:10:04 +0000723//===----------------------------------------------------------------------===//
724// Semantic Analysis for various Expression Types
725//===----------------------------------------------------------------------===//
726
727
Steve Naroff83895f72007-09-16 03:34:24 +0000728/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000729/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
730/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
731/// multiple tokens. However, the common case is that StringToks points to one
732/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000733///
John McCalldadc5752010-08-24 06:29:42 +0000734ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000735Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000736 assert(NumStringToks && "Must have at least one string!");
737
Chris Lattner8a24e582009-01-16 18:51:42 +0000738 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000739 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000740 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000741
Chris Lattner23b7eb62007-06-15 23:05:46 +0000742 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000743 for (unsigned i = 0; i != NumStringToks; ++i)
744 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000745
Chris Lattner36fc8792008-02-11 00:02:17 +0000746 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000747 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000748 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000749
750 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000751 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000752 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000753
Chris Lattner36fc8792008-02-11 00:02:17 +0000754 // Get an array type for the string, according to C99 6.4.5. This includes
755 // the nul terminator character as well as the string length for pascal
756 // strings.
757 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000758 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000759 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattner5b183d82006-11-10 05:03:26 +0000761 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000762 return Owned(StringLiteral::Create(Context, Literal.GetString(),
763 Literal.GetStringLength(),
764 Literal.AnyWide, StrTy,
765 &StringTokLocs[0],
766 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000767}
768
John McCallc63de662011-02-02 13:00:07 +0000769enum CaptureResult {
770 /// No capture is required.
771 CR_NoCapture,
772
773 /// A capture is required.
774 CR_Capture,
775
John McCall351762c2011-02-07 10:33:21 +0000776 /// A by-ref capture is required.
777 CR_CaptureByRef,
778
John McCallc63de662011-02-02 13:00:07 +0000779 /// An error occurred when trying to capture the given variable.
780 CR_Error
781};
782
783/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000784///
John McCallc63de662011-02-02 13:00:07 +0000785/// \param var - the variable referenced
786/// \param DC - the context which we couldn't capture through
787static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000788diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000789 VarDecl *var, DeclContext *DC) {
790 switch (S.ExprEvalContexts.back().Context) {
791 case Sema::Unevaluated:
792 // The argument will never be evaluated, so don't complain.
793 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000794
John McCallc63de662011-02-02 13:00:07 +0000795 case Sema::PotentiallyEvaluated:
796 case Sema::PotentiallyEvaluatedIfUsed:
797 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000798
John McCallc63de662011-02-02 13:00:07 +0000799 case Sema::PotentiallyPotentiallyEvaluated:
800 // FIXME: delay these!
801 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000802 }
Mike Stump11289f42009-09-09 15:08:12 +0000803
John McCallc63de662011-02-02 13:00:07 +0000804 // Don't diagnose about capture if we're not actually in code right
805 // now; in general, there are more appropriate places that will
806 // diagnose this.
807 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
808
John McCall92d627e2011-03-22 23:15:50 +0000809 // Certain madnesses can happen with parameter declarations, which
810 // we want to ignore.
811 if (isa<ParmVarDecl>(var)) {
812 // - If the parameter still belongs to the translation unit, then
813 // we're actually just using one parameter in the declaration of
814 // the next. This is useful in e.g. VLAs.
815 if (isa<TranslationUnitDecl>(var->getDeclContext()))
816 return CR_NoCapture;
817
818 // - This particular madness can happen in ill-formed default
819 // arguments; claim it's okay and let downstream code handle it.
820 if (S.CurContext == var->getDeclContext()->getParent())
821 return CR_NoCapture;
822 }
John McCallc63de662011-02-02 13:00:07 +0000823
824 DeclarationName functionName;
825 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
826 functionName = fn->getDeclName();
827 // FIXME: variable from enclosing block that we couldn't capture from!
828
829 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
830 << var->getIdentifier() << functionName;
831 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
832 << var->getIdentifier();
833
834 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000835}
836
John McCall351762c2011-02-07 10:33:21 +0000837/// There is a well-formed capture at a particular scope level;
838/// propagate it through all the nested blocks.
839static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
840 const BlockDecl::Capture &capture) {
841 VarDecl *var = capture.getVariable();
842
843 // Update all the inner blocks with the capture information.
844 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
845 i != e; ++i) {
846 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
847 innerBlock->Captures.push_back(
848 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
849 /*nested*/ true, capture.getCopyExpr()));
850 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
851 }
852
853 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
854}
855
856/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000857/// given value in the current context requires a variable capture.
858///
859/// This also keeps the captures set in the BlockScopeInfo records
860/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000861static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000862 ValueDecl *value) {
863 // Only variables ever require capture.
864 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000865 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000866
867 // Fast path: variables from the current context never require capture.
868 DeclContext *DC = S.CurContext;
869 if (var->getDeclContext() == DC) return CR_NoCapture;
870
871 // Only variables with local storage require capture.
872 // FIXME: What about 'const' variables in C++?
873 if (!var->hasLocalStorage()) return CR_NoCapture;
874
875 // Otherwise, we need to capture.
876
877 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000878 do {
879 // Only blocks (and eventually C++0x closures) can capture; other
880 // scopes don't work.
881 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000882 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000883
884 BlockScopeInfo *blockScope =
885 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
886 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
887
John McCall351762c2011-02-07 10:33:21 +0000888 // Check whether we've already captured it in this block. If so,
889 // we're done.
890 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
891 return propagateCapture(S, functionScopesIndex,
892 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000893
894 functionScopesIndex--;
895 DC = cast<BlockDecl>(DC)->getDeclContext();
896 } while (var->getDeclContext() != DC);
897
John McCall351762c2011-02-07 10:33:21 +0000898 // Okay, we descended all the way to the block that defines the variable.
899 // Actually try to capture it.
900 QualType type = var->getType();
901
902 // Prohibit variably-modified types.
903 if (type->isVariablyModifiedType()) {
904 S.Diag(loc, diag::err_ref_vm_type);
905 S.Diag(var->getLocation(), diag::note_declared_at);
906 return CR_Error;
907 }
908
909 // Prohibit arrays, even in __block variables, but not references to
910 // them.
911 if (type->isArrayType()) {
912 S.Diag(loc, diag::err_ref_array_type);
913 S.Diag(var->getLocation(), diag::note_declared_at);
914 return CR_Error;
915 }
916
917 S.MarkDeclarationReferenced(loc, var);
918
919 // The BlocksAttr indicates the variable is bound by-reference.
920 bool byRef = var->hasAttr<BlocksAttr>();
921
922 // Build a copy expression.
923 Expr *copyExpr = 0;
924 if (!byRef && S.getLangOptions().CPlusPlus &&
925 !type->isDependentType() && type->isStructureOrClassType()) {
926 // According to the blocks spec, the capture of a variable from
927 // the stack requires a const copy constructor. This is not true
928 // of the copy/move done to move a __block variable to the heap.
929 type.addConst();
930
931 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
932 ExprResult result =
933 S.PerformCopyInitialization(
934 InitializedEntity::InitializeBlock(var->getLocation(),
935 type, false),
936 loc, S.Owned(declRef));
937
938 // Build a full-expression copy expression if initialization
939 // succeeded and used a non-trivial constructor. Recover from
940 // errors by pretending that the copy isn't necessary.
941 if (!result.isInvalid() &&
942 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
943 result = S.MaybeCreateExprWithCleanups(result);
944 copyExpr = result.take();
945 }
946 }
947
948 // We're currently at the declarer; go back to the closure.
949 functionScopesIndex++;
950 BlockScopeInfo *blockScope =
951 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
952
953 // Build a valid capture in this scope.
954 blockScope->Captures.push_back(
955 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
956 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
957
958 // Propagate that to inner captures if necessary.
959 return propagateCapture(S, functionScopesIndex,
960 blockScope->Captures.back());
961}
962
963static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
964 const DeclarationNameInfo &NameInfo,
965 bool byRef) {
966 assert(isa<VarDecl>(vd) && "capturing non-variable");
967
968 VarDecl *var = cast<VarDecl>(vd);
969 assert(var->hasLocalStorage() && "capturing non-local");
970 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
971
972 QualType exprType = var->getType().getNonReferenceType();
973
974 BlockDeclRefExpr *BDRE;
975 if (!byRef) {
976 // The variable will be bound by copy; make it const within the
977 // closure, but record that this was done in the expression.
978 bool constAdded = !exprType.isConstQualified();
979 exprType.addConst();
980
981 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
982 NameInfo.getLoc(), false,
983 constAdded);
984 } else {
985 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
986 NameInfo.getLoc(), true);
987 }
988
989 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000990}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000991
John McCalldadc5752010-08-24 06:29:42 +0000992ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000993Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000994 SourceLocation Loc,
995 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000996 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000997 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000998}
999
John McCallf4cd4f92011-02-09 01:13:10 +00001000/// BuildDeclRefExpr - Build an expression that references a
1001/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001002ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001003Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001004 const DeclarationNameInfo &NameInfo,
1005 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001006 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001007
John McCall086a4642010-11-24 05:12:34 +00001008 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001009 SS? SS->getWithLocInContext(Context)
1010 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001011 D, NameInfo, Ty, VK);
1012
1013 // Just in case we're building an illegal pointer-to-member.
1014 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1015 E->setObjectKind(OK_BitField);
1016
1017 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001018}
1019
John McCallfeb624a2010-11-23 20:48:44 +00001020static ExprResult
1021BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1022 const CXXScopeSpec &SS, FieldDecl *Field,
1023 DeclAccessPair FoundDecl,
1024 const DeclarationNameInfo &MemberNameInfo);
1025
John McCalldadc5752010-08-24 06:29:42 +00001026ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001027Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1028 SourceLocation loc,
1029 IndirectFieldDecl *indirectField,
1030 Expr *baseObjectExpr,
1031 SourceLocation opLoc) {
1032 // First, build the expression that refers to the base object.
1033
1034 bool baseObjectIsPointer = false;
1035 Qualifiers baseQuals;
1036
1037 // Case 1: the base of the indirect field is not a field.
1038 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001039 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001040 if (baseVariable) {
1041 assert(baseVariable->getType()->isRecordType());
1042
1043 // In principle we could have a member access expression that
1044 // accesses an anonymous struct/union that's a static member of
1045 // the base object's class. However, under the current standard,
1046 // static data members cannot be anonymous structs or unions.
1047 // Supporting this is as easy as building a MemberExpr here.
1048 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1049
1050 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1051
1052 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001053 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001054 if (result.isInvalid()) return ExprError();
1055
1056 baseObjectExpr = result.take();
1057 baseObjectIsPointer = false;
1058 baseQuals = baseObjectExpr->getType().getQualifiers();
1059
1060 // Case 2: the base of the indirect field is a field and the user
1061 // wrote a member expression.
1062 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001063 // The caller provided the base object expression. Determine
1064 // whether its a pointer and whether it adds any qualifiers to the
1065 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001066 QualType objectType = baseObjectExpr->getType();
1067
1068 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1069 baseObjectIsPointer = true;
1070 objectType = ptr->getPointeeType();
1071 } else {
1072 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001073 }
John McCallf3a88602011-02-03 08:15:49 +00001074 baseQuals = objectType.getQualifiers();
1075
1076 // Case 3: the base of the indirect field is a field and we should
1077 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001078 } else {
1079 // We've found a member of an anonymous struct/union that is
1080 // inside a non-anonymous struct/union, so in a well-formed
1081 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001082 CXXMethodDecl *method = tryCaptureCXXThis();
1083 if (!method) {
1084 Diag(loc, diag::err_invalid_member_use_in_static_method)
1085 << indirectField->getDeclName();
1086 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001087 }
1088
John McCallf3a88602011-02-03 08:15:49 +00001089 // Our base object expression is "this".
1090 baseObjectExpr =
1091 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1092 /*isImplicit=*/ true);
1093 baseObjectIsPointer = true;
1094 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001095 }
1096
1097 // Build the implicit member references to the field of the
1098 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001099 Expr *result = baseObjectExpr;
1100 IndirectFieldDecl::chain_iterator
1101 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001102
John McCallf3a88602011-02-03 08:15:49 +00001103 // Build the first member access in the chain with full information.
1104 if (!baseVariable) {
1105 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001106
John McCallf3a88602011-02-03 08:15:49 +00001107 // FIXME: use the real found-decl info!
1108 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001109
John McCallf3a88602011-02-03 08:15:49 +00001110 // Make a nameInfo that properly uses the anonymous name.
1111 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001112
John McCallf3a88602011-02-03 08:15:49 +00001113 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001114 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001115 memberNameInfo).take();
1116 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001117
John McCallf3a88602011-02-03 08:15:49 +00001118 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001119 }
1120
John McCallf3a88602011-02-03 08:15:49 +00001121 // In all cases, we should now skip the first declaration in the chain.
1122 ++FI;
1123
Douglas Gregore10f36d2011-02-18 02:44:58 +00001124 while (FI != FEnd) {
1125 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001126
1127 // FIXME: these are somewhat meaningless
1128 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1129 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001130
1131 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001132 (FI == FEnd? SS : EmptySS), field,
1133 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001134 .take();
1135 }
1136
1137 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001138}
1139
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001140/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001141/// possibly a list of template arguments.
1142///
1143/// If this produces template arguments, it is permitted to call
1144/// DecomposeTemplateName.
1145///
1146/// This actually loses a lot of source location information for
1147/// non-standard name kinds; we should consider preserving that in
1148/// some way.
1149static void DecomposeUnqualifiedId(Sema &SemaRef,
1150 const UnqualifiedId &Id,
1151 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001152 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001153 const TemplateArgumentListInfo *&TemplateArgs) {
1154 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1155 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1156 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1157
1158 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1159 Id.TemplateId->getTemplateArgs(),
1160 Id.TemplateId->NumArgs);
1161 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1162 TemplateArgsPtr.release();
1163
John McCall3e56fd42010-08-23 07:28:44 +00001164 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001165 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1166 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001167 TemplateArgs = &Buffer;
1168 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001169 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001170 TemplateArgs = 0;
1171 }
1172}
1173
John McCall2d74de92009-12-01 22:10:20 +00001174/// Determines if the given class is provably not derived from all of
1175/// the prospective base classes.
1176static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1177 CXXRecordDecl *Record,
1178 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001179 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001180 return false;
1181
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001182 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001183 if (!RD) return false;
1184 Record = cast<CXXRecordDecl>(RD);
1185
John McCall2d74de92009-12-01 22:10:20 +00001186 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1187 E = Record->bases_end(); I != E; ++I) {
1188 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1189 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1190 if (!BaseRT) return false;
1191
1192 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001193 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1194 return false;
1195 }
1196
1197 return true;
1198}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001199
John McCall2d74de92009-12-01 22:10:20 +00001200enum IMAKind {
1201 /// The reference is definitely not an instance member access.
1202 IMA_Static,
1203
1204 /// The reference may be an implicit instance member access.
1205 IMA_Mixed,
1206
1207 /// The reference may be to an instance member, but it is invalid if
1208 /// so, because the context is not an instance method.
1209 IMA_Mixed_StaticContext,
1210
1211 /// The reference may be to an instance member, but it is invalid if
1212 /// so, because the context is from an unrelated class.
1213 IMA_Mixed_Unrelated,
1214
1215 /// The reference is definitely an implicit instance member access.
1216 IMA_Instance,
1217
1218 /// The reference may be to an unresolved using declaration.
1219 IMA_Unresolved,
1220
1221 /// The reference may be to an unresolved using declaration and the
1222 /// context is not an instance method.
1223 IMA_Unresolved_StaticContext,
1224
John McCall2d74de92009-12-01 22:10:20 +00001225 /// All possible referrents are instance members and the current
1226 /// context is not an instance method.
1227 IMA_Error_StaticContext,
1228
1229 /// All possible referrents are instance members of an unrelated
1230 /// class.
1231 IMA_Error_Unrelated
1232};
1233
1234/// The given lookup names class member(s) and is not being used for
1235/// an address-of-member expression. Classify the type of access
1236/// according to whether it's possible that this reference names an
1237/// instance member. This is best-effort; it is okay to
1238/// conservatively answer "yes", in which case some errors will simply
1239/// not be caught until template-instantiation.
1240static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1241 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001242 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001243
John McCall87fe5d52010-05-20 01:18:31 +00001244 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001245 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001246 (!isa<CXXMethodDecl>(DC) ||
1247 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001248
1249 if (R.isUnresolvableResult())
1250 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1251
1252 // Collect all the declaring classes of instance members we find.
1253 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001254 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001255 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1256 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001257 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001258
John McCalla8ae2222010-04-06 21:38:20 +00001259 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001260 if (dyn_cast<FieldDecl>(D))
1261 hasField = true;
1262
John McCall2d74de92009-12-01 22:10:20 +00001263 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001264 Classes.insert(R->getCanonicalDecl());
1265 }
1266 else
1267 hasNonInstance = true;
1268 }
1269
1270 // If we didn't find any instance members, it can't be an implicit
1271 // member reference.
1272 if (Classes.empty())
1273 return IMA_Static;
1274
1275 // If the current context is not an instance method, it can't be
1276 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001277 if (isStaticContext) {
1278 if (hasNonInstance)
1279 return IMA_Mixed_StaticContext;
1280
1281 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1282 // C++0x [expr.prim.general]p10:
1283 // An id-expression that denotes a non-static data member or non-static
1284 // member function of a class can only be used:
1285 // (...)
1286 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1287 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1288 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1289 if (isUnevaluatedExpression)
1290 return IMA_Mixed_StaticContext;
1291 }
1292
1293 return IMA_Error_StaticContext;
1294 }
John McCall2d74de92009-12-01 22:10:20 +00001295
1296 // If we can prove that the current context is unrelated to all the
1297 // declaring classes, it can't be an implicit member reference (in
1298 // which case it's an error if any of those members are selected).
1299 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001300 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001301 Classes))
1302 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1303
1304 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1305}
1306
1307/// Diagnose a reference to a field with no object available.
1308static void DiagnoseInstanceReference(Sema &SemaRef,
1309 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001310 NamedDecl *rep,
1311 const DeclarationNameInfo &nameInfo) {
1312 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001313 SourceRange Range(Loc);
1314 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1315
John McCallf3a88602011-02-03 08:15:49 +00001316 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001317 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1318 if (MD->isStatic()) {
1319 // "invalid use of member 'x' in static member function"
1320 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001321 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001322 return;
1323 }
1324 }
1325
1326 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001327 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001328 return;
1329 }
1330
1331 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001332}
1333
John McCalld681c392009-12-16 08:11:27 +00001334/// Diagnose an empty lookup.
1335///
1336/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001337bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1338 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001339 DeclarationName Name = R.getLookupName();
1340
John McCalld681c392009-12-16 08:11:27 +00001341 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001342 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001343 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1344 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001345 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001346 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001347 diagnostic_suggest = diag::err_undeclared_use_suggest;
1348 }
John McCalld681c392009-12-16 08:11:27 +00001349
Douglas Gregor598b08f2009-12-31 05:20:13 +00001350 // If the original lookup was an unqualified lookup, fake an
1351 // unqualified lookup. This is useful when (for example) the
1352 // original lookup would not have found something because it was a
1353 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001354 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001355 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001356 if (isa<CXXRecordDecl>(DC)) {
1357 LookupQualifiedName(R, DC);
1358
1359 if (!R.empty()) {
1360 // Don't give errors about ambiguities in this lookup.
1361 R.suppressDiagnostics();
1362
1363 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1364 bool isInstance = CurMethod &&
1365 CurMethod->isInstance() &&
1366 DC == CurMethod->getParent();
1367
1368 // Give a code modification hint to insert 'this->'.
1369 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1370 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001371 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001372 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1373 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001374 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001375 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001376 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001377 Diag(R.getNameLoc(), diagnostic) << Name
1378 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1379 QualType DepThisType = DepMethod->getThisType(Context);
1380 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1381 R.getNameLoc(), DepThisType, false);
1382 TemplateArgumentListInfo TList;
1383 if (ULE->hasExplicitTemplateArgs())
1384 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001385
Douglas Gregore16af532011-02-28 18:50:33 +00001386 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001387 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001388 CXXDependentScopeMemberExpr *DepExpr =
1389 CXXDependentScopeMemberExpr::Create(
1390 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001391 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001392 R.getLookupNameInfo(), &TList);
1393 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001394 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001395 // FIXME: we should be able to handle this case too. It is correct
1396 // to add this-> here. This is a workaround for PR7947.
1397 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001398 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001399 } else {
John McCalld681c392009-12-16 08:11:27 +00001400 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001401 }
John McCalld681c392009-12-16 08:11:27 +00001402
1403 // Do we really want to note all of these?
1404 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1405 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1406
1407 // Tell the callee to try to recover.
1408 return false;
1409 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001410
1411 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001412 }
1413 }
1414
Douglas Gregor598b08f2009-12-31 05:20:13 +00001415 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001416 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001417 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001418 if (!R.empty()) {
1419 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1420 if (SS.isEmpty())
1421 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1422 << FixItHint::CreateReplacement(R.getNameLoc(),
1423 R.getLookupName().getAsString());
1424 else
1425 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1426 << Name << computeDeclContext(SS, false) << R.getLookupName()
1427 << SS.getRange()
1428 << FixItHint::CreateReplacement(R.getNameLoc(),
1429 R.getLookupName().getAsString());
1430 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1431 Diag(ND->getLocation(), diag::note_previous_decl)
1432 << ND->getDeclName();
1433
1434 // Tell the callee to try to recover.
1435 return false;
1436 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001437
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001438 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1439 // FIXME: If we ended up with a typo for a type name or
1440 // Objective-C class name, we're in trouble because the parser
1441 // is in the wrong place to recover. Suggest the typo
1442 // correction, but don't make it a fix-it since we're not going
1443 // to recover well anyway.
1444 if (SS.isEmpty())
1445 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1446 else
1447 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1448 << Name << computeDeclContext(SS, false) << R.getLookupName()
1449 << SS.getRange();
1450
1451 // Don't try to recover; it won't work.
1452 return true;
1453 }
1454 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001455 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001456 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001457 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001458 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001459 else
Douglas Gregor25363982010-01-01 00:15:04 +00001460 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001461 << Name << computeDeclContext(SS, false) << Corrected
1462 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001463 return true;
1464 }
Douglas Gregor25363982010-01-01 00:15:04 +00001465 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001466 }
1467
1468 // Emit a special diagnostic for failed member lookups.
1469 // FIXME: computing the declaration context might fail here (?)
1470 if (!SS.isEmpty()) {
1471 Diag(R.getNameLoc(), diag::err_no_member)
1472 << Name << computeDeclContext(SS, false)
1473 << SS.getRange();
1474 return true;
1475 }
1476
John McCalld681c392009-12-16 08:11:27 +00001477 // Give up, we can't recover.
1478 Diag(R.getNameLoc(), diagnostic) << Name;
1479 return true;
1480}
1481
Douglas Gregor05fcf842010-11-02 20:36:02 +00001482ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1483 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001484 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1485 if (!IDecl)
1486 return 0;
1487 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1488 if (!ClassImpDecl)
1489 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001490 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001491 if (!property)
1492 return 0;
1493 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001494 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1495 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001496 return 0;
1497 return property;
1498}
1499
Douglas Gregor05fcf842010-11-02 20:36:02 +00001500bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1501 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1502 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1503 if (!IDecl)
1504 return false;
1505 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1506 if (!ClassImpDecl)
1507 return false;
1508 if (ObjCPropertyImplDecl *PIDecl
1509 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1510 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1511 PIDecl->getPropertyIvarDecl())
1512 return false;
1513
1514 return true;
1515}
1516
Fariborz Jahanian18722982010-07-17 00:59:30 +00001517static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001518 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001519 IdentifierInfo *II,
1520 SourceLocation NameLoc) {
1521 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001522 bool LookForIvars;
1523 if (Lookup.empty())
1524 LookForIvars = true;
1525 else if (CurMeth->isClassMethod())
1526 LookForIvars = false;
1527 else
1528 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001529 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1530 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001531 if (!LookForIvars)
1532 return 0;
1533
Fariborz Jahanian18722982010-07-17 00:59:30 +00001534 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1535 if (!IDecl)
1536 return 0;
1537 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001538 if (!ClassImpDecl)
1539 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001540 bool DynamicImplSeen = false;
1541 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1542 if (!property)
1543 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001544 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001545 DynamicImplSeen =
1546 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001547 // property implementation has a designated ivar. No need to assume a new
1548 // one.
1549 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1550 return 0;
1551 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001552 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001553 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1554 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001555 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001556 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001557 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001558 (Expr *)0, true);
1559 ClassImpDecl->addDecl(Ivar);
1560 IDecl->makeDeclVisibleInContext(Ivar, false);
1561 property->setPropertyIvarDecl(Ivar);
1562 return Ivar;
1563 }
1564 return 0;
1565}
1566
John McCalldadc5752010-08-24 06:29:42 +00001567ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001568 CXXScopeSpec &SS,
1569 UnqualifiedId &Id,
1570 bool HasTrailingLParen,
1571 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001572 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1573 "cannot be direct & operand and have a trailing lparen");
1574
1575 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001576 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001577
John McCall10eae182009-11-30 22:42:35 +00001578 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001579
1580 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001582 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001583 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001584
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001586 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001588
John McCalle66edc12009-11-24 19:00:30 +00001589 // C++ [temp.dep.expr]p3:
1590 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001591 // -- an identifier that was declared with a dependent type,
1592 // (note: handled after lookup)
1593 // -- a template-id that is dependent,
1594 // (note: handled in BuildTemplateIdExpr)
1595 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001596 // -- a nested-name-specifier that contains a class-name that
1597 // names a dependent type.
1598 // Determine whether this is a member of an unknown specialization;
1599 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001600 bool DependentID = false;
1601 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1602 Name.getCXXNameType()->isDependentType()) {
1603 DependentID = true;
1604 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001605 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001606 if (RequireCompleteDeclContext(SS, DC))
1607 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001608 } else {
1609 DependentID = true;
1610 }
1611 }
1612
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001613 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001614 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001615 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001616
Fariborz Jahanian86151342010-07-22 23:33:21 +00001617 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001618 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001619 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001620 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001621 // Lookup the template name again to correctly establish the context in
1622 // which it was found. This is really unfortunate as we already did the
1623 // lookup to determine that it was a template name in the first place. If
1624 // this becomes a performance hit, we can work harder to preserve those
1625 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001626 bool MemberOfUnknownSpecialization;
1627 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1628 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001629
1630 if (MemberOfUnknownSpecialization ||
1631 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1632 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1633 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001634 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001635 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001636 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001637
Douglas Gregora5226932011-02-04 13:35:07 +00001638 // If the result might be in a dependent base class, this is a dependent
1639 // id-expression.
1640 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1641 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1642 TemplateArgs);
1643
John McCalle66edc12009-11-24 19:00:30 +00001644 // If this reference is in an Objective-C method, then we need to do
1645 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001646 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001647 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001648 if (E.isInvalid())
1649 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001651 if (Expr *Ex = E.takeAs<Expr>())
1652 return Owned(Ex);
1653
1654 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001655 if (getLangOptions().ObjCDefaultSynthProperties &&
1656 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001657 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1658 if (const ObjCPropertyDecl *Property =
1659 canSynthesizeProvisionalIvar(II)) {
1660 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1661 Diag(Property->getLocation(), diag::note_property_declare);
1662 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001663 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1664 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001665 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001666 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001667 // for further use, this must be set to false if in class method.
1668 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001669 }
Chris Lattner59a25942008-03-31 00:36:02 +00001670 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001671
John McCalle66edc12009-11-24 19:00:30 +00001672 if (R.isAmbiguous())
1673 return ExprError();
1674
Douglas Gregor171c45a2009-02-18 21:56:37 +00001675 // Determine whether this name might be a candidate for
1676 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001677 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001678
John McCalle66edc12009-11-24 19:00:30 +00001679 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001680 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001681 // in C90, extension in C99, forbidden in C++).
1682 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1683 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1684 if (D) R.addDecl(D);
1685 }
1686
1687 // If this name wasn't predeclared and if this is not a function
1688 // call, diagnose the problem.
1689 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001690 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001691 return ExprError();
1692
1693 assert(!R.empty() &&
1694 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001695
1696 // If we found an Objective-C instance variable, let
1697 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001698 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001699 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1700 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001701 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001702 assert(E.isInvalid() || E.get());
1703 return move(E);
1704 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001705 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
John McCalle66edc12009-11-24 19:00:30 +00001708 // This is guaranteed from this point on.
1709 assert(!R.empty() || ADL);
1710
John McCall2d74de92009-12-01 22:10:20 +00001711 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001712 // C++ [class.mfct.non-static]p3:
1713 // When an id-expression that is not part of a class member access
1714 // syntax and not used to form a pointer to member is used in the
1715 // body of a non-static member function of class X, if name lookup
1716 // resolves the name in the id-expression to a non-static non-type
1717 // member of some class C, the id-expression is transformed into a
1718 // class member access expression using (*this) as the
1719 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001720 //
1721 // But we don't actually need to do this for '&' operands if R
1722 // resolved to a function or overloaded function set, because the
1723 // expression is ill-formed if it actually works out to be a
1724 // non-static member function:
1725 //
1726 // C++ [expr.ref]p4:
1727 // Otherwise, if E1.E2 refers to a non-static member function. . .
1728 // [t]he expression can be used only as the left-hand operand of a
1729 // member function call.
1730 //
1731 // There are other safeguards against such uses, but it's important
1732 // to get this right here so that we don't end up making a
1733 // spuriously dependent expression if we're inside a dependent
1734 // instance method.
John McCall57500772009-12-16 12:17:52 +00001735 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001736 bool MightBeImplicitMember;
1737 if (!isAddressOfOperand)
1738 MightBeImplicitMember = true;
1739 else if (!SS.isEmpty())
1740 MightBeImplicitMember = false;
1741 else if (R.isOverloadedResult())
1742 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001743 else if (R.isUnresolvableResult())
1744 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001745 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001746 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1747 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001748
1749 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001750 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001751 }
1752
John McCalle66edc12009-11-24 19:00:30 +00001753 if (TemplateArgs)
1754 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001755
John McCalle66edc12009-11-24 19:00:30 +00001756 return BuildDeclarationNameExpr(SS, R, ADL);
1757}
1758
John McCall57500772009-12-16 12:17:52 +00001759/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001760ExprResult
John McCall57500772009-12-16 12:17:52 +00001761Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1762 LookupResult &R,
1763 const TemplateArgumentListInfo *TemplateArgs) {
1764 switch (ClassifyImplicitMemberAccess(*this, R)) {
1765 case IMA_Instance:
1766 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1767
John McCall57500772009-12-16 12:17:52 +00001768 case IMA_Mixed:
1769 case IMA_Mixed_Unrelated:
1770 case IMA_Unresolved:
1771 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1772
1773 case IMA_Static:
1774 case IMA_Mixed_StaticContext:
1775 case IMA_Unresolved_StaticContext:
1776 if (TemplateArgs)
1777 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1778 return BuildDeclarationNameExpr(SS, R, false);
1779
1780 case IMA_Error_StaticContext:
1781 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001782 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1783 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001784 return ExprError();
1785 }
1786
1787 llvm_unreachable("unexpected instance member access kind");
1788 return ExprError();
1789}
1790
John McCall10eae182009-11-30 22:42:35 +00001791/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1792/// declaration name, generally during template instantiation.
1793/// There's a large number of things which don't need to be done along
1794/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001795ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001796Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001797 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001798 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001799 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001800 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001801
John McCall0b66eb32010-05-01 00:40:08 +00001802 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001803 return ExprError();
1804
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001805 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001806 LookupQualifiedName(R, DC);
1807
1808 if (R.isAmbiguous())
1809 return ExprError();
1810
1811 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001812 Diag(NameInfo.getLoc(), diag::err_no_member)
1813 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001814 return ExprError();
1815 }
1816
1817 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1818}
1819
1820/// LookupInObjCMethod - The parser has read a name in, and Sema has
1821/// detected that we're currently inside an ObjC method. Perform some
1822/// additional lookup.
1823///
1824/// Ideally, most of this would be done by lookup, but there's
1825/// actually quite a lot of extra work involved.
1826///
1827/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001828ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001829Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001830 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001831 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001832 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001833
John McCalle66edc12009-11-24 19:00:30 +00001834 // There are two cases to handle here. 1) scoped lookup could have failed,
1835 // in which case we should look for an ivar. 2) scoped lookup could have
1836 // found a decl, but that decl is outside the current instance method (i.e.
1837 // a global variable). In these two cases, we do a lookup for an ivar with
1838 // this name, if the lookup sucedes, we replace it our current decl.
1839
1840 // If we're in a class method, we don't normally want to look for
1841 // ivars. But if we don't find anything else, and there's an
1842 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001843 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001844
1845 bool LookForIvars;
1846 if (Lookup.empty())
1847 LookForIvars = true;
1848 else if (IsClassMethod)
1849 LookForIvars = false;
1850 else
1851 LookForIvars = (Lookup.isSingleResult() &&
1852 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001853 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001854 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001855 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001856 ObjCInterfaceDecl *ClassDeclared;
1857 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1858 // Diagnose using an ivar in a class method.
1859 if (IsClassMethod)
1860 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1861 << IV->getDeclName());
1862
1863 // If we're referencing an invalid decl, just return this as a silent
1864 // error node. The error diagnostic was already emitted on the decl.
1865 if (IV->isInvalidDecl())
1866 return ExprError();
1867
1868 // Check if referencing a field with __attribute__((deprecated)).
1869 if (DiagnoseUseOfDecl(IV, Loc))
1870 return ExprError();
1871
1872 // Diagnose the use of an ivar outside of the declaring class.
1873 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1874 ClassDeclared != IFace)
1875 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1876
1877 // FIXME: This should use a new expr for a direct reference, don't
1878 // turn this into Self->ivar, just return a BareIVarExpr or something.
1879 IdentifierInfo &II = Context.Idents.get("self");
1880 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001881 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001882 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001883 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001884 SelfName, false, false);
1885 if (SelfExpr.isInvalid())
1886 return ExprError();
1887
John McCall27584242010-12-06 20:48:59 +00001888 Expr *SelfE = SelfExpr.take();
1889 DefaultLvalueConversion(SelfE);
1890
John McCalle66edc12009-11-24 19:00:30 +00001891 MarkDeclarationReferenced(Loc, IV);
1892 return Owned(new (Context)
1893 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001894 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001895 }
Chris Lattner87313662010-04-12 05:10:17 +00001896 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001897 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001898 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001899 ObjCInterfaceDecl *ClassDeclared;
1900 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1901 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1902 IFace == ClassDeclared)
1903 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1904 }
1905 }
1906
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001907 if (Lookup.empty() && II && AllowBuiltinCreation) {
1908 // FIXME. Consolidate this with similar code in LookupName.
1909 if (unsigned BuiltinID = II->getBuiltinID()) {
1910 if (!(getLangOptions().CPlusPlus &&
1911 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1912 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1913 S, Lookup.isForRedeclaration(),
1914 Lookup.getNameLoc());
1915 if (D) Lookup.addDecl(D);
1916 }
1917 }
1918 }
John McCalle66edc12009-11-24 19:00:30 +00001919 // Sentinel value saying that we didn't do anything special.
1920 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001921}
John McCalld14a8642009-11-21 08:51:07 +00001922
John McCall16df1e52010-03-30 21:47:33 +00001923/// \brief Cast a base object to a member's actual type.
1924///
1925/// Logically this happens in three phases:
1926///
1927/// * First we cast from the base type to the naming class.
1928/// The naming class is the class into which we were looking
1929/// when we found the member; it's the qualifier type if a
1930/// qualifier was provided, and otherwise it's the base type.
1931///
1932/// * Next we cast from the naming class to the declaring class.
1933/// If the member we found was brought into a class's scope by
1934/// a using declaration, this is that class; otherwise it's
1935/// the class declaring the member.
1936///
1937/// * Finally we cast from the declaring class to the "true"
1938/// declaring class of the member. This conversion does not
1939/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001940bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941Sema::PerformObjectMemberConversion(Expr *&From,
1942 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001943 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 NamedDecl *Member) {
1945 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1946 if (!RD)
1947 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001948
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001949 QualType DestRecordType;
1950 QualType DestType;
1951 QualType FromRecordType;
1952 QualType FromType = From->getType();
1953 bool PointerConversions = false;
1954 if (isa<FieldDecl>(Member)) {
1955 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001957 if (FromType->getAs<PointerType>()) {
1958 DestType = Context.getPointerType(DestRecordType);
1959 FromRecordType = FromType->getPointeeType();
1960 PointerConversions = true;
1961 } else {
1962 DestType = DestRecordType;
1963 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001964 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1966 if (Method->isStatic())
1967 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001968
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001969 DestType = Method->getThisType(Context);
1970 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 if (FromType->getAs<PointerType>()) {
1973 FromRecordType = FromType->getPointeeType();
1974 PointerConversions = true;
1975 } else {
1976 FromRecordType = FromType;
1977 DestType = DestRecordType;
1978 }
1979 } else {
1980 // No conversion necessary.
1981 return false;
1982 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001984 if (DestType->isDependentType() || FromType->isDependentType())
1985 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001986
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001987 // If the unqualified types are the same, no conversion is necessary.
1988 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1989 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001990
John McCall16df1e52010-03-30 21:47:33 +00001991 SourceRange FromRange = From->getSourceRange();
1992 SourceLocation FromLoc = FromRange.getBegin();
1993
John McCall2536c6d2010-08-25 10:28:54 +00001994 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001995
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001996 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001997 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 // class name.
1999 //
2000 // If the member was a qualified name and the qualified referred to a
2001 // specific base subobject type, we'll cast to that intermediate type
2002 // first and then to the object in which the member is declared. That allows
2003 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2004 //
2005 // class Base { public: int x; };
2006 // class Derived1 : public Base { };
2007 // class Derived2 : public Base { };
2008 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2009 //
2010 // void VeryDerived::f() {
2011 // x = 17; // error: ambiguous base subobjects
2012 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2013 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002015 QualType QType = QualType(Qualifier->getAsType(), 0);
2016 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2017 assert(QType->isRecordType() && "lookup done with non-record type");
2018
2019 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2020
2021 // In C++98, the qualifier type doesn't actually have to be a base
2022 // type of the object type, in which case we just ignore it.
2023 // Otherwise build the appropriate casts.
2024 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002025 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002026 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002027 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002028 return true;
2029
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002030 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002031 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002032 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2033 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002034
2035 FromType = QType;
2036 FromRecordType = QRecordType;
2037
2038 // If the qualifier type was the same as the destination type,
2039 // we're done.
2040 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2041 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002042 }
2043 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002044
John McCall16df1e52010-03-30 21:47:33 +00002045 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002046
John McCall16df1e52010-03-30 21:47:33 +00002047 // If we actually found the member through a using declaration, cast
2048 // down to the using declaration's type.
2049 //
2050 // Pointer equality is fine here because only one declaration of a
2051 // class ever has member declarations.
2052 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2053 assert(isa<UsingShadowDecl>(FoundDecl));
2054 QualType URecordType = Context.getTypeDeclType(
2055 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2056
2057 // We only need to do this if the naming-class to declaring-class
2058 // conversion is non-trivial.
2059 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2060 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002061 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002062 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002063 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002064 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002065
John McCall16df1e52010-03-30 21:47:33 +00002066 QualType UType = URecordType;
2067 if (PointerConversions)
2068 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002069 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002070 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002071 FromType = UType;
2072 FromRecordType = URecordType;
2073 }
2074
2075 // We don't do access control for the conversion from the
2076 // declaring class to the true declaring class.
2077 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002078 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002079
John McCallcf142162010-08-07 06:22:56 +00002080 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002081 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2082 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002083 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002084 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002085
John McCalle3027922010-08-25 11:45:40 +00002086 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002087 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002088 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002089}
Douglas Gregor3256d042009-06-30 15:47:41 +00002090
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002091/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002092static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002093 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002094 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002095 const DeclarationNameInfo &MemberNameInfo,
2096 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002097 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002098 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002099 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002100 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002101 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002102}
2103
John McCallfeb624a2010-11-23 20:48:44 +00002104static ExprResult
2105BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2106 const CXXScopeSpec &SS, FieldDecl *Field,
2107 DeclAccessPair FoundDecl,
2108 const DeclarationNameInfo &MemberNameInfo) {
2109 // x.a is an l-value if 'a' has a reference type. Otherwise:
2110 // x.a is an l-value/x-value/pr-value if the base is (and note
2111 // that *x is always an l-value), except that if the base isn't
2112 // an ordinary object then we must have an rvalue.
2113 ExprValueKind VK = VK_LValue;
2114 ExprObjectKind OK = OK_Ordinary;
2115 if (!IsArrow) {
2116 if (BaseExpr->getObjectKind() == OK_Ordinary)
2117 VK = BaseExpr->getValueKind();
2118 else
2119 VK = VK_RValue;
2120 }
2121 if (VK != VK_RValue && Field->isBitField())
2122 OK = OK_BitField;
2123
2124 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2125 QualType MemberType = Field->getType();
2126 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2127 MemberType = Ref->getPointeeType();
2128 VK = VK_LValue;
2129 } else {
2130 QualType BaseType = BaseExpr->getType();
2131 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2132
2133 Qualifiers BaseQuals = BaseType.getQualifiers();
2134
2135 // GC attributes are never picked up by members.
2136 BaseQuals.removeObjCGCAttr();
2137
2138 // CVR attributes from the base are picked up by members,
2139 // except that 'mutable' members don't pick up 'const'.
2140 if (Field->isMutable()) BaseQuals.removeConst();
2141
2142 Qualifiers MemberQuals
2143 = S.Context.getCanonicalType(MemberType).getQualifiers();
2144
2145 // TR 18037 does not allow fields to be declared with address spaces.
2146 assert(!MemberQuals.hasAddressSpace());
2147
2148 Qualifiers Combined = BaseQuals + MemberQuals;
2149 if (Combined != MemberQuals)
2150 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2151 }
2152
2153 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2154 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2155 FoundDecl, Field))
2156 return ExprError();
2157 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2158 Field, FoundDecl, MemberNameInfo,
2159 MemberType, VK, OK));
2160}
2161
John McCall2d74de92009-12-01 22:10:20 +00002162/// Builds an implicit member access expression. The current context
2163/// is known to be an instance method, and the given unqualified lookup
2164/// set is known to contain only instance members, at least one of which
2165/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002166ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002167Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2168 LookupResult &R,
2169 const TemplateArgumentListInfo *TemplateArgs,
2170 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002171 assert(!R.empty() && !R.isAmbiguous());
2172
John McCallf3a88602011-02-03 08:15:49 +00002173 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002174
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002175 // We may have found a field within an anonymous union or struct
2176 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002177 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002178 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002179 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002180
John McCallf3a88602011-02-03 08:15:49 +00002181 // If this is known to be an instance access, go ahead and build an
2182 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002183 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002184 CXXMethodDecl *method = tryCaptureCXXThis();
2185 assert(method && "didn't correctly pre-flight capture of 'this'");
2186
2187 QualType thisType = method->getThisType(Context);
2188 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002189 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002190 SourceLocation Loc = R.getNameLoc();
2191 if (SS.getRange().isValid())
2192 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002193 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002194 }
2195
John McCallf3a88602011-02-03 08:15:49 +00002196 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002197 /*OpLoc*/ SourceLocation(),
2198 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002199 SS,
2200 /*FirstQualifierInScope*/ 0,
2201 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002202}
2203
John McCalle66edc12009-11-24 19:00:30 +00002204bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002205 const LookupResult &R,
2206 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002207 // Only when used directly as the postfix-expression of a call.
2208 if (!HasTrailingLParen)
2209 return false;
2210
2211 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002212 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002213 return false;
2214
2215 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002216 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002217 return false;
2218
2219 // Turn off ADL when we find certain kinds of declarations during
2220 // normal lookup:
2221 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2222 NamedDecl *D = *I;
2223
2224 // C++0x [basic.lookup.argdep]p3:
2225 // -- a declaration of a class member
2226 // Since using decls preserve this property, we check this on the
2227 // original decl.
John McCall57500772009-12-16 12:17:52 +00002228 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002229 return false;
2230
2231 // C++0x [basic.lookup.argdep]p3:
2232 // -- a block-scope function declaration that is not a
2233 // using-declaration
2234 // NOTE: we also trigger this for function templates (in fact, we
2235 // don't check the decl type at all, since all other decl types
2236 // turn off ADL anyway).
2237 if (isa<UsingShadowDecl>(D))
2238 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2239 else if (D->getDeclContext()->isFunctionOrMethod())
2240 return false;
2241
2242 // C++0x [basic.lookup.argdep]p3:
2243 // -- a declaration that is neither a function or a function
2244 // template
2245 // And also for builtin functions.
2246 if (isa<FunctionDecl>(D)) {
2247 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2248
2249 // But also builtin functions.
2250 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2251 return false;
2252 } else if (!isa<FunctionTemplateDecl>(D))
2253 return false;
2254 }
2255
2256 return true;
2257}
2258
2259
John McCalld14a8642009-11-21 08:51:07 +00002260/// Diagnoses obvious problems with the use of the given declaration
2261/// as an expression. This is only actually called for lookups that
2262/// were not overloaded, and it doesn't promise that the declaration
2263/// will in fact be used.
2264static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2265 if (isa<TypedefDecl>(D)) {
2266 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2267 return true;
2268 }
2269
2270 if (isa<ObjCInterfaceDecl>(D)) {
2271 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2272 return true;
2273 }
2274
2275 if (isa<NamespaceDecl>(D)) {
2276 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2277 return true;
2278 }
2279
2280 return false;
2281}
2282
John McCalldadc5752010-08-24 06:29:42 +00002283ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002284Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002285 LookupResult &R,
2286 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002287 // If this is a single, fully-resolved result and we don't need ADL,
2288 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002289 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002290 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2291 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002292
2293 // We only need to check the declaration if there's exactly one
2294 // result, because in the overloaded case the results can only be
2295 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002296 if (R.isSingleResult() &&
2297 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002298 return ExprError();
2299
John McCall58cc69d2010-01-27 01:50:18 +00002300 // Otherwise, just build an unresolved lookup expression. Suppress
2301 // any lookup-related diagnostics; we'll hash these out later, when
2302 // we've picked a target.
2303 R.suppressDiagnostics();
2304
John McCalld14a8642009-11-21 08:51:07 +00002305 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002306 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002307 SS.getWithLocInContext(Context),
2308 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002309 NeedsADL, R.isOverloadedResult(),
2310 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002311
2312 return Owned(ULE);
2313}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002314
John McCalld14a8642009-11-21 08:51:07 +00002315/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002316ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002317Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002318 const DeclarationNameInfo &NameInfo,
2319 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002320 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002321 assert(!isa<FunctionTemplateDecl>(D) &&
2322 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002323
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002324 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002325 if (CheckDeclInExpr(*this, Loc, D))
2326 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002327
Douglas Gregore7488b92009-12-01 16:58:18 +00002328 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2329 // Specifically diagnose references to class templates that are missing
2330 // a template argument list.
2331 Diag(Loc, diag::err_template_decl_ref)
2332 << Template << SS.getRange();
2333 Diag(Template->getLocation(), diag::note_template_decl_here);
2334 return ExprError();
2335 }
2336
2337 // Make sure that we're referring to a value.
2338 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2339 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002340 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002341 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002342 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002343 return ExprError();
2344 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002345
Douglas Gregor171c45a2009-02-18 21:56:37 +00002346 // Check whether this declaration can be used. Note that we suppress
2347 // this check when we're going to perform argument-dependent lookup
2348 // on this function name, because this might not be the function
2349 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002350 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002351 return ExprError();
2352
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002353 // Only create DeclRefExpr's for valid Decl's.
2354 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002355 return ExprError();
2356
John McCallf3a88602011-02-03 08:15:49 +00002357 // Handle members of anonymous structs and unions. If we got here,
2358 // and the reference is to a class member indirect field, then this
2359 // must be the subject of a pointer-to-member expression.
2360 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2361 if (!indirectField->isCXXClassMember())
2362 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2363 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002364
Chris Lattner2a9d9892008-10-20 05:16:36 +00002365 // If the identifier reference is inside a block, and it refers to a value
2366 // that is outside the block, create a BlockDeclRefExpr instead of a
2367 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2368 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002369 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002370 // We do not do this for things like enum constants, global variables, etc,
2371 // as they do not get snapshotted.
2372 //
John McCall351762c2011-02-07 10:33:21 +00002373 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002374 case CR_Error:
2375 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002376
John McCallc63de662011-02-02 13:00:07 +00002377 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002378 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2379 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2380
2381 case CR_CaptureByRef:
2382 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2383 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002384
2385 case CR_NoCapture: {
2386 // If this reference is not in a block or if the referenced
2387 // variable is within the block, create a normal DeclRefExpr.
2388
2389 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002390 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002391
2392 switch (D->getKind()) {
2393 // Ignore all the non-ValueDecl kinds.
2394#define ABSTRACT_DECL(kind)
2395#define VALUE(type, base)
2396#define DECL(type, base) \
2397 case Decl::type:
2398#include "clang/AST/DeclNodes.inc"
2399 llvm_unreachable("invalid value decl kind");
2400 return ExprError();
2401
2402 // These shouldn't make it here.
2403 case Decl::ObjCAtDefsField:
2404 case Decl::ObjCIvar:
2405 llvm_unreachable("forming non-member reference to ivar?");
2406 return ExprError();
2407
2408 // Enum constants are always r-values and never references.
2409 // Unresolved using declarations are dependent.
2410 case Decl::EnumConstant:
2411 case Decl::UnresolvedUsingValue:
2412 valueKind = VK_RValue;
2413 break;
2414
2415 // Fields and indirect fields that got here must be for
2416 // pointer-to-member expressions; we just call them l-values for
2417 // internal consistency, because this subexpression doesn't really
2418 // exist in the high-level semantics.
2419 case Decl::Field:
2420 case Decl::IndirectField:
2421 assert(getLangOptions().CPlusPlus &&
2422 "building reference to field in C?");
2423
2424 // These can't have reference type in well-formed programs, but
2425 // for internal consistency we do this anyway.
2426 type = type.getNonReferenceType();
2427 valueKind = VK_LValue;
2428 break;
2429
2430 // Non-type template parameters are either l-values or r-values
2431 // depending on the type.
2432 case Decl::NonTypeTemplateParm: {
2433 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2434 type = reftype->getPointeeType();
2435 valueKind = VK_LValue; // even if the parameter is an r-value reference
2436 break;
2437 }
2438
2439 // For non-references, we need to strip qualifiers just in case
2440 // the template parameter was declared as 'const int' or whatever.
2441 valueKind = VK_RValue;
2442 type = type.getUnqualifiedType();
2443 break;
2444 }
2445
2446 case Decl::Var:
2447 // In C, "extern void blah;" is valid and is an r-value.
2448 if (!getLangOptions().CPlusPlus &&
2449 !type.hasQualifiers() &&
2450 type->isVoidType()) {
2451 valueKind = VK_RValue;
2452 break;
2453 }
2454 // fallthrough
2455
2456 case Decl::ImplicitParam:
2457 case Decl::ParmVar:
2458 // These are always l-values.
2459 valueKind = VK_LValue;
2460 type = type.getNonReferenceType();
2461 break;
2462
2463 case Decl::Function: {
2464 // Functions are l-values in C++.
2465 if (getLangOptions().CPlusPlus) {
2466 valueKind = VK_LValue;
2467 break;
2468 }
2469
2470 // C99 DR 316 says that, if a function type comes from a
2471 // function definition (without a prototype), that type is only
2472 // used for checking compatibility. Therefore, when referencing
2473 // the function, we pretend that we don't have the full function
2474 // type.
2475 if (!cast<FunctionDecl>(VD)->hasPrototype())
2476 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2477 type = Context.getFunctionNoProtoType(proto->getResultType(),
2478 proto->getExtInfo());
2479
2480 // Functions are r-values in C.
2481 valueKind = VK_RValue;
2482 break;
2483 }
2484
2485 case Decl::CXXMethod:
2486 // C++ methods are l-values if static, r-values if non-static.
2487 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2488 valueKind = VK_LValue;
2489 break;
2490 }
2491 // fallthrough
2492
2493 case Decl::CXXConversion:
2494 case Decl::CXXDestructor:
2495 case Decl::CXXConstructor:
2496 valueKind = VK_RValue;
2497 break;
2498 }
2499
2500 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2501 }
2502
John McCallc63de662011-02-02 13:00:07 +00002503 }
John McCall7decc9e2010-11-18 06:31:45 +00002504
John McCall351762c2011-02-07 10:33:21 +00002505 llvm_unreachable("unknown capture result");
2506 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002507}
Chris Lattnere168f762006-11-10 05:29:30 +00002508
John McCalldadc5752010-08-24 06:29:42 +00002509ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002510 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002511 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512
Chris Lattnere168f762006-11-10 05:29:30 +00002513 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002514 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002515 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2516 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2517 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002518 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002519
Chris Lattnera81a0272008-01-12 08:14:25 +00002520 // Pre-defined identifiers are of type char[x], where x is the length of the
2521 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002522
Anders Carlsson2fb08242009-09-08 18:24:21 +00002523 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002524 if (!currentDecl && getCurBlock())
2525 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002526 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002527 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002528 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002529 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530
Anders Carlsson0b209a82009-09-11 01:22:35 +00002531 QualType ResTy;
2532 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2533 ResTy = Context.DependentTy;
2534 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002535 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Anders Carlsson0b209a82009-09-11 01:22:35 +00002537 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002538 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002539 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2540 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002541 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002542}
2543
John McCalldadc5752010-08-24 06:29:42 +00002544ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002545 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002546 bool Invalid = false;
2547 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2548 if (Invalid)
2549 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002551 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2552 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002553 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002554 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002555
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002556 QualType Ty;
2557 if (!getLangOptions().CPlusPlus)
2558 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2559 else if (Literal.isWide())
2560 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002561 else if (Literal.isMultiChar())
2562 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002563 else
2564 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002565
Sebastian Redl20614a72009-01-20 22:23:13 +00002566 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2567 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002568 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002569}
2570
John McCalldadc5752010-08-24 06:29:42 +00002571ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002572 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002573 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2574 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002575 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002576 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002577 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002578 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002579 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002580
Chris Lattner23b7eb62007-06-15 23:05:46 +00002581 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002582 // Add padding so that NumericLiteralParser can overread by one character.
2583 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002584 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002585
Chris Lattner67ca9252007-05-21 01:08:44 +00002586 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002587 bool Invalid = false;
2588 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2589 if (Invalid)
2590 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002591
Mike Stump11289f42009-09-09 15:08:12 +00002592 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002593 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002594 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002595 return ExprError();
2596
Chris Lattner1c20a172007-08-26 03:42:43 +00002597 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002598
Chris Lattner1c20a172007-08-26 03:42:43 +00002599 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002600 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002601 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002602 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002603 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002604 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002605 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002606 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002607
2608 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2609
John McCall53b93a02009-12-24 09:08:04 +00002610 using llvm::APFloat;
2611 APFloat Val(Format);
2612
2613 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002614
2615 // Overflow is always an error, but underflow is only an error if
2616 // we underflowed to zero (APFloat reports denormals as underflow).
2617 if ((result & APFloat::opOverflow) ||
2618 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002619 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002620 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002621 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002622 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002623 APFloat::getLargest(Format).toString(buffer);
2624 } else {
John McCall62abc942010-02-26 23:35:57 +00002625 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002626 APFloat::getSmallest(Format).toString(buffer);
2627 }
2628
2629 Diag(Tok.getLocation(), diagnostic)
2630 << Ty
2631 << llvm::StringRef(buffer.data(), buffer.size());
2632 }
2633
2634 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002635 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002636
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002637 if (Ty == Context.DoubleTy) {
2638 if (getLangOptions().SinglePrecisionConstants) {
2639 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2640 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2641 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2642 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2643 }
2644 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002645 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002646 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002647 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002648 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002649
Neil Boothac582c52007-08-29 22:00:19 +00002650 // long long is a C99 feature.
2651 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002652 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002653 Diag(Tok.getLocation(), diag::ext_longlong);
2654
Chris Lattner67ca9252007-05-21 01:08:44 +00002655 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002656 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002657
Chris Lattner67ca9252007-05-21 01:08:44 +00002658 if (Literal.GetIntegerValue(ResultVal)) {
2659 // If this value didn't fit into uintmax_t, warn and force to ull.
2660 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002661 Ty = Context.UnsignedLongLongTy;
2662 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002663 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002664 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 // If this value fits into a ULL, try to figure out what else it fits into
2666 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002667
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2669 // be an unsigned int.
2670 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2671
2672 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002673 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002674 if (!Literal.isLong && !Literal.isLongLong) {
2675 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002676 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // Does it fit in a unsigned int?
2679 if (ResultVal.isIntN(IntSize)) {
2680 // Does it fit in a signed int?
2681 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002690 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002691 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 // Does it fit in a unsigned long?
2694 if (ResultVal.isIntN(LongSize)) {
2695 // Does it fit in a signed long?
2696 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002697 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002698 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002699 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702 }
2703
Chris Lattner67ca9252007-05-21 01:08:44 +00002704 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002705 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002706 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002707
Chris Lattner67ca9252007-05-21 01:08:44 +00002708 // Does it fit in a unsigned long long?
2709 if (ResultVal.isIntN(LongLongSize)) {
2710 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002711 // To be compatible with MSVC, hex integer literals ending with the
2712 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002713 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2714 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002715 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002719 }
2720 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002721
Chris Lattner67ca9252007-05-21 01:08:44 +00002722 // If we still couldn't decide a type, we probably have something that
2723 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002724 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002725 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002726 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002727 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002728 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002729
Chris Lattner55258cf2008-05-09 05:59:00 +00002730 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002731 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002732 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002733 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002734 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002735
Chris Lattner1c20a172007-08-26 03:42:43 +00002736 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2737 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002738 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002739 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002740
2741 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002742}
2743
John McCalldadc5752010-08-24 06:29:42 +00002744ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002745 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002746 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002747 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002748}
2749
Steve Naroff71b59a92007-06-04 22:22:31 +00002750/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002751/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002752bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2753 SourceLocation OpLoc,
2754 SourceRange ExprRange,
2755 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002756 if (exprType->isDependentType())
2757 return false;
2758
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002759 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2760 // the result is the size of the referenced type."
2761 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2762 // result shall be the alignment of the referenced type."
2763 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2764 exprType = Ref->getPointeeType();
2765
Peter Collingbournee190dee2011-03-11 19:24:49 +00002766 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2767 // scalar or vector data type argument..."
2768 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2769 // type (C99 6.2.5p18) or void.
2770 if (ExprKind == UETT_VecStep) {
2771 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2772 exprType->isVectorType())) {
2773 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2774 << exprType << ExprRange;
2775 return true;
2776 }
2777 }
2778
Steve Naroff043d45d2007-05-15 02:32:35 +00002779 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002780 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002781 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002782 if (ExprKind == UETT_SizeOf)
2783 Diag(OpLoc, diag::ext_sizeof_function_type)
2784 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002785 return false;
2786 }
Mike Stump11289f42009-09-09 15:08:12 +00002787
Peter Collingbournee190dee2011-03-11 19:24:49 +00002788 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2789 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002790 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002791 if (ExprKind != UETT_VecStep)
2792 Diag(OpLoc, diag::ext_sizeof_void_type)
2793 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002794 return false;
2795 }
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner62975a72009-04-24 00:30:45 +00002797 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002798 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002799 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002800 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002801
Chris Lattner62975a72009-04-24 00:30:45 +00002802 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002803 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002804 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002805 << exprType << (ExprKind == UETT_SizeOf)
2806 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002807 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattner62975a72009-04-24 00:30:45 +00002810 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002811}
2812
John McCall36e7fe32010-10-12 00:20:44 +00002813static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2814 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002815 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002816
Mike Stump11289f42009-09-09 15:08:12 +00002817 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002818 if (isa<DeclRefExpr>(E))
2819 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002820
2821 // Cannot know anything else if the expression is dependent.
2822 if (E->isTypeDependent())
2823 return false;
2824
Douglas Gregor71235ec2009-05-02 02:18:30 +00002825 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002826 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002827 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002828 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002829
2830 // Alignment of a field access is always okay, so long as it isn't a
2831 // bit-field.
2832 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002833 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002834 return false;
2835
Peter Collingbournee190dee2011-03-11 19:24:49 +00002836 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2837 UETT_AlignOf);
2838}
2839
2840bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2841 SourceRange ExprRange) {
2842 E = E->IgnoreParens();
2843
2844 // Cannot know anything else if the expression is dependent.
2845 if (E->isTypeDependent())
2846 return false;
2847
2848 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2849 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002850}
2851
Douglas Gregor0950e412009-03-13 21:01:28 +00002852/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002853ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002854Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2855 SourceLocation OpLoc,
2856 UnaryExprOrTypeTrait ExprKind,
2857 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002858 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002859 return ExprError();
2860
John McCallbcd03502009-12-07 02:54:59 +00002861 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002862
Douglas Gregor0950e412009-03-13 21:01:28 +00002863 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002864 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002865 return ExprError();
2866
2867 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002868 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2869 Context.getSizeType(),
2870 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002871}
2872
2873/// \brief Build a sizeof or alignof expression given an expression
2874/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002875ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002876Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2877 UnaryExprOrTypeTrait ExprKind,
2878 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002879 // Verify that the operand is valid.
2880 bool isInvalid = false;
2881 if (E->isTypeDependent()) {
2882 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002883 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002884 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002885 } else if (ExprKind == UETT_VecStep) {
2886 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002887 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002888 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2889 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002890 } else if (E->getType()->isPlaceholderType()) {
2891 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2892 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002894 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002895 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2896 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002897 }
2898
2899 if (isInvalid)
2900 return ExprError();
2901
2902 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002903 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2904 Context.getSizeType(),
2905 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002906}
2907
Peter Collingbournee190dee2011-03-11 19:24:49 +00002908/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2909/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002910/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002911ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002912Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2913 UnaryExprOrTypeTrait ExprKind, bool isType,
2914 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002915 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002916 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002917
Sebastian Redl6f282892008-11-11 17:56:53 +00002918 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002919 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002920 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002921 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002922 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002923
Douglas Gregor0950e412009-03-13 21:01:28 +00002924 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002925 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002926 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2927 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002928
Douglas Gregor0950e412009-03-13 21:01:28 +00002929 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002930}
2931
John McCall4bc41ae2010-11-18 19:01:18 +00002932static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2933 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002934 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002935 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002936
John McCall34376a62010-12-04 03:47:34 +00002937 // _Real and _Imag are only l-values for normal l-values.
2938 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002939 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002940
Chris Lattnere267f5d2007-08-26 05:39:26 +00002941 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002942 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002943 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002944
Chris Lattnere267f5d2007-08-26 05:39:26 +00002945 // Otherwise they pass through real integer and floating point types here.
2946 if (V->getType()->isArithmeticType())
2947 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002948
John McCall36226622010-10-12 02:09:17 +00002949 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002950 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002951 if (PR.isInvalid()) return QualType();
2952 if (PR.take() != V) {
2953 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002954 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002955 }
2956
Chris Lattnere267f5d2007-08-26 05:39:26 +00002957 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002958 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002959 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002960 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002961}
2962
2963
Chris Lattnere168f762006-11-10 05:29:30 +00002964
John McCalldadc5752010-08-24 06:29:42 +00002965ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002966Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002967 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002968 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002969 switch (Kind) {
2970 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002971 case tok::plusplus: Opc = UO_PostInc; break;
2972 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002973 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002974
John McCallb268a282010-08-23 23:25:46 +00002975 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002976}
2977
John McCall4bc41ae2010-11-18 19:01:18 +00002978/// Expressions of certain arbitrary types are forbidden by C from
2979/// having l-value type. These are:
2980/// - 'void', but not qualified void
2981/// - function types
2982///
2983/// The exact rule here is C99 6.3.2.1:
2984/// An lvalue is an expression with an object type or an incomplete
2985/// type other than void.
2986static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2987 return ((T->isVoidType() && !T.hasQualifiers()) ||
2988 T->isFunctionType());
2989}
2990
John McCalldadc5752010-08-24 06:29:42 +00002991ExprResult
John McCallb268a282010-08-23 23:25:46 +00002992Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2993 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002994 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002995 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002996 if (Result.isInvalid()) return ExprError();
2997 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002998
John McCallb268a282010-08-23 23:25:46 +00002999 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003000
Douglas Gregor40412ac2008-11-19 17:17:41 +00003001 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003002 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003003 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003004 Context.DependentTy,
3005 VK_LValue, OK_Ordinary,
3006 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003007 }
3008
Mike Stump11289f42009-09-09 15:08:12 +00003009 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003011 LHSExp->getType()->isEnumeralType() ||
3012 RHSExp->getType()->isRecordType() ||
3013 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003014 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003015 }
3016
John McCallb268a282010-08-23 23:25:46 +00003017 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003018}
3019
3020
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
John McCallb268a282010-08-23 23:25:46 +00003022Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3023 Expr *Idx, SourceLocation RLoc) {
3024 Expr *LHSExp = Base;
3025 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003026
Chris Lattner36d572b2007-07-16 00:14:47 +00003027 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00003028 if (!LHSExp->getType()->getAs<VectorType>())
3029 DefaultFunctionArrayLvalueConversion(LHSExp);
3030 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003031
Chris Lattner36d572b2007-07-16 00:14:47 +00003032 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003033 ExprValueKind VK = VK_LValue;
3034 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003035
Steve Naroffc1aadb12007-03-28 21:49:40 +00003036 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003037 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003038 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003039 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003040 Expr *BaseExpr, *IndexExpr;
3041 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003042 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3043 BaseExpr = LHSExp;
3044 IndexExpr = RHSExp;
3045 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003046 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003047 BaseExpr = LHSExp;
3048 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003049 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003050 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003051 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003052 BaseExpr = RHSExp;
3053 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003054 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003055 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003056 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003057 BaseExpr = LHSExp;
3058 IndexExpr = RHSExp;
3059 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003060 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003061 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003062 // Handle the uncommon case of "123[Ptr]".
3063 BaseExpr = RHSExp;
3064 IndexExpr = LHSExp;
3065 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003066 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003067 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003068 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003069 VK = LHSExp->getValueKind();
3070 if (VK != VK_RValue)
3071 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003072
Chris Lattner36d572b2007-07-16 00:14:47 +00003073 // FIXME: need to deal with const...
3074 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003075 } else if (LHSTy->isArrayType()) {
3076 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003077 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003078 // wasn't promoted because of the C90 rule that doesn't
3079 // allow promoting non-lvalue arrays. Warn, then
3080 // force the promotion here.
3081 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3082 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003083 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003084 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003085 LHSTy = LHSExp->getType();
3086
3087 BaseExpr = LHSExp;
3088 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003089 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003090 } else if (RHSTy->isArrayType()) {
3091 // Same as previous, except for 123[f().a] case
3092 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3093 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003094 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003095 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003096 RHSTy = RHSExp->getType();
3097
3098 BaseExpr = RHSExp;
3099 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003100 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003101 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003102 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3103 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003104 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003105 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003106 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003107 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3108 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003109
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003110 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003111 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3112 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003113 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3114
Douglas Gregorac1fb652009-03-24 19:52:54 +00003115 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003116 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3117 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003118 // incomplete types are not object types.
3119 if (ResultType->isFunctionType()) {
3120 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3121 << ResultType << BaseExpr->getSourceRange();
3122 return ExprError();
3123 }
Mike Stump11289f42009-09-09 15:08:12 +00003124
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003125 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3126 // GNU extension: subscripting on pointer to void
3127 Diag(LLoc, diag::ext_gnu_void_ptr)
3128 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003129
3130 // C forbids expressions of unqualified void type from being l-values.
3131 // See IsCForbiddenLValueType.
3132 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003133 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003134 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003135 PDiag(diag::err_subscript_incomplete_type)
3136 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003137 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003138
Chris Lattner62975a72009-04-24 00:30:45 +00003139 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003140 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003141 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3142 << ResultType << BaseExpr->getSourceRange();
3143 return ExprError();
3144 }
Mike Stump11289f42009-09-09 15:08:12 +00003145
John McCall4bc41ae2010-11-18 19:01:18 +00003146 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3147 !IsCForbiddenLValueType(Context, ResultType));
3148
Mike Stump4e1f26a2009-02-19 03:04:26 +00003149 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003150 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003151}
3152
John McCall4bc41ae2010-11-18 19:01:18 +00003153/// Check an ext-vector component access expression.
3154///
3155/// VK should be set in advance to the value kind of the base
3156/// expression.
3157static QualType
3158CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3159 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003160 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003161 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3162 // see FIXME there.
3163 //
3164 // FIXME: This logic can be greatly simplified by splitting it along
3165 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003166 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003167
Steve Narofff8fd09e2007-07-27 22:15:19 +00003168 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003169 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003170
Mike Stump4e1f26a2009-02-19 03:04:26 +00003171 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003172 // special names that indicate a subset of exactly half the elements are
3173 // to be selected.
3174 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003175
Nate Begemanbb70bf62009-01-18 01:47:54 +00003176 // This flag determines whether or not CompName has an 's' char prefix,
3177 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003178 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003179
John McCall4bc41ae2010-11-18 19:01:18 +00003180 bool HasRepeated = false;
3181 bool HasIndex[16] = {};
3182
3183 int Idx;
3184
Nate Begemanf322eab2008-05-09 06:41:27 +00003185 // Check that we've found one of the special components, or that the component
3186 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003187 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003188 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3189 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003190 } else if (!HexSwizzle &&
3191 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3192 do {
3193 if (HasIndex[Idx]) HasRepeated = true;
3194 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003195 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003196 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3197 } else {
3198 if (HexSwizzle) compStr++;
3199 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3200 if (HasIndex[Idx]) HasRepeated = true;
3201 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003202 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003203 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003204 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003205
Mike Stump4e1f26a2009-02-19 03:04:26 +00003206 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003207 // We didn't get to the end of the string. This means the component names
3208 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003209 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003210 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003211 return QualType();
3212 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003213
Nate Begemanbb70bf62009-01-18 01:47:54 +00003214 // Ensure no component accessor exceeds the width of the vector type it
3215 // operates on.
3216 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003217 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003218
3219 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003220 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003221
3222 while (*compStr) {
3223 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003224 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003225 << baseType << SourceRange(CompLoc);
3226 return QualType();
3227 }
3228 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003229 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003230
Steve Narofff8fd09e2007-07-27 22:15:19 +00003231 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003232 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003233 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003234 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003235 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003236 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003237 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003238 if (HexSwizzle)
3239 CompSize--;
3240
Steve Narofff8fd09e2007-07-27 22:15:19 +00003241 if (CompSize == 1)
3242 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003243
John McCall4bc41ae2010-11-18 19:01:18 +00003244 if (HasRepeated) VK = VK_RValue;
3245
3246 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003247 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003248 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003249 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3250 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3251 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003252 }
3253 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003254}
3255
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003256static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003257 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003258 const Selector &Sel,
3259 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003260 if (Member)
3261 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3262 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003263 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003264 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003265
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003266 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3267 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003268 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3269 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003270 return D;
3271 }
3272 return 0;
3273}
3274
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003275static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3276 IdentifierInfo *Member,
3277 const Selector &Sel,
3278 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003279 // Check protocols on qualified interfaces.
3280 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003281 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003282 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003283 if (Member)
3284 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3285 GDecl = PD;
3286 break;
3287 }
3288 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003289 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003290 GDecl = OMD;
3291 break;
3292 }
3293 }
3294 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003295 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003296 E = QIdTy->qual_end(); I != E; ++I) {
3297 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003298 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3299 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003300 if (GDecl)
3301 return GDecl;
3302 }
3303 }
3304 return GDecl;
3305}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003306
John McCalldadc5752010-08-24 06:29:42 +00003307ExprResult
John McCallb268a282010-08-23 23:25:46 +00003308Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003309 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003310 const CXXScopeSpec &SS,
3311 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003312 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003313 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003314 // Even in dependent contexts, try to diagnose base expressions with
3315 // obviously wrong types, e.g.:
3316 //
3317 // T* t;
3318 // t.f;
3319 //
3320 // In Obj-C++, however, the above expression is valid, since it could be
3321 // accessing the 'f' property if T is an Obj-C interface. The extra check
3322 // allows this, while still reporting an error if T is a struct pointer.
3323 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003324 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003325 if (PT && (!getLangOptions().ObjC1 ||
3326 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003327 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003328 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003329 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003330 return ExprError();
3331 }
3332 }
3333
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003334 assert(BaseType->isDependentType() ||
3335 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003336 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003337
3338 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3339 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003340 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003341 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003342 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003343 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003344 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003345}
3346
3347/// We know that the given qualified member reference points only to
3348/// declarations which do not belong to the static type of the base
3349/// expression. Diagnose the problem.
3350static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3351 Expr *BaseExpr,
3352 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003353 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003354 NamedDecl *rep,
3355 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003356 // If this is an implicit member access, use a different set of
3357 // diagnostics.
3358 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003359 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003360
John McCallf3a88602011-02-03 08:15:49 +00003361 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3362 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003363}
3364
3365// Check whether the declarations we found through a nested-name
3366// specifier in a member expression are actually members of the base
3367// type. The restriction here is:
3368//
3369// C++ [expr.ref]p2:
3370// ... In these cases, the id-expression shall name a
3371// member of the class or of one of its base classes.
3372//
3373// So it's perfectly legitimate for the nested-name specifier to name
3374// an unrelated class, and for us to find an overload set including
3375// decls from classes which are not superclasses, as long as the decl
3376// we actually pick through overload resolution is from a superclass.
3377bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3378 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003379 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003380 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003381 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3382 if (!BaseRT) {
3383 // We can't check this yet because the base type is still
3384 // dependent.
3385 assert(BaseType->isDependentType());
3386 return false;
3387 }
3388 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003389
3390 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003391 // If this is an implicit member reference and we find a
3392 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003393 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003394 return false;
John McCall10eae182009-11-30 22:42:35 +00003395
John McCall2d74de92009-12-01 22:10:20 +00003396 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003397 DeclContext *DC = (*I)->getDeclContext();
3398 while (DC->isTransparentContext())
3399 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003400
Douglas Gregora9c3e822010-07-28 22:27:52 +00003401 if (!DC->isRecord())
3402 continue;
3403
John McCall2d74de92009-12-01 22:10:20 +00003404 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003405 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003406
3407 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3408 return false;
3409 }
3410
John McCallf3a88602011-02-03 08:15:49 +00003411 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3412 R.getRepresentativeDecl(),
3413 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003414 return true;
3415}
3416
3417static bool
3418LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3419 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003420 SourceLocation OpLoc, CXXScopeSpec &SS,
3421 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003422 RecordDecl *RDecl = RTy->getDecl();
3423 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003424 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003425 << BaseRange))
3426 return true;
3427
John McCalle9cccd82010-06-16 08:42:20 +00003428 if (HasTemplateArgs) {
3429 // LookupTemplateName doesn't expect these both to exist simultaneously.
3430 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3431
3432 bool MOUS;
3433 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3434 return false;
3435 }
3436
John McCall2d74de92009-12-01 22:10:20 +00003437 DeclContext *DC = RDecl;
3438 if (SS.isSet()) {
3439 // If the member name was a qualified-id, look into the
3440 // nested-name-specifier.
3441 DC = SemaRef.computeDeclContext(SS, false);
3442
John McCall0b66eb32010-05-01 00:40:08 +00003443 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003444 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3445 << SS.getRange() << DC;
3446 return true;
3447 }
3448
John McCall2d74de92009-12-01 22:10:20 +00003449 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003450
John McCall2d74de92009-12-01 22:10:20 +00003451 if (!isa<TypeDecl>(DC)) {
3452 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3453 << DC << SS.getRange();
3454 return true;
John McCall10eae182009-11-30 22:42:35 +00003455 }
3456 }
3457
John McCall2d74de92009-12-01 22:10:20 +00003458 // The record definition is complete, now look up the member.
3459 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003460
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003461 if (!R.empty())
3462 return false;
3463
3464 // We didn't find anything with the given name, so try to correct
3465 // for typos.
3466 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003467 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003468 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003469 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3470 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3471 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003472 << FixItHint::CreateReplacement(R.getNameLoc(),
3473 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003474 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3475 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3476 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003477 return false;
3478 } else {
3479 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003480 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003481 }
3482
John McCall10eae182009-11-30 22:42:35 +00003483 return false;
3484}
3485
John McCalldadc5752010-08-24 06:29:42 +00003486ExprResult
John McCallb268a282010-08-23 23:25:46 +00003487Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003488 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003489 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003490 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003491 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003492 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003493 if (BaseType->isDependentType() ||
3494 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003495 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003496 IsArrow, OpLoc,
3497 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003498 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003499
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003500 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003501
John McCall2d74de92009-12-01 22:10:20 +00003502 // Implicit member accesses.
3503 if (!Base) {
3504 QualType RecordTy = BaseType;
3505 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3506 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3507 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003508 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003509 return ExprError();
3510
3511 // Explicit member accesses.
3512 } else {
John McCalldadc5752010-08-24 06:29:42 +00003513 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003514 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003515 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003516
3517 if (Result.isInvalid()) {
3518 Owned(Base);
3519 return ExprError();
3520 }
3521
3522 if (Result.get())
3523 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003524
3525 // LookupMemberExpr can modify Base, and thus change BaseType
3526 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003527 }
3528
John McCallb268a282010-08-23 23:25:46 +00003529 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003530 OpLoc, IsArrow, SS, FirstQualifierInScope,
3531 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003532}
3533
John McCalldadc5752010-08-24 06:29:42 +00003534ExprResult
John McCallb268a282010-08-23 23:25:46 +00003535Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003536 SourceLocation OpLoc, bool IsArrow,
3537 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003538 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003539 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003540 const TemplateArgumentListInfo *TemplateArgs,
3541 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003542 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003543 if (IsArrow) {
3544 assert(BaseType->isPointerType());
3545 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3546 }
John McCalla8ae2222010-04-06 21:38:20 +00003547 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003548
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003549 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3550 DeclarationName MemberName = MemberNameInfo.getName();
3551 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003552
3553 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003554 return ExprError();
3555
John McCall10eae182009-11-30 22:42:35 +00003556 if (R.empty()) {
3557 // Rederive where we looked up.
3558 DeclContext *DC = (SS.isSet()
3559 ? computeDeclContext(SS, false)
3560 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003561
John McCall10eae182009-11-30 22:42:35 +00003562 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003563 << MemberName << DC
3564 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003565 return ExprError();
3566 }
3567
John McCall38836f02010-01-15 08:34:02 +00003568 // Diagnose lookups that find only declarations from a non-base
3569 // type. This is possible for either qualified lookups (which may
3570 // have been qualified with an unrelated type) or implicit member
3571 // expressions (which were found with unqualified lookup and thus
3572 // may have come from an enclosing scope). Note that it's okay for
3573 // lookup to find declarations from a non-base type as long as those
3574 // aren't the ones picked by overload resolution.
3575 if ((SS.isSet() || !BaseExpr ||
3576 (isa<CXXThisExpr>(BaseExpr) &&
3577 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003578 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003579 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003580 return ExprError();
3581
3582 // Construct an unresolved result if we in fact got an unresolved
3583 // result.
3584 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003585 // Suppress any lookup-related diagnostics; we'll do these when we
3586 // pick a member.
3587 R.suppressDiagnostics();
3588
John McCall10eae182009-11-30 22:42:35 +00003589 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003590 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003591 BaseExpr, BaseExprType,
3592 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003593 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003594 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003595 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003596
3597 return Owned(MemExpr);
3598 }
3599
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003600 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003601 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003602 NamedDecl *MemberDecl = R.getFoundDecl();
3603
3604 // FIXME: diagnose the presence of template arguments now.
3605
3606 // If the decl being referenced had an error, return an error for this
3607 // sub-expr without emitting another error, in order to avoid cascading
3608 // error cases.
3609 if (MemberDecl->isInvalidDecl())
3610 return ExprError();
3611
John McCall2d74de92009-12-01 22:10:20 +00003612 // Handle the implicit-member-access case.
3613 if (!BaseExpr) {
3614 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003615 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003616 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003617
Douglas Gregorb15af892010-01-07 23:12:05 +00003618 SourceLocation Loc = R.getNameLoc();
3619 if (SS.getRange().isValid())
3620 Loc = SS.getRange().getBegin();
3621 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003622 }
3623
John McCall10eae182009-11-30 22:42:35 +00003624 bool ShouldCheckUse = true;
3625 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3626 // Don't diagnose the use of a virtual member function unless it's
3627 // explicitly qualified.
3628 if (MD->isVirtual() && !SS.isSet())
3629 ShouldCheckUse = false;
3630 }
3631
3632 // Check the use of this member.
3633 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3634 Owned(BaseExpr);
3635 return ExprError();
3636 }
3637
John McCall34376a62010-12-04 03:47:34 +00003638 // Perform a property load on the base regardless of whether we
3639 // actually need it for the declaration.
3640 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3641 ConvertPropertyForRValue(BaseExpr);
3642
John McCallfeb624a2010-11-23 20:48:44 +00003643 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3644 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3645 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003646
Francois Pichet783dd6e2010-11-21 06:08:52 +00003647 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3648 // We may have found a field within an anonymous union or struct
3649 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003650 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003651 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003652
John McCall10eae182009-11-30 22:42:35 +00003653 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3654 MarkDeclarationReferenced(MemberLoc, Var);
3655 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003656 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003657 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003658 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003659 }
3660
John McCall7decc9e2010-11-18 06:31:45 +00003661 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003662 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3663 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003664 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003665 MemberFn->getType(),
3666 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3667 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003668 }
John McCall7decc9e2010-11-18 06:31:45 +00003669 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003670
3671 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3672 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3673 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003674 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003675 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003676 }
3677
3678 Owned(BaseExpr);
3679
Douglas Gregor861eb802010-04-25 20:55:08 +00003680 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003681 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003682 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003683 << MemberName << BaseType << int(IsArrow);
3684 else
3685 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3686 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003687
Douglas Gregor861eb802010-04-25 20:55:08 +00003688 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3689 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003690 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003691 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003692}
3693
John McCall68fc88ec2010-12-15 16:46:44 +00003694/// Given that normal member access failed on the given expression,
3695/// and given that the expression's type involves builtin-id or
3696/// builtin-Class, decide whether substituting in the redefinition
3697/// types would be profitable. The redefinition type is whatever
3698/// this translation unit tried to typedef to id/Class; we store
3699/// it to the side and then re-use it in places like this.
3700static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3701 const ObjCObjectPointerType *opty
3702 = base->getType()->getAs<ObjCObjectPointerType>();
3703 if (!opty) return false;
3704
3705 const ObjCObjectType *ty = opty->getObjectType();
3706
3707 QualType redef;
3708 if (ty->isObjCId()) {
3709 redef = S.Context.ObjCIdRedefinitionType;
3710 } else if (ty->isObjCClass()) {
3711 redef = S.Context.ObjCClassRedefinitionType;
3712 } else {
3713 return false;
3714 }
3715
3716 // Do the substitution as long as the redefinition type isn't just a
3717 // possibly-qualified pointer to builtin-id or builtin-Class again.
3718 opty = redef->getAs<ObjCObjectPointerType>();
3719 if (opty && !opty->getObjectType()->getInterface() != 0)
3720 return false;
3721
3722 S.ImpCastExprToType(base, redef, CK_BitCast);
3723 return true;
3724}
3725
John McCall10eae182009-11-30 22:42:35 +00003726/// Look up the given member of the given non-type-dependent
3727/// expression. This can return in one of two ways:
3728/// * If it returns a sentinel null-but-valid result, the caller will
3729/// assume that lookup was performed and the results written into
3730/// the provided structure. It will take over from there.
3731/// * Otherwise, the returned expression will be produced in place of
3732/// an ordinary member expression.
3733///
3734/// The ObjCImpDecl bit is a gross hack that will need to be properly
3735/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003736ExprResult
John McCall10eae182009-11-30 22:42:35 +00003737Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003738 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003739 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003740 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003741 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003742
Steve Naroffeaaae462007-12-16 21:42:28 +00003743 // Perform default conversions.
3744 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003745 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003746
Steve Naroff185616f2007-07-26 03:11:44 +00003747 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003748 assert(!BaseType->isDependentType());
3749
3750 DeclarationName MemberName = R.getLookupName();
3751 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003752
John McCall68fc88ec2010-12-15 16:46:44 +00003753 // For later type-checking purposes, turn arrow accesses into dot
3754 // accesses. The only access type we support that doesn't follow
3755 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3756 // and those never use arrows, so this is unaffected.
3757 if (IsArrow) {
3758 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3759 BaseType = Ptr->getPointeeType();
3760 else if (const ObjCObjectPointerType *Ptr
3761 = BaseType->getAs<ObjCObjectPointerType>())
3762 BaseType = Ptr->getPointeeType();
3763 else if (BaseType->isRecordType()) {
3764 // Recover from arrow accesses to records, e.g.:
3765 // struct MyRecord foo;
3766 // foo->bar
3767 // This is actually well-formed in C++ if MyRecord has an
3768 // overloaded operator->, but that should have been dealt with
3769 // by now.
3770 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3771 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3772 << FixItHint::CreateReplacement(OpLoc, ".");
3773 IsArrow = false;
3774 } else {
3775 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3776 << BaseType << BaseExpr->getSourceRange();
3777 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003778 }
3779 }
3780
John McCall68fc88ec2010-12-15 16:46:44 +00003781 // Handle field access to simple records.
3782 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3783 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3784 RTy, OpLoc, SS, HasTemplateArgs))
3785 return ExprError();
3786
3787 // Returning valid-but-null is how we indicate to the caller that
3788 // the lookup result was filled in.
3789 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003790 }
John McCall10eae182009-11-30 22:42:35 +00003791
John McCall68fc88ec2010-12-15 16:46:44 +00003792 // Handle ivar access to Objective-C objects.
3793 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003794 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003795
3796 // There are three cases for the base type:
3797 // - builtin id (qualified or unqualified)
3798 // - builtin Class (qualified or unqualified)
3799 // - an interface
3800 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3801 if (!IDecl) {
3802 // There's an implicit 'isa' ivar on all objects.
3803 // But we only actually find it this way on objects of type 'id',
3804 // apparently.
3805 if (OTy->isObjCId() && Member->isStr("isa"))
3806 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3807 Context.getObjCClassType()));
3808
3809 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3810 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3811 ObjCImpDecl, HasTemplateArgs);
3812 goto fail;
3813 }
3814
3815 ObjCInterfaceDecl *ClassDeclared;
3816 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3817
3818 if (!IV) {
3819 // Attempt to correct for typos in ivar names.
3820 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3821 LookupMemberName);
3822 if (CorrectTypo(Res, 0, 0, IDecl, false,
3823 IsArrow ? CTC_ObjCIvarLookup
3824 : CTC_ObjCPropertyLookup) &&
3825 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3826 Diag(R.getNameLoc(),
3827 diag::err_typecheck_member_reference_ivar_suggest)
3828 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3829 << FixItHint::CreateReplacement(R.getNameLoc(),
3830 IV->getNameAsString());
3831 Diag(IV->getLocation(), diag::note_previous_decl)
3832 << IV->getDeclName();
3833 } else {
3834 Res.clear();
3835 Res.setLookupName(Member);
3836
3837 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3838 << IDecl->getDeclName() << MemberName
3839 << BaseExpr->getSourceRange();
3840 return ExprError();
3841 }
3842 }
3843
3844 // If the decl being referenced had an error, return an error for this
3845 // sub-expr without emitting another error, in order to avoid cascading
3846 // error cases.
3847 if (IV->isInvalidDecl())
3848 return ExprError();
3849
3850 // Check whether we can reference this field.
3851 if (DiagnoseUseOfDecl(IV, MemberLoc))
3852 return ExprError();
3853 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3854 IV->getAccessControl() != ObjCIvarDecl::Package) {
3855 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3856 if (ObjCMethodDecl *MD = getCurMethodDecl())
3857 ClassOfMethodDecl = MD->getClassInterface();
3858 else if (ObjCImpDecl && getCurFunctionDecl()) {
3859 // Case of a c-function declared inside an objc implementation.
3860 // FIXME: For a c-style function nested inside an objc implementation
3861 // class, there is no implementation context available, so we pass
3862 // down the context as argument to this routine. Ideally, this context
3863 // need be passed down in the AST node and somehow calculated from the
3864 // AST for a function decl.
3865 if (ObjCImplementationDecl *IMPD =
3866 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3867 ClassOfMethodDecl = IMPD->getClassInterface();
3868 else if (ObjCCategoryImplDecl* CatImplClass =
3869 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3870 ClassOfMethodDecl = CatImplClass->getClassInterface();
3871 }
3872
3873 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3874 if (ClassDeclared != IDecl ||
3875 ClassOfMethodDecl != ClassDeclared)
3876 Diag(MemberLoc, diag::error_private_ivar_access)
3877 << IV->getDeclName();
3878 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3879 // @protected
3880 Diag(MemberLoc, diag::error_protected_ivar_access)
3881 << IV->getDeclName();
3882 }
3883
3884 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3885 MemberLoc, BaseExpr,
3886 IsArrow));
3887 }
3888
3889 // Objective-C property access.
3890 const ObjCObjectPointerType *OPT;
3891 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3892 // This actually uses the base as an r-value.
3893 DefaultLvalueConversion(BaseExpr);
3894 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3895
3896 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3897
3898 const ObjCObjectType *OT = OPT->getObjectType();
3899
3900 // id, with and without qualifiers.
3901 if (OT->isObjCId()) {
3902 // Check protocols on qualified interfaces.
3903 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3904 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3905 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3906 // Check the use of this declaration
3907 if (DiagnoseUseOfDecl(PD, MemberLoc))
3908 return ExprError();
3909
3910 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3911 VK_LValue,
3912 OK_ObjCProperty,
3913 MemberLoc,
3914 BaseExpr));
3915 }
3916
3917 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3918 // Check the use of this method.
3919 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3920 return ExprError();
3921 Selector SetterSel =
3922 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3923 PP.getSelectorTable(), Member);
3924 ObjCMethodDecl *SMD = 0;
3925 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3926 SetterSel, Context))
3927 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3928 QualType PType = OMD->getSendResultType();
3929
3930 ExprValueKind VK = VK_LValue;
3931 if (!getLangOptions().CPlusPlus &&
3932 IsCForbiddenLValueType(Context, PType))
3933 VK = VK_RValue;
3934 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3935
3936 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3937 VK, OK,
3938 MemberLoc, BaseExpr));
3939 }
3940 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003941 // Use of id.member can only be for a property reference. Do not
3942 // use the 'id' redefinition in this case.
3943 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003944 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3945 ObjCImpDecl, HasTemplateArgs);
3946
3947 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3948 << MemberName << BaseType);
3949 }
3950
3951 // 'Class', unqualified only.
3952 if (OT->isObjCClass()) {
3953 // Only works in a method declaration (??!).
3954 ObjCMethodDecl *MD = getCurMethodDecl();
3955 if (!MD) {
3956 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3957 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3958 ObjCImpDecl, HasTemplateArgs);
3959
3960 goto fail;
3961 }
3962
3963 // Also must look for a getter name which uses property syntax.
3964 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003965 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3966 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003967 if ((Getter = IFace->lookupClassMethod(Sel))) {
3968 // Check the use of this method.
3969 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3970 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003971 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003972 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003973 // If we found a getter then this may be a valid dot-reference, we
3974 // will look for the matching setter, in case it is needed.
3975 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003976 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3977 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003978 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3979 if (!Setter) {
3980 // If this reference is in an @implementation, also check for 'private'
3981 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003982 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003983 }
3984 // Look through local category implementations associated with the class.
3985 if (!Setter)
3986 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003987
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003988 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3989 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003990
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003991 if (Getter || Setter) {
3992 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003993
John McCall4bc41ae2010-11-18 19:01:18 +00003994 ExprValueKind VK = VK_LValue;
3995 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003996 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003997 if (!getLangOptions().CPlusPlus &&
3998 IsCForbiddenLValueType(Context, PType))
3999 VK = VK_RValue;
4000 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004001 // Get the expression type from Setter's incoming parameter.
4002 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004003 }
4004 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4005
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004006 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004007 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4008 PType, VK, OK,
4009 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004010 }
John McCall68fc88ec2010-12-15 16:46:44 +00004011
4012 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4013 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4014 ObjCImpDecl, HasTemplateArgs);
4015
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004016 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004017 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004018 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004019
John McCall68fc88ec2010-12-15 16:46:44 +00004020 // Normal property access.
4021 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
4022 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004023 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004024
Chris Lattnerb63a7452008-07-21 04:28:12 +00004025 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004026 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004027 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004028 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00004029 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004030 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4031 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004032 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004033 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004034
4035 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
4036 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004037 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004038
John McCall68fc88ec2010-12-15 16:46:44 +00004039 // Adjust builtin-sel to the appropriate redefinition type if that's
4040 // not just a pointer to builtin-sel again.
4041 if (IsArrow &&
4042 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4043 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4044 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
4045 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4046 ObjCImpDecl, HasTemplateArgs);
4047 }
4048
4049 // Failure cases.
4050 fail:
4051
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004052 // Recover from dot accesses to pointers, e.g.:
4053 // type *foo;
4054 // foo.bar
4055 // This is actually well-formed in two cases:
4056 // - 'type' is an Objective C type
4057 // - 'bar' is a pseudo-destructor name which happens to refer to
4058 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004059 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004060 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4061 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004062 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004063 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4064 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004065
4066 // Recurse as an -> access.
4067 IsArrow = true;
4068 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4069 ObjCImpDecl, HasTemplateArgs);
4070 }
John McCall68fc88ec2010-12-15 16:46:44 +00004071 }
4072
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004073 // If the user is trying to apply -> or . to a function name, it's probably
4074 // because they forgot parentheses to call that function.
4075 bool TryCall = false;
4076 bool Overloaded = false;
4077 UnresolvedSet<8> AllOverloads;
4078 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4079 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4080 TryCall = true;
4081 Overloaded = true;
4082 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4083 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4084 AllOverloads.addDecl(Fun);
4085 TryCall = true;
4086 }
4087 }
John McCall68fc88ec2010-12-15 16:46:44 +00004088
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004089 if (TryCall) {
4090 // Plunder the overload set for something that would make the member
4091 // expression valid.
4092 UnresolvedSet<4> ViableOverloads;
4093 bool HasViableZeroArgOverload = false;
4094 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4095 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004096 // Our overload set may include TemplateDecls, which we'll ignore for the
4097 // purposes of determining whether we can issue a '()' fixit.
4098 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4099 QualType ResultTy = OverloadDecl->getResultType();
4100 if ((!IsArrow && ResultTy->isRecordType()) ||
4101 (IsArrow && ResultTy->isPointerType() &&
4102 ResultTy->getPointeeType()->isRecordType())) {
4103 ViableOverloads.addDecl(*it);
4104 if (OverloadDecl->getMinRequiredArguments() == 0) {
4105 HasViableZeroArgOverload = true;
4106 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004107 }
John McCall68fc88ec2010-12-15 16:46:44 +00004108 }
4109 }
4110
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004111 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4112 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004113 << (AllOverloads.size() > 1) << 0
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004114 << BaseExpr->getSourceRange();
4115 int ViableOverloadCount = ViableOverloads.size();
4116 int I;
4117 for (I = 0; I < ViableOverloadCount; ++I) {
4118 // FIXME: Magic number for max shown overloads stolen from
4119 // OverloadCandidateSet::NoteCandidates.
4120 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4121 break;
4122 }
4123 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4124 diag::note_member_ref_possible_intended_overload);
4125 }
4126 if (I != ViableOverloadCount) {
4127 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4128 << int(ViableOverloadCount - I);
4129 }
4130 return ExprError();
4131 }
4132 } else {
4133 // We don't have an expression that's convenient to get a Decl from, but we
4134 // can at least check if the type is "function of 0 arguments which returns
4135 // an acceptable type".
4136 const FunctionType *Fun = NULL;
4137 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4138 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4139 TryCall = true;
4140 }
4141 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4142 TryCall = true;
4143 }
John McCall68fc88ec2010-12-15 16:46:44 +00004144
4145 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004146 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4147 if (FPT->getNumArgs() == 0) {
4148 QualType ResultTy = Fun->getResultType();
4149 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4150 (IsArrow && ResultTy->isPointerType() &&
4151 ResultTy->getPointeeType()->isRecordType());
4152 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004153 }
John McCall68fc88ec2010-12-15 16:46:44 +00004154 }
4155 }
4156
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004157 if (TryCall) {
4158 // At this point, we know BaseExpr looks like it's potentially callable with
4159 // 0 arguments, and that it returns something of a reasonable type, so we
4160 // can emit a fixit and carry on pretending that BaseExpr was actually a
4161 // CallExpr.
4162 SourceLocation ParenInsertionLoc =
4163 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4164 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4165 << int(Overloaded) << 1
4166 << BaseExpr->getSourceRange()
4167 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4168 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4169 MultiExprArg(*this, 0, 0),
4170 ParenInsertionLoc);
4171 if (NewBase.isInvalid())
4172 return ExprError();
4173 BaseExpr = NewBase.takeAs<Expr>();
4174 DefaultFunctionArrayConversion(BaseExpr);
4175 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4176 ObjCImpDecl, HasTemplateArgs);
4177 }
4178
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004179 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4180 << BaseType << BaseExpr->getSourceRange();
4181
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004182 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004183}
4184
John McCall10eae182009-11-30 22:42:35 +00004185/// The main callback when the parser finds something like
4186/// expression . [nested-name-specifier] identifier
4187/// expression -> [nested-name-specifier] identifier
4188/// where 'identifier' encompasses a fairly broad spectrum of
4189/// possibilities, including destructor and operator references.
4190///
4191/// \param OpKind either tok::arrow or tok::period
4192/// \param HasTrailingLParen whether the next token is '(', which
4193/// is used to diagnose mis-uses of special members that can
4194/// only be called
4195/// \param ObjCImpDecl the current ObjC @implementation decl;
4196/// this is an ugly hack around the fact that ObjC @implementations
4197/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004198ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004199 SourceLocation OpLoc,
4200 tok::TokenKind OpKind,
4201 CXXScopeSpec &SS,
4202 UnqualifiedId &Id,
4203 Decl *ObjCImpDecl,
4204 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004205 if (SS.isSet() && SS.isInvalid())
4206 return ExprError();
4207
Francois Pichet64225792011-01-18 05:04:39 +00004208 // Warn about the explicit constructor calls Microsoft extension.
4209 if (getLangOptions().Microsoft &&
4210 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4211 Diag(Id.getSourceRange().getBegin(),
4212 diag::ext_ms_explicit_constructor_call);
4213
John McCall10eae182009-11-30 22:42:35 +00004214 TemplateArgumentListInfo TemplateArgsBuffer;
4215
4216 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004217 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004218 const TemplateArgumentListInfo *TemplateArgs;
4219 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004220 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004221
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004222 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004223 bool IsArrow = (OpKind == tok::arrow);
4224
4225 NamedDecl *FirstQualifierInScope
4226 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4227 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4228
4229 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004230 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004231 if (Result.isInvalid()) return ExprError();
4232 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004233
Douglas Gregor41f90302010-04-12 20:54:26 +00004234 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4235 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004236 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004237 IsArrow, OpLoc,
4238 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004239 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004240 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004241 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004242 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4243 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004244
John McCalle9cccd82010-06-16 08:42:20 +00004245 if (Result.isInvalid()) {
4246 Owned(Base);
4247 return ExprError();
4248 }
John McCall10eae182009-11-30 22:42:35 +00004249
John McCalle9cccd82010-06-16 08:42:20 +00004250 if (Result.get()) {
4251 // The only way a reference to a destructor can be used is to
4252 // immediately call it, which falls into this case. If the
4253 // next token is not a '(', produce a diagnostic and build the
4254 // call now.
4255 if (!HasTrailingLParen &&
4256 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004257 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004258
John McCalle9cccd82010-06-16 08:42:20 +00004259 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004260 }
4261
John McCallb268a282010-08-23 23:25:46 +00004262 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004263 OpLoc, IsArrow, SS, FirstQualifierInScope,
4264 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004265 }
4266
4267 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004268}
4269
John McCalldadc5752010-08-24 06:29:42 +00004270ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004271 FunctionDecl *FD,
4272 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004273 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004274 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004275 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004276 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004277 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004278 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004279 return ExprError();
4280 }
4281
4282 if (Param->hasUninstantiatedDefaultArg()) {
4283 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004284
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004285 // Instantiate the expression.
4286 MultiLevelTemplateArgumentList ArgList
4287 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004288
Nico Weber44887f62010-11-29 18:19:25 +00004289 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004290 = ArgList.getInnermost();
4291 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4292 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004293
Nico Weber44887f62010-11-29 18:19:25 +00004294 ExprResult Result;
4295 {
4296 // C++ [dcl.fct.default]p5:
4297 // The names in the [default argument] expression are bound, and
4298 // the semantic constraints are checked, at the point where the
4299 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004300 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004301 Result = SubstExpr(UninstExpr, ArgList);
4302 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004303 if (Result.isInvalid())
4304 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004305
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004306 // Check the expression as an initializer for the parameter.
4307 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004308 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004309 InitializationKind Kind
4310 = InitializationKind::CreateCopy(Param->getLocation(),
4311 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4312 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004313
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004314 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4315 Result = InitSeq.Perform(*this, Entity, Kind,
4316 MultiExprArg(*this, &ResultE, 1));
4317 if (Result.isInvalid())
4318 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004319
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004320 // Build the default argument expression.
4321 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4322 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004323 }
4324
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004325 // If the default expression creates temporaries, we need to
4326 // push them to the current stack of expression temporaries so they'll
4327 // be properly destroyed.
4328 // FIXME: We should really be rebuilding the default argument with new
4329 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004330 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4331 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4332 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4333 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4334 ExprTemporaries.push_back(Temporary);
4335 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004336
4337 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004338 // Just mark all of the declarations in this potentially-evaluated expression
4339 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004340 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004341 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004342}
4343
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004344/// ConvertArgumentsForCall - Converts the arguments specified in
4345/// Args/NumArgs to the parameter types of the function FDecl with
4346/// function prototype Proto. Call is the call expression itself, and
4347/// Fn is the function expression. For a C++ member function, this
4348/// routine does not attempt to convert the object argument. Returns
4349/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004350bool
4351Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004352 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004353 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004354 Expr **Args, unsigned NumArgs,
4355 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004356 // Bail out early if calling a builtin with custom typechecking.
4357 // We don't need to do this in the
4358 if (FDecl)
4359 if (unsigned ID = FDecl->getBuiltinID())
4360 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4361 return false;
4362
Mike Stump4e1f26a2009-02-19 03:04:26 +00004363 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004364 // assignment, to the types of the corresponding parameter, ...
4365 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004366 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004367
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004368 // If too few arguments are available (and we don't have default
4369 // arguments for the remaining parameters), don't make the call.
4370 if (NumArgs < NumArgsInProto) {
4371 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4372 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004373 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004374 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004375 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004376 }
4377
4378 // If too many are passed and not variadic, error on the extras and drop
4379 // them.
4380 if (NumArgs > NumArgsInProto) {
4381 if (!Proto->isVariadic()) {
4382 Diag(Args[NumArgsInProto]->getLocStart(),
4383 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004384 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004385 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004386 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4387 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004388
4389 // Emit the location of the prototype.
4390 if (FDecl && !FDecl->getBuiltinID())
4391 Diag(FDecl->getLocStart(),
4392 diag::note_typecheck_call_too_many_args)
4393 << FDecl;
4394
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004395 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004396 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004397 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004398 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004399 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004400 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004401 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004402 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4403 if (Fn->getType()->isBlockPointerType())
4404 CallType = VariadicBlock; // Block
4405 else if (isa<MemberExpr>(Fn))
4406 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004407 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004408 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004409 if (Invalid)
4410 return true;
4411 unsigned TotalNumArgs = AllArgs.size();
4412 for (unsigned i = 0; i < TotalNumArgs; ++i)
4413 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004414
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004415 return false;
4416}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004417
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004418bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4419 FunctionDecl *FDecl,
4420 const FunctionProtoType *Proto,
4421 unsigned FirstProtoArg,
4422 Expr **Args, unsigned NumArgs,
4423 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004424 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004425 unsigned NumArgsInProto = Proto->getNumArgs();
4426 unsigned NumArgsToCheck = NumArgs;
4427 bool Invalid = false;
4428 if (NumArgs != NumArgsInProto)
4429 // Use default arguments for missing arguments
4430 NumArgsToCheck = NumArgsInProto;
4431 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004432 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004433 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004434 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004435
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004436 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004437 if (ArgIx < NumArgs) {
4438 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004439
Eli Friedman3164fb12009-03-22 22:00:50 +00004440 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4441 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004442 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004443 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004444 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004445
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004446 // Pass the argument
4447 ParmVarDecl *Param = 0;
4448 if (FDecl && i < FDecl->getNumParams())
4449 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004450
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004451 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004452 Param? InitializedEntity::InitializeParameter(Context, Param)
4453 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004454 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004455 SourceLocation(),
4456 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004457 if (ArgE.isInvalid())
4458 return true;
4459
4460 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004461 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004462 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004463
John McCalldadc5752010-08-24 06:29:42 +00004464 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004465 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004466 if (ArgExpr.isInvalid())
4467 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004468
Anders Carlsson355933d2009-08-25 03:49:14 +00004469 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004470 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004471 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004472 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004474 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004475 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004476 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004477 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004478 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004479 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004480 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004481 }
4482 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004483 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004484}
4485
Steve Naroff83895f72007-09-16 03:34:24 +00004486/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004487/// This provides the location of the left/right parens and a list of comma
4488/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004489ExprResult
John McCallb268a282010-08-23 23:25:46 +00004490Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004491 MultiExprArg args, SourceLocation RParenLoc,
4492 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004493 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004494
4495 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004496 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004497 if (Result.isInvalid()) return ExprError();
4498 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004499
John McCallb268a282010-08-23 23:25:46 +00004500 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004501
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004502 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004503 // If this is a pseudo-destructor expression, build the call immediately.
4504 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4505 if (NumArgs > 0) {
4506 // Pseudo-destructor calls should not have any arguments.
4507 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004508 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004509 SourceRange(Args[0]->getLocStart(),
4510 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004511
Douglas Gregorad8a3362009-09-04 17:36:40 +00004512 NumArgs = 0;
4513 }
Mike Stump11289f42009-09-09 15:08:12 +00004514
Douglas Gregorad8a3362009-09-04 17:36:40 +00004515 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004516 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004517 }
Mike Stump11289f42009-09-09 15:08:12 +00004518
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004519 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004520 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004521 // FIXME: Will need to cache the results of name lookup (including ADL) in
4522 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004523 bool Dependent = false;
4524 if (Fn->isTypeDependent())
4525 Dependent = true;
4526 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4527 Dependent = true;
4528
Peter Collingbourne41f85462011-02-09 21:07:24 +00004529 if (Dependent) {
4530 if (ExecConfig) {
4531 return Owned(new (Context) CUDAKernelCallExpr(
4532 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4533 Context.DependentTy, VK_RValue, RParenLoc));
4534 } else {
4535 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4536 Context.DependentTy, VK_RValue,
4537 RParenLoc));
4538 }
4539 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004540
4541 // Determine whether this is a call to an object (C++ [over.call.object]).
4542 if (Fn->getType()->isRecordType())
4543 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004544 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004545
John McCall10eae182009-11-30 22:42:35 +00004546 Expr *NakedFn = Fn->IgnoreParens();
4547
4548 // Determine whether this is a call to an unresolved member function.
4549 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4550 // If lookup was unresolved but not dependent (i.e. didn't find
4551 // an unresolved using declaration), it has to be an overloaded
4552 // function set, which means it must contain either multiple
4553 // declarations (all methods or method templates) or a single
4554 // method template.
4555 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004556 isa<FunctionTemplateDecl>(
4557 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004558 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004559
John McCall2d74de92009-12-01 22:10:20 +00004560 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004561 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004562 }
4563
Douglas Gregore254f902009-02-04 00:32:51 +00004564 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004565 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004566 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004567 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004568 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004569 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004570 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004571
Anders Carlsson61914b52009-10-03 17:40:22 +00004572 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004573 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004574 if (BO->getOpcode() == BO_PtrMemD ||
4575 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004576 if (const FunctionProtoType *FPT
4577 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004578 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004579 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004580
Douglas Gregor125fa402011-02-04 12:57:49 +00004581 // Check that the object type isn't more qualified than the
4582 // member function we're calling.
4583 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4584 Qualifiers ObjectQuals
4585 = BO->getOpcode() == BO_PtrMemD
4586 ? BO->getLHS()->getType().getQualifiers()
4587 : BO->getLHS()->getType()->getAs<PointerType>()
4588 ->getPointeeType().getQualifiers();
4589
4590 Qualifiers Difference = ObjectQuals - FuncQuals;
4591 Difference.removeObjCGCAttr();
4592 Difference.removeAddressSpace();
4593 if (Difference) {
4594 std::string QualsString = Difference.getAsString();
4595 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4596 << BO->getType().getUnqualifiedType()
4597 << QualsString
4598 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4599 }
4600
John McCallb268a282010-08-23 23:25:46 +00004601 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004602 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004603 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004604 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004605
4606 if (CheckCallReturnType(FPT->getResultType(),
4607 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004608 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004609 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004610
John McCallb268a282010-08-23 23:25:46 +00004611 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004612 RParenLoc))
4613 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004614
John McCallb268a282010-08-23 23:25:46 +00004615 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004616 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004617 }
4618 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004619 }
4620
Douglas Gregore254f902009-02-04 00:32:51 +00004621 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004622 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004623 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004624
Eli Friedmane14b1992009-12-26 03:35:45 +00004625 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004626 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4627 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4628 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004629 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004630 }
4631
John McCall57500772009-12-16 12:17:52 +00004632 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004633 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4634 if (UnOp->getOpcode() == UO_AddrOf)
4635 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4636
John McCall57500772009-12-16 12:17:52 +00004637 if (isa<DeclRefExpr>(NakedFn))
4638 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4639
Peter Collingbourne41f85462011-02-09 21:07:24 +00004640 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4641 ExecConfig);
4642}
4643
4644ExprResult
4645Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4646 MultiExprArg execConfig, SourceLocation GGGLoc) {
4647 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4648 if (!ConfigDecl)
4649 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4650 << "cudaConfigureCall");
4651 QualType ConfigQTy = ConfigDecl->getType();
4652
4653 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4654 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4655
4656 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004657}
4658
John McCall57500772009-12-16 12:17:52 +00004659/// BuildResolvedCallExpr - Build a call to a resolved expression,
4660/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004661/// unary-convert to an expression of function-pointer or
4662/// block-pointer type.
4663///
4664/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004665ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004666Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4667 SourceLocation LParenLoc,
4668 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004669 SourceLocation RParenLoc,
4670 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004671 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4672
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004673 // Promote the function operand.
4674 UsualUnaryConversions(Fn);
4675
Chris Lattner08464942007-12-28 05:29:59 +00004676 // Make the call expr early, before semantic checks. This guarantees cleanup
4677 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004678 CallExpr *TheCall;
4679 if (Config) {
4680 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4681 cast<CallExpr>(Config),
4682 Args, NumArgs,
4683 Context.BoolTy,
4684 VK_RValue,
4685 RParenLoc);
4686 } else {
4687 TheCall = new (Context) CallExpr(Context, Fn,
4688 Args, NumArgs,
4689 Context.BoolTy,
4690 VK_RValue,
4691 RParenLoc);
4692 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004693
John McCallbebede42011-02-26 05:39:39 +00004694 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4695
4696 // Bail out early if calling a builtin with custom typechecking.
4697 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4698 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4699
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004700 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004701 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004702 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4703 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004704 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004705 if (FuncT == 0)
4706 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4707 << Fn->getType() << Fn->getSourceRange());
4708 } else if (const BlockPointerType *BPT =
4709 Fn->getType()->getAs<BlockPointerType>()) {
4710 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4711 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004712 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4713 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004714 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004715
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004716 if (getLangOptions().CUDA) {
4717 if (Config) {
4718 // CUDA: Kernel calls must be to global functions
4719 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4720 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4721 << FDecl->getName() << Fn->getSourceRange());
4722
4723 // CUDA: Kernel function must have 'void' return type
4724 if (!FuncT->getResultType()->isVoidType())
4725 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4726 << Fn->getType() << Fn->getSourceRange());
4727 }
4728 }
4729
Eli Friedman3164fb12009-03-22 22:00:50 +00004730 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004731 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004732 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004733 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004734 return ExprError();
4735
Chris Lattner08464942007-12-28 05:29:59 +00004736 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004737 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004738 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004739
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004740 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004741 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004742 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004743 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004744 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004745 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004746
Douglas Gregord8e97de2009-04-02 15:37:10 +00004747 if (FDecl) {
4748 // Check if we have too few/too many template arguments, based
4749 // on our knowledge of the function definition.
4750 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004751 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004752 const FunctionProtoType *Proto
4753 = Def->getType()->getAs<FunctionProtoType>();
4754 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004755 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4756 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004757 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004758
4759 // If the function we're calling isn't a function prototype, but we have
4760 // a function prototype from a prior declaratiom, use that prototype.
4761 if (!FDecl->hasPrototype())
4762 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004763 }
4764
Steve Naroff0b661582007-08-28 23:30:39 +00004765 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004766 for (unsigned i = 0; i != NumArgs; i++) {
4767 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004768
4769 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004770 InitializedEntity Entity
4771 = InitializedEntity::InitializeParameter(Context,
4772 Proto->getArgType(i));
4773 ExprResult ArgE = PerformCopyInitialization(Entity,
4774 SourceLocation(),
4775 Owned(Arg));
4776 if (ArgE.isInvalid())
4777 return true;
4778
4779 Arg = ArgE.takeAs<Expr>();
4780
4781 } else {
4782 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004783 }
4784
Douglas Gregor83025412010-10-26 05:45:40 +00004785 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4786 Arg->getType(),
4787 PDiag(diag::err_call_incomplete_argument)
4788 << Arg->getSourceRange()))
4789 return ExprError();
4790
Chris Lattner08464942007-12-28 05:29:59 +00004791 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004792 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004793 }
Chris Lattner08464942007-12-28 05:29:59 +00004794
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004795 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4796 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004797 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4798 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004799
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004800 // Check for sentinels
4801 if (NDecl)
4802 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004803
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004804 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004805 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004806 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004807 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004808
John McCallbebede42011-02-26 05:39:39 +00004809 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004810 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004811 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004812 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004813 return ExprError();
4814 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004815
John McCallb268a282010-08-23 23:25:46 +00004816 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004817}
4818
John McCalldadc5752010-08-24 06:29:42 +00004819ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004820Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004821 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004822 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004823 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004824 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004825
4826 TypeSourceInfo *TInfo;
4827 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4828 if (!TInfo)
4829 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4830
John McCallb268a282010-08-23 23:25:46 +00004831 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004832}
4833
John McCalldadc5752010-08-24 06:29:42 +00004834ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004835Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004836 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004837 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004838
Eli Friedman37a186d2008-05-20 05:22:08 +00004839 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004840 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4841 PDiag(diag::err_illegal_decl_array_incomplete_type)
4842 << SourceRange(LParenLoc,
4843 literalExpr->getSourceRange().getEnd())))
4844 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004845 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004846 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4847 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004848 } else if (!literalType->isDependentType() &&
4849 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004850 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004851 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004852 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004853 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004854
Douglas Gregor85dabae2009-12-16 01:38:02 +00004855 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004856 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004857 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004858 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004859 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004860 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004861 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004862 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004863 &literalType);
4864 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004865 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004866 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004867
Chris Lattner79413952008-12-04 23:50:19 +00004868 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004869 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004870 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004871 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004872 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004873
John McCall7decc9e2010-11-18 06:31:45 +00004874 // In C, compound literals are l-values for some reason.
4875 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4876
John McCall5d7aa7f2010-01-19 22:33:45 +00004877 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004878 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004879}
4880
John McCalldadc5752010-08-24 06:29:42 +00004881ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004882Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004883 SourceLocation RBraceLoc) {
4884 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004885 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004886
Steve Naroff30d242c2007-09-15 18:49:24 +00004887 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004888 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004889
Ted Kremenekac034612010-04-13 23:39:13 +00004890 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4891 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004892 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004893 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004894}
4895
John McCalld7646252010-11-14 08:17:51 +00004896/// Prepares for a scalar cast, performing all the necessary stages
4897/// except the final cast and returning the kind required.
4898static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4899 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4900 // Also, callers should have filtered out the invalid cases with
4901 // pointers. Everything else should be possible.
4902
Abramo Bagnaraba854972011-01-04 09:50:03 +00004903 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004904 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004905 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004906
John McCall8cb679e2010-11-15 09:13:47 +00004907 switch (SrcTy->getScalarTypeKind()) {
4908 case Type::STK_MemberPointer:
4909 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004910
John McCall8cb679e2010-11-15 09:13:47 +00004911 case Type::STK_Pointer:
4912 switch (DestTy->getScalarTypeKind()) {
4913 case Type::STK_Pointer:
4914 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004915 CK_AnyPointerToObjCPointerCast :
4916 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004917 case Type::STK_Bool:
4918 return CK_PointerToBoolean;
4919 case Type::STK_Integral:
4920 return CK_PointerToIntegral;
4921 case Type::STK_Floating:
4922 case Type::STK_FloatingComplex:
4923 case Type::STK_IntegralComplex:
4924 case Type::STK_MemberPointer:
4925 llvm_unreachable("illegal cast from pointer");
4926 }
4927 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004928
John McCall8cb679e2010-11-15 09:13:47 +00004929 case Type::STK_Bool: // casting from bool is like casting from an integer
4930 case Type::STK_Integral:
4931 switch (DestTy->getScalarTypeKind()) {
4932 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004933 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004934 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004935 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004936 case Type::STK_Bool:
4937 return CK_IntegralToBoolean;
4938 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004939 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004940 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004941 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004942 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004943 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004944 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004945 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004946 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004947 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004948 CK_IntegralToFloating);
4949 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004950 case Type::STK_MemberPointer:
4951 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004952 }
4953 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004954
John McCall8cb679e2010-11-15 09:13:47 +00004955 case Type::STK_Floating:
4956 switch (DestTy->getScalarTypeKind()) {
4957 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004958 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004959 case Type::STK_Bool:
4960 return CK_FloatingToBoolean;
4961 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004962 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004963 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004964 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004965 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004966 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004967 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004968 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004969 CK_FloatingToIntegral);
4970 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004971 case Type::STK_Pointer:
4972 llvm_unreachable("valid float->pointer cast?");
4973 case Type::STK_MemberPointer:
4974 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004975 }
4976 break;
4977
John McCall8cb679e2010-11-15 09:13:47 +00004978 case Type::STK_FloatingComplex:
4979 switch (DestTy->getScalarTypeKind()) {
4980 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004981 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004982 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004983 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004984 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004985 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004986 if (S.Context.hasSameType(ET, DestTy))
4987 return CK_FloatingComplexToReal;
4988 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4989 return CK_FloatingCast;
4990 }
John McCall8cb679e2010-11-15 09:13:47 +00004991 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004992 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004993 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004994 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004995 CK_FloatingComplexToReal);
4996 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004997 case Type::STK_Pointer:
4998 llvm_unreachable("valid complex float->pointer cast?");
4999 case Type::STK_MemberPointer:
5000 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005001 }
5002 break;
5003
John McCall8cb679e2010-11-15 09:13:47 +00005004 case Type::STK_IntegralComplex:
5005 switch (DestTy->getScalarTypeKind()) {
5006 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005007 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005008 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005009 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005010 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005011 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005012 if (S.Context.hasSameType(ET, DestTy))
5013 return CK_IntegralComplexToReal;
5014 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
5015 return CK_IntegralCast;
5016 }
John McCall8cb679e2010-11-15 09:13:47 +00005017 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005018 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005019 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005020 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00005021 CK_IntegralComplexToReal);
5022 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005023 case Type::STK_Pointer:
5024 llvm_unreachable("valid complex int->pointer cast?");
5025 case Type::STK_MemberPointer:
5026 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005027 }
5028 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005029 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005030
John McCalld7646252010-11-14 08:17:51 +00005031 llvm_unreachable("Unhandled scalar cast");
5032 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005033}
5034
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005035/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00005036bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5037 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
5038 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00005039 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005040 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5041 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005042 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005043 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005044
John McCall7decc9e2010-11-18 06:31:45 +00005045 // We only support r-value casts in C.
5046 VK = VK_RValue;
5047
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005048 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5049 // type needs to be scalar.
5050 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005051 // We don't necessarily do lvalue-to-rvalue conversions on this.
5052 IgnoredValueConversions(castExpr);
5053
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005054 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005055 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00005056 return false;
5057 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005058
John McCall34376a62010-12-04 03:47:34 +00005059 DefaultFunctionArrayLvalueConversion(castExpr);
5060
Eli Friedmane98194d2010-07-17 20:43:49 +00005061 if (RequireCompleteType(TyR.getBegin(), castType,
5062 diag::err_typecheck_cast_to_incomplete))
5063 return true;
5064
Anders Carlssonef918ac2009-10-16 02:35:04 +00005065 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005066 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005067 (castType->isStructureType() || castType->isUnionType())) {
5068 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005069 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005070 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5071 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005072 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005073 return false;
5074 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005075
Anders Carlsson525b76b2009-10-16 02:48:28 +00005076 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005077 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005078 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005079 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005080 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005081 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005082 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005083 castExpr->getType()) &&
5084 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005085 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5086 << castExpr->getSourceRange();
5087 break;
5088 }
5089 }
5090 if (Field == FieldEnd)
5091 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5092 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005093 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005094 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005095 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005096
Anders Carlsson525b76b2009-10-16 02:48:28 +00005097 // Reject any other conversions to non-scalar types.
5098 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5099 << castType << castExpr->getSourceRange();
5100 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005101
John McCalld7646252010-11-14 08:17:51 +00005102 // The type we're casting to is known to be a scalar or vector.
5103
5104 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005105 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005106 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005107 return Diag(castExpr->getLocStart(),
5108 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005109 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005110 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005111
5112 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005113 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005114
Anton Yartsev28ccef72011-03-27 09:32:40 +00005115 if (castType->isVectorType()) {
5116 if (castType->getAs<VectorType>()->getVectorKind() ==
5117 VectorType::AltiVecVector &&
5118 (castExpr->getType()->isIntegerType() ||
5119 castExpr->getType()->isFloatingType())) {
5120 Kind = CK_VectorSplat;
5121 return false;
5122 } else
5123 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5124 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005125 if (castExpr->getType()->isVectorType())
5126 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5127
John McCalld7646252010-11-14 08:17:51 +00005128 // The source and target types are both scalars, i.e.
5129 // - arithmetic types (fundamental, enum, and complex)
5130 // - all kinds of pointers
5131 // Note that member pointers were filtered out with C++, above.
5132
Anders Carlsson43d70f82009-10-16 05:23:41 +00005133 if (isa<ObjCSelectorExpr>(castExpr))
5134 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005135
John McCalld7646252010-11-14 08:17:51 +00005136 // If either type is a pointer, the other type has to be either an
5137 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005138 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005139 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005140 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005141 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005142 return Diag(castExpr->getLocStart(),
5143 diag::err_cast_pointer_from_non_pointer_int)
5144 << castExprType << castExpr->getSourceRange();
5145 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005146 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005147 return Diag(castExpr->getLocStart(),
5148 diag::err_cast_pointer_to_non_pointer_int)
5149 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005150 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005151
John McCalld7646252010-11-14 08:17:51 +00005152 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005153
John McCalld7646252010-11-14 08:17:51 +00005154 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005155 CheckCastAlign(castExpr, castType, TyR);
5156
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005157 return false;
5158}
5159
Anders Carlsson525b76b2009-10-16 02:48:28 +00005160bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005161 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005162 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163
Anders Carlssonde71adf2007-11-27 05:51:55 +00005164 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005165 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005166 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005167 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005168 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005169 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005170 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005171 } else
5172 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005173 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005174 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005175
John McCalle3027922010-08-25 11:45:40 +00005176 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005177 return false;
5178}
5179
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005180bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005181 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005182 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005183
Anders Carlsson43d70f82009-10-16 05:23:41 +00005184 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005185
Nate Begemanc8961a42009-06-27 22:05:55 +00005186 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5187 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005188 if (SrcTy->isVectorType()) {
5189 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5190 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5191 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005192 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005193 return false;
5194 }
5195
Nate Begemanbd956c42009-06-28 02:36:38 +00005196 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005197 // conversion will take place first from scalar to elt type, and then
5198 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005199 if (SrcTy->isPointerType())
5200 return Diag(R.getBegin(),
5201 diag::err_invalid_conversion_between_vector_and_scalar)
5202 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005203
5204 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5205 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005206 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005207
John McCalle3027922010-08-25 11:45:40 +00005208 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005209 return false;
5210}
5211
John McCalldadc5752010-08-24 06:29:42 +00005212ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005213Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005214 SourceLocation RParenLoc, Expr *castExpr) {
5215 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005216 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005217
John McCall97513962010-01-15 18:39:57 +00005218 TypeSourceInfo *castTInfo;
5219 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5220 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005221 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005222
Nate Begeman5ec4b312009-08-10 23:49:36 +00005223 // If the Expr being casted is a ParenListExpr, handle it specially.
5224 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005225 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005226 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005227
John McCallb268a282010-08-23 23:25:46 +00005228 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005229}
5230
John McCalldadc5752010-08-24 06:29:42 +00005231ExprResult
John McCallebe54742010-01-15 18:56:44 +00005232Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005233 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005234 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005235 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005236 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005237 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005238 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005239 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005240
John McCallcf142162010-08-07 06:22:56 +00005241 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005242 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005243 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005244 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005245}
5246
Nate Begeman5ec4b312009-08-10 23:49:36 +00005247/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5248/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005249ExprResult
John McCallb268a282010-08-23 23:25:46 +00005250Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005251 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5252 if (!E)
5253 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005254
John McCalldadc5752010-08-24 06:29:42 +00005255 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005256
Nate Begeman5ec4b312009-08-10 23:49:36 +00005257 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005258 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5259 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005260
John McCallb268a282010-08-23 23:25:46 +00005261 if (Result.isInvalid()) return ExprError();
5262
5263 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005264}
5265
John McCalldadc5752010-08-24 06:29:42 +00005266ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005267Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005268 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005269 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005270 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005271 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005272 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005273
Anton Yartsev28ccef72011-03-27 09:32:40 +00005274 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005275 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005276 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5277 if (PE->getNumExprs() == 0) {
5278 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5279 return ExprError();
5280 }
John Thompson781ad172010-06-30 22:55:51 +00005281 if (PE->getNumExprs() == 1) {
5282 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005283 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005284 }
5285 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005286 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005287 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005288
Anton Yartsev28ccef72011-03-27 09:32:40 +00005289 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005290 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005291 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005292 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005293 // '(...)' form of vector initialization in AltiVec: the number of
5294 // initializers must be one or must match the size of the vector.
5295 // If a single value is specified in the initializer then it will be
5296 // replicated to all the components of the vector
5297 if (Ty->getAs<VectorType>()->getVectorKind() ==
5298 VectorType::AltiVecVector) {
5299 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5300 // The number of initializers must be one or must match the size of the
5301 // vector. If a single value is specified in the initializer then it will
5302 // be replicated to all the components of the vector
5303 if (PE->getNumExprs() == 1) {
5304 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5305 Expr *Literal = PE->getExpr(0);
5306 ImpCastExprToType(Literal, ElemTy,
5307 PrepareScalarCast(*this, Literal, ElemTy));
5308 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal);
5309 }
5310 else if (PE->getNumExprs() < numElems) {
5311 Diag(PE->getExprLoc(),
5312 diag::err_incorrect_number_of_vector_initializers);
5313 return ExprError();
5314 }
5315 else
5316 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5317 initExprs.push_back(PE->getExpr(i));
5318 }
5319 else
5320 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5321 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005322
5323 // FIXME: This means that pretty-printing the final AST will produce curly
5324 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005325 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5326 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005327 initExprs.size(), RParenLoc);
5328 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005329 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005330 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005331 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005332 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005333 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005334 if (Result.isInvalid()) return ExprError();
5335 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005336 }
5337}
5338
John McCalldadc5752010-08-24 06:29:42 +00005339ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005340 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005341 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005342 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005343 unsigned nexprs = Val.size();
5344 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005345 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5346 Expr *expr;
5347 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5348 expr = new (Context) ParenExpr(L, R, exprs[0]);
5349 else
5350 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005351 return Owned(expr);
5352}
5353
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005354/// \brief Emit a specialized diagnostic when one expression is a null pointer
5355/// constant and the other is not a pointer.
5356bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5357 SourceLocation QuestionLoc) {
5358 Expr *NullExpr = LHS;
5359 Expr *NonPointerExpr = RHS;
5360 Expr::NullPointerConstantKind NullKind =
5361 NullExpr->isNullPointerConstant(Context,
5362 Expr::NPC_ValueDependentIsNotNull);
5363
5364 if (NullKind == Expr::NPCK_NotNull) {
5365 NullExpr = RHS;
5366 NonPointerExpr = LHS;
5367 NullKind =
5368 NullExpr->isNullPointerConstant(Context,
5369 Expr::NPC_ValueDependentIsNotNull);
5370 }
5371
5372 if (NullKind == Expr::NPCK_NotNull)
5373 return false;
5374
5375 if (NullKind == Expr::NPCK_ZeroInteger) {
5376 // In this case, check to make sure that we got here from a "NULL"
5377 // string in the source code.
5378 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005379 SourceLocation loc = NullExpr->getExprLoc();
5380 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005381 return false;
5382 }
5383
5384 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5385 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5386 << NonPointerExpr->getType() << DiagType
5387 << NonPointerExpr->getSourceRange();
5388 return true;
5389}
5390
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005391/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5392/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005393/// C99 6.5.15
5394QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005395 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005396 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005397
5398 // If either LHS or RHS are overloaded functions, try to resolve them.
5399 if (LHS->getType() == Context.OverloadTy ||
5400 RHS->getType() == Context.OverloadTy) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005401 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5402 if (LHSResult.isInvalid())
5403 return QualType();
5404
5405 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5406 if (RHSResult.isInvalid())
5407 return QualType();
5408
5409 LHS = LHSResult.take();
5410 RHS = RHSResult.take();
5411 }
5412
Sebastian Redl1a99f442009-04-16 17:51:27 +00005413 // C++ is sufficiently different to merit its own checker.
5414 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005415 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005416
5417 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005418 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005419
Chris Lattner432cff52009-02-18 04:28:32 +00005420 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005421 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005422 UsualUnaryConversions(RHS);
5423 QualType CondTy = Cond->getType();
5424 QualType LHSTy = LHS->getType();
5425 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005426
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005427 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005428 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005429 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5430 // Throw an error if its not either.
5431 if (getLangOptions().OpenCL) {
5432 if (!CondTy->isVectorType()) {
5433 Diag(Cond->getLocStart(),
5434 diag::err_typecheck_cond_expect_scalar_or_vector)
5435 << CondTy;
5436 return QualType();
5437 }
5438 }
5439 else {
5440 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5441 << CondTy;
5442 return QualType();
5443 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005444 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005445
Chris Lattnere2949f42008-01-06 22:42:25 +00005446 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005447 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5448 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005449
Nate Begemanabb5a732010-09-20 22:41:17 +00005450 // OpenCL: If the condition is a vector, and both operands are scalar,
5451 // attempt to implicity convert them to the vector type to act like the
5452 // built in select.
5453 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5454 // Both operands should be of scalar type.
5455 if (!LHSTy->isScalarType()) {
5456 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5457 << CondTy;
5458 return QualType();
5459 }
5460 if (!RHSTy->isScalarType()) {
5461 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5462 << CondTy;
5463 return QualType();
5464 }
5465 // Implicity convert these scalars to the type of the condition.
5466 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5467 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5468 }
5469
Chris Lattnere2949f42008-01-06 22:42:25 +00005470 // If both operands have arithmetic type, do the usual arithmetic conversions
5471 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005472 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5473 UsualArithmeticConversions(LHS, RHS);
5474 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005475 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005476
Chris Lattnere2949f42008-01-06 22:42:25 +00005477 // If both operands are the same structure or union type, the result is that
5478 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005479 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5480 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005481 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005482 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005483 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005484 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005485 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005486 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005487
Chris Lattnere2949f42008-01-06 22:42:25 +00005488 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005489 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005490 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5491 if (!LHSTy->isVoidType())
5492 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5493 << RHS->getSourceRange();
5494 if (!RHSTy->isVoidType())
5495 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5496 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005497 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5498 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005499 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005500 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005501 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5502 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005503 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005504 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005505 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005506 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005507 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005508 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005509 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005510 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005511 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005512 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005513 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005514
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005515 // All objective-c pointer type analysis is done here.
5516 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5517 QuestionLoc);
5518 if (!compositeType.isNull())
5519 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005520
5521
Steve Naroff05efa972009-07-01 14:36:47 +00005522 // Handle block pointer types.
5523 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5524 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5525 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5526 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005527 ImpCastExprToType(LHS, destType, CK_BitCast);
5528 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005529 return destType;
5530 }
5531 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005532 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005533 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005534 }
Steve Naroff05efa972009-07-01 14:36:47 +00005535 // We have 2 block pointer types.
5536 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5537 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005538 return LHSTy;
5539 }
Steve Naroff05efa972009-07-01 14:36:47 +00005540 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005541 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5542 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005543
Steve Naroff05efa972009-07-01 14:36:47 +00005544 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5545 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005546 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005547 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005548 // In this situation, we assume void* type. No especially good
5549 // reason, but this is what gcc does, and we do have to pick
5550 // to get a consistent AST.
5551 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005552 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5553 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005554 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005555 }
Steve Naroff05efa972009-07-01 14:36:47 +00005556 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005557 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5558 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005559 return LHSTy;
5560 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005561
Steve Naroff05efa972009-07-01 14:36:47 +00005562 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5563 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5564 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005565 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5566 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005567
5568 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5569 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5570 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005571 QualType destPointee
5572 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005573 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005574 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005575 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005576 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005577 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005578 return destType;
5579 }
5580 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005581 QualType destPointee
5582 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005583 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005584 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005585 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005586 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005587 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005588 return destType;
5589 }
5590
5591 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5592 // Two identical pointer types are always compatible.
5593 return LHSTy;
5594 }
5595 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5596 rhptee.getUnqualifiedType())) {
5597 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5598 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5599 // In this situation, we assume void* type. No especially good
5600 // reason, but this is what gcc does, and we do have to pick
5601 // to get a consistent AST.
5602 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005603 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5604 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005605 return incompatTy;
5606 }
5607 // The pointer types are compatible.
5608 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5609 // differently qualified versions of compatible types, the result type is
5610 // a pointer to an appropriately qualified version of the *composite*
5611 // type.
5612 // FIXME: Need to calculate the composite type.
5613 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005614 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5615 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005616 return LHSTy;
5617 }
Mike Stump11289f42009-09-09 15:08:12 +00005618
John McCalle84af4e2010-11-13 01:35:44 +00005619 // GCC compatibility: soften pointer/integer mismatch. Note that
5620 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005621 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5622 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5623 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005624 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005625 return RHSTy;
5626 }
5627 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5628 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5629 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005630 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005631 return LHSTy;
5632 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005633
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005634 // Emit a better diagnostic if one of the expressions is a null pointer
5635 // constant and the other is not a pointer type. In this case, the user most
5636 // likely forgot to take the address of the other expression.
5637 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5638 return QualType();
5639
Chris Lattnere2949f42008-01-06 22:42:25 +00005640 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005641 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5642 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005643 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005644}
5645
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005646/// FindCompositeObjCPointerType - Helper method to find composite type of
5647/// two objective-c pointer types of the two input expressions.
5648QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5649 SourceLocation QuestionLoc) {
5650 QualType LHSTy = LHS->getType();
5651 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005652
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005653 // Handle things like Class and struct objc_class*. Here we case the result
5654 // to the pseudo-builtin, because that will be implicitly cast back to the
5655 // redefinition type if an attempt is made to access its fields.
5656 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005657 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005658 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005659 return LHSTy;
5660 }
5661 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005662 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005663 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005664 return RHSTy;
5665 }
5666 // And the same for struct objc_object* / id
5667 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005668 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005669 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005670 return LHSTy;
5671 }
5672 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005673 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005674 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005675 return RHSTy;
5676 }
5677 // And the same for struct objc_selector* / SEL
5678 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005679 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005680 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005681 return LHSTy;
5682 }
5683 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005684 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005685 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005686 return RHSTy;
5687 }
5688 // Check constraints for Objective-C object pointers types.
5689 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005690
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005691 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5692 // Two identical object pointer types are always compatible.
5693 return LHSTy;
5694 }
5695 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5696 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5697 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005698
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005699 // If both operands are interfaces and either operand can be
5700 // assigned to the other, use that type as the composite
5701 // type. This allows
5702 // xxx ? (A*) a : (B*) b
5703 // where B is a subclass of A.
5704 //
5705 // Additionally, as for assignment, if either type is 'id'
5706 // allow silent coercion. Finally, if the types are
5707 // incompatible then make sure to use 'id' as the composite
5708 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005709
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005710 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5711 // It could return the composite type.
5712 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5713 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5714 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5715 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5716 } else if ((LHSTy->isObjCQualifiedIdType() ||
5717 RHSTy->isObjCQualifiedIdType()) &&
5718 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5719 // Need to handle "id<xx>" explicitly.
5720 // GCC allows qualified id and any Objective-C type to devolve to
5721 // id. Currently localizing to here until clear this should be
5722 // part of ObjCQualifiedIdTypesAreCompatible.
5723 compositeType = Context.getObjCIdType();
5724 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5725 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005726 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005727 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5728 ;
5729 else {
5730 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5731 << LHSTy << RHSTy
5732 << LHS->getSourceRange() << RHS->getSourceRange();
5733 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005734 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5735 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005736 return incompatTy;
5737 }
5738 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005739 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5740 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005741 return compositeType;
5742 }
5743 // Check Objective-C object pointer types and 'void *'
5744 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5745 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5746 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5747 QualType destPointee
5748 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5749 QualType destType = Context.getPointerType(destPointee);
5750 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005751 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005752 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005753 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005754 return destType;
5755 }
5756 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5757 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5758 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5759 QualType destPointee
5760 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5761 QualType destType = Context.getPointerType(destPointee);
5762 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005763 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005764 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005765 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005766 return destType;
5767 }
5768 return QualType();
5769}
5770
Steve Naroff83895f72007-09-16 03:34:24 +00005771/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005772/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005773ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005774 SourceLocation ColonLoc,
5775 Expr *CondExpr, Expr *LHSExpr,
5776 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005777 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5778 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005779 OpaqueValueExpr *opaqueValue = 0;
5780 Expr *commonExpr = 0;
5781 if (LHSExpr == 0) {
5782 commonExpr = CondExpr;
5783
5784 // We usually want to apply unary conversions *before* saving, except
5785 // in the special case of a C++ l-value conditional.
5786 if (!(getLangOptions().CPlusPlus
5787 && !commonExpr->isTypeDependent()
5788 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5789 && commonExpr->isGLValue()
5790 && commonExpr->isOrdinaryOrBitFieldObject()
5791 && RHSExpr->isOrdinaryOrBitFieldObject()
5792 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5793 UsualUnaryConversions(commonExpr);
5794 }
5795
5796 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5797 commonExpr->getType(),
5798 commonExpr->getValueKind(),
5799 commonExpr->getObjectKind());
5800 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005801 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005802
John McCall7decc9e2010-11-18 06:31:45 +00005803 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005804 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005805 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005806 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005807 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005808 return ExprError();
5809
John McCallc07a0c72011-02-17 10:25:35 +00005810 if (!commonExpr)
5811 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5812 LHSExpr, ColonLoc,
5813 RHSExpr, result, VK, OK));
5814
5815 return Owned(new (Context)
5816 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5817 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005818}
5819
John McCallaba90822011-01-31 23:13:11 +00005820// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005821// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005822// routine is it effectively iqnores the qualifiers on the top level pointee.
5823// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5824// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005825static Sema::AssignConvertType
5826checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5827 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5828 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005829
Steve Naroff1f4d7272007-05-11 04:00:31 +00005830 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005831 const Type *lhptee, *rhptee;
5832 Qualifiers lhq, rhq;
5833 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5834 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005835
John McCallaba90822011-01-31 23:13:11 +00005836 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005837
5838 // C99 6.5.16.1p1: This following citation is common to constraints
5839 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5840 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005841 Qualifiers lq;
5842
5843 if (!lhq.compatiblyIncludes(rhq)) {
5844 // Treat address-space mismatches as fatal. TODO: address subspaces
5845 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5846 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5847
John McCall78535952011-03-26 02:56:45 +00005848 // It's okay to add or remove GC qualifiers when converting to
5849 // and from void*.
5850 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
5851 && (lhptee->isVoidType() || rhptee->isVoidType()))
5852 ; // keep old
5853
John McCall4fff8f62011-02-01 00:10:29 +00005854 // For GCC compatibility, other qualifier mismatches are treated
5855 // as still compatible in C.
5856 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5857 }
Steve Naroff3f597292007-05-11 22:18:03 +00005858
Mike Stump4e1f26a2009-02-19 03:04:26 +00005859 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5860 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005861 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005862 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005863 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005864 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005865
Chris Lattner0a788432008-01-03 22:56:36 +00005866 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005867 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005868 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005869 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005870
Chris Lattner0a788432008-01-03 22:56:36 +00005871 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005872 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005873 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005874
5875 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005876 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005877 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005878 }
John McCall4fff8f62011-02-01 00:10:29 +00005879
Mike Stump4e1f26a2009-02-19 03:04:26 +00005880 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005881 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005882 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5883 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005884 // Check if the pointee types are compatible ignoring the sign.
5885 // We explicitly check for char so that we catch "char" vs
5886 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005887 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005888 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005889 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005890 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005891
Chris Lattnerec3a1562009-10-17 20:33:28 +00005892 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005893 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005894 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005895 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005896
John McCall4fff8f62011-02-01 00:10:29 +00005897 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005898 // Types are compatible ignoring the sign. Qualifier incompatibility
5899 // takes priority over sign incompatibility because the sign
5900 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005901 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005902 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005903
John McCallaba90822011-01-31 23:13:11 +00005904 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005905 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005906
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005907 // If we are a multi-level pointer, it's possible that our issue is simply
5908 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5909 // the eventual target type is the same and the pointers have the same
5910 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005911 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005912 do {
John McCall4fff8f62011-02-01 00:10:29 +00005913 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5914 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005915 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005916
John McCall4fff8f62011-02-01 00:10:29 +00005917 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005918 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005919 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005920
Eli Friedman80160bd2009-03-22 23:59:44 +00005921 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005922 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005923 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005924 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005925}
5926
John McCallaba90822011-01-31 23:13:11 +00005927/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005928/// block pointer types are compatible or whether a block and normal pointer
5929/// are compatible. It is more restrict than comparing two function pointer
5930// types.
John McCallaba90822011-01-31 23:13:11 +00005931static Sema::AssignConvertType
5932checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5933 QualType rhsType) {
5934 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5935 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5936
Steve Naroff081c7422008-09-04 15:10:53 +00005937 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005938
Steve Naroff081c7422008-09-04 15:10:53 +00005939 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005940 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5941 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942
John McCallaba90822011-01-31 23:13:11 +00005943 // In C++, the types have to match exactly.
5944 if (S.getLangOptions().CPlusPlus)
5945 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005946
John McCallaba90822011-01-31 23:13:11 +00005947 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005948
Steve Naroff081c7422008-09-04 15:10:53 +00005949 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005950 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5951 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005952
John McCallaba90822011-01-31 23:13:11 +00005953 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5954 return Sema::IncompatibleBlockPointer;
5955
Steve Naroff081c7422008-09-04 15:10:53 +00005956 return ConvTy;
5957}
5958
John McCallaba90822011-01-31 23:13:11 +00005959/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005960/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005961static Sema::AssignConvertType
5962checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5963 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5964 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5965
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005966 if (lhsType->isObjCBuiltinType()) {
5967 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005968 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5969 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005970 return Sema::IncompatiblePointer;
5971 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005972 }
5973 if (rhsType->isObjCBuiltinType()) {
5974 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005975 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5976 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005977 return Sema::IncompatiblePointer;
5978 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005979 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005980 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005981 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005982 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005983 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005984
John McCallaba90822011-01-31 23:13:11 +00005985 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5986 return Sema::CompatiblePointerDiscardsQualifiers;
5987
5988 if (S.Context.typesAreCompatible(lhsType, rhsType))
5989 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005990 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005991 return Sema::IncompatibleObjCQualifiedId;
5992 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005993}
5994
John McCall29600e12010-11-16 02:32:08 +00005995Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005996Sema::CheckAssignmentConstraints(SourceLocation Loc,
5997 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005998 // Fake up an opaque expression. We don't actually care about what
5999 // cast operations are required, so if CheckAssignmentConstraints
6000 // adds casts to this they'll be wasted, but fortunately that doesn't
6001 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006002 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00006003 Expr *rhsPtr = &rhs;
6004 CastKind K = CK_Invalid;
6005
6006 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6007}
6008
Mike Stump4e1f26a2009-02-19 03:04:26 +00006009/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6010/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006011/// pointers. Here are some objectionable examples that GCC considers warnings:
6012///
6013/// int a, *pint;
6014/// short *pshort;
6015/// struct foo *pfoo;
6016///
6017/// pint = pshort; // warning: assignment from incompatible pointer type
6018/// a = pint; // warning: assignment makes integer from pointer without a cast
6019/// pint = a; // warning: assignment makes pointer from integer without a cast
6020/// pint = pfoo; // warning: assignment from incompatible pointer type
6021///
6022/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006023/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006024///
John McCall8cb679e2010-11-15 09:13:47 +00006025/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006026Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00006027Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006028 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00006029 QualType rhsType = rhs->getType();
6030
Chris Lattnera52c2f22008-01-04 23:18:45 +00006031 // Get canonical types. We're not formatting these types, just comparing
6032 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006033 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6034 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006035
John McCalle5255932011-01-31 22:28:28 +00006036 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006037 if (lhsType == rhsType) {
6038 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006039 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006040 }
6041
Douglas Gregor6b754842008-10-28 00:22:11 +00006042 // If the left-hand side is a reference type, then we are in a
6043 // (rare!) case where we've allowed the use of references in C,
6044 // e.g., as a parameter type in a built-in function. In this case,
6045 // just make sure that the type referenced is compatible with the
6046 // right-hand side type. The caller is responsible for adjusting
6047 // lhsType so that the resulting expression does not have reference
6048 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006049 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006050 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6051 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006052 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006053 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006054 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006055 }
John McCalle5255932011-01-31 22:28:28 +00006056
Nate Begemanbd956c42009-06-28 02:36:38 +00006057 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6058 // to the same ExtVector type.
6059 if (lhsType->isExtVectorType()) {
6060 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006061 return Incompatible;
6062 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006063 // CK_VectorSplat does T -> vector T, so first cast to the
6064 // element type.
6065 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6066 if (elType != rhsType) {
6067 Kind = PrepareScalarCast(*this, rhs, elType);
6068 ImpCastExprToType(rhs, elType, Kind);
6069 }
6070 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006071 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006072 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006073 }
Mike Stump11289f42009-09-09 15:08:12 +00006074
John McCalle5255932011-01-31 22:28:28 +00006075 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006076 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006077 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006078 // Allow assignments of an AltiVec vector type to an equivalent GCC
6079 // vector type and vice versa
6080 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6081 Kind = CK_BitCast;
6082 return Compatible;
6083 }
6084
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006085 // If we are allowing lax vector conversions, and LHS and RHS are both
6086 // vectors, the total size only needs to be the same. This is a bitcast;
6087 // no bits are changed but the result type is different.
6088 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006089 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006090 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006091 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006092 }
Chris Lattner881a2122008-01-04 23:32:24 +00006093 }
6094 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006095 }
Eli Friedman3360d892008-05-30 18:07:22 +00006096
John McCalle5255932011-01-31 22:28:28 +00006097 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006098 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006099 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006100 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006101 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006102 }
Eli Friedman3360d892008-05-30 18:07:22 +00006103
John McCalle5255932011-01-31 22:28:28 +00006104 // Conversions to normal pointers.
6105 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6106 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006107 if (isa<PointerType>(rhsType)) {
6108 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006109 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006110 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006111
John McCalle5255932011-01-31 22:28:28 +00006112 // int -> T*
6113 if (rhsType->isIntegerType()) {
6114 Kind = CK_IntegralToPointer; // FIXME: null?
6115 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006116 }
John McCalle5255932011-01-31 22:28:28 +00006117
6118 // C pointers are not compatible with ObjC object pointers,
6119 // with two exceptions:
6120 if (isa<ObjCObjectPointerType>(rhsType)) {
6121 // - conversions to void*
6122 if (lhsPointer->getPointeeType()->isVoidType()) {
6123 Kind = CK_AnyPointerToObjCPointerCast;
6124 return Compatible;
6125 }
6126
6127 // - conversions from 'Class' to the redefinition type
6128 if (rhsType->isObjCClassType() &&
6129 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006130 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006131 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006132 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006133
John McCalle5255932011-01-31 22:28:28 +00006134 Kind = CK_BitCast;
6135 return IncompatiblePointer;
6136 }
6137
6138 // U^ -> void*
6139 if (rhsType->getAs<BlockPointerType>()) {
6140 if (lhsPointer->getPointeeType()->isVoidType()) {
6141 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006142 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006143 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006144 }
John McCalle5255932011-01-31 22:28:28 +00006145
Steve Naroff081c7422008-09-04 15:10:53 +00006146 return Incompatible;
6147 }
6148
John McCalle5255932011-01-31 22:28:28 +00006149 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006150 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006151 // U^ -> T^
6152 if (rhsType->isBlockPointerType()) {
6153 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006154 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006155 }
6156
6157 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006158 if (rhsType->isIntegerType()) {
6159 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006160 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006161 }
6162
John McCalle5255932011-01-31 22:28:28 +00006163 // id -> T^
6164 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6165 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006166 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006167 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006168
John McCalle5255932011-01-31 22:28:28 +00006169 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006170 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006171 if (RHSPT->getPointeeType()->isVoidType()) {
6172 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006173 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006174 }
John McCall8cb679e2010-11-15 09:13:47 +00006175
Chris Lattnera52c2f22008-01-04 23:18:45 +00006176 return Incompatible;
6177 }
6178
John McCalle5255932011-01-31 22:28:28 +00006179 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006180 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006181 // A* -> B*
6182 if (rhsType->isObjCObjectPointerType()) {
6183 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006184 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006185 }
6186
6187 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006188 if (rhsType->isIntegerType()) {
6189 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006190 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006191 }
6192
John McCalle5255932011-01-31 22:28:28 +00006193 // In general, C pointers are not compatible with ObjC object pointers,
6194 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006195 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006196 // - conversions from 'void*'
6197 if (rhsType->isVoidPointerType()) {
6198 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006199 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006200 }
6201
6202 // - conversions to 'Class' from its redefinition type
6203 if (lhsType->isObjCClassType() &&
6204 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6205 Kind = CK_BitCast;
6206 return Compatible;
6207 }
6208
6209 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006210 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006211 }
John McCalle5255932011-01-31 22:28:28 +00006212
6213 // T^ -> A*
6214 if (rhsType->isBlockPointerType()) {
6215 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006216 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006217 }
6218
Steve Naroff7cae42b2009-07-10 23:34:53 +00006219 return Incompatible;
6220 }
John McCalle5255932011-01-31 22:28:28 +00006221
6222 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006223 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006224 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006225 if (lhsType == Context.BoolTy) {
6226 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006227 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006228 }
Eli Friedman3360d892008-05-30 18:07:22 +00006229
John McCalle5255932011-01-31 22:28:28 +00006230 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006231 if (lhsType->isIntegerType()) {
6232 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006233 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235
Chris Lattnera52c2f22008-01-04 23:18:45 +00006236 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006237 }
John McCalle5255932011-01-31 22:28:28 +00006238
6239 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006240 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006241 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006242 if (lhsType == Context.BoolTy) {
6243 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006244 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006245 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006246
John McCalle5255932011-01-31 22:28:28 +00006247 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006248 if (lhsType->isIntegerType()) {
6249 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006250 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006251 }
6252
Steve Naroff7cae42b2009-07-10 23:34:53 +00006253 return Incompatible;
6254 }
Eli Friedman3360d892008-05-30 18:07:22 +00006255
John McCalle5255932011-01-31 22:28:28 +00006256 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006257 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006258 if (Context.typesAreCompatible(lhsType, rhsType)) {
6259 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006260 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006261 }
Bill Wendling216423b2007-05-30 06:30:29 +00006262 }
John McCalle5255932011-01-31 22:28:28 +00006263
Steve Naroff98cf3e92007-06-06 18:38:38 +00006264 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006265}
6266
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006267/// \brief Constructs a transparent union from an expression that is
6268/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006269static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006270 QualType UnionType, FieldDecl *Field) {
6271 // Build an initializer list that designates the appropriate member
6272 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006273 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006274 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006275 SourceLocation());
6276 Initializer->setType(UnionType);
6277 Initializer->setInitializedFieldInUnion(Field);
6278
6279 // Build a compound literal constructing a value of the transparent
6280 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006281 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006282 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006283 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006284}
6285
6286Sema::AssignConvertType
6287Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6288 QualType FromType = rExpr->getType();
6289
Mike Stump11289f42009-09-09 15:08:12 +00006290 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006291 // transparent_union GCC extension.
6292 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006293 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006294 return Incompatible;
6295
6296 // The field to initialize within the transparent union.
6297 RecordDecl *UD = UT->getDecl();
6298 FieldDecl *InitField = 0;
6299 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006300 for (RecordDecl::field_iterator it = UD->field_begin(),
6301 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006302 it != itend; ++it) {
6303 if (it->getType()->isPointerType()) {
6304 // If the transparent union contains a pointer type, we allow:
6305 // 1) void pointer
6306 // 2) null pointer constant
6307 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006308 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006309 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006310 InitField = *it;
6311 break;
6312 }
Mike Stump11289f42009-09-09 15:08:12 +00006313
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006314 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006315 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006316 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006317 InitField = *it;
6318 break;
6319 }
6320 }
6321
John McCall29600e12010-11-16 02:32:08 +00006322 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006323 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006324 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006325 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006326 ImpCastExprToType(rhs, it->getType(), Kind);
6327 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006328 InitField = *it;
6329 break;
6330 }
6331 }
6332
6333 if (!InitField)
6334 return Incompatible;
6335
6336 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6337 return Compatible;
6338}
6339
Chris Lattner9bad62c2008-01-04 18:04:52 +00006340Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006341Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006342 if (getLangOptions().CPlusPlus) {
6343 if (!lhsType->isRecordType()) {
6344 // C++ 5.17p3: If the left operand is not of class type, the
6345 // expression is implicitly converted (C++ 4) to the
6346 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006347 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006348 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006349 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006350 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006351 }
6352
6353 // FIXME: Currently, we fall through and treat C++ classes like C
6354 // structures.
John McCall34376a62010-12-04 03:47:34 +00006355 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006356
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006357 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6358 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006359 if ((lhsType->isPointerType() ||
6360 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006361 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006362 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006363 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006364 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006365 return Compatible;
6366 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006367
Chris Lattnere6dcd502007-10-16 02:55:40 +00006368 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006369 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006370 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006371 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006372 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006373 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006374 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006375 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006376
John McCall8cb679e2010-11-15 09:13:47 +00006377 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006378 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006379 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006380
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006381 // C99 6.5.16.1p2: The value of the right operand is converted to the
6382 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006383 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6384 // so that we can use references in built-in functions even in C.
6385 // The getNonReferenceType() call makes sure that the resulting expression
6386 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006387 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006388 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006389 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006390}
6391
Chris Lattner326f7572008-11-18 01:30:42 +00006392QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006393 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006394 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006395 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006396 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006397}
6398
Chris Lattnerfaa54172010-01-12 21:23:57 +00006399QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006400 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006401 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006402 QualType lhsType =
6403 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6404 QualType rhsType =
6405 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006406
Nate Begeman191a6b12008-07-14 18:02:46 +00006407 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006408 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006409 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006410
Nate Begeman191a6b12008-07-14 18:02:46 +00006411 // Handle the case of a vector & extvector type of the same size and element
6412 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006413 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006414 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006415 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006416 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006417 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006418 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006419 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006420 return lhsType;
6421 }
6422
John McCalle3027922010-08-25 11:45:40 +00006423 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006424 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006425 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6426 // If we are allowing lax vector conversions, and LHS and RHS are both
6427 // vectors, the total size only needs to be the same. This is a
6428 // bitcast; no bits are changed but the result type is different.
6429 ImpCastExprToType(rex, lhsType, CK_BitCast);
6430 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006431 }
Eric Christophera613f562010-08-26 00:42:16 +00006432 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006433 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006434 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006435
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006436 // Handle the case of equivalent AltiVec and GCC vector types
6437 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6438 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006439 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006440 return rhsType;
6441 }
6442
Nate Begemanbd956c42009-06-28 02:36:38 +00006443 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6444 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6445 bool swapped = false;
6446 if (rhsType->isExtVectorType()) {
6447 swapped = true;
6448 std::swap(rex, lex);
6449 std::swap(rhsType, lhsType);
6450 }
Mike Stump11289f42009-09-09 15:08:12 +00006451
Nate Begeman886448d2009-06-28 19:12:57 +00006452 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006453 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006454 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006455 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006456 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6457 if (order > 0)
6458 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6459 if (order >= 0) {
6460 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006461 if (swapped) std::swap(rex, lex);
6462 return lhsType;
6463 }
6464 }
6465 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6466 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006467 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6468 if (order > 0)
6469 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6470 if (order >= 0) {
6471 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006472 if (swapped) std::swap(rex, lex);
6473 return lhsType;
6474 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006475 }
6476 }
Mike Stump11289f42009-09-09 15:08:12 +00006477
Nate Begeman886448d2009-06-28 19:12:57 +00006478 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006479 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006480 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006481 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006482 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006483}
6484
Chris Lattnerfaa54172010-01-12 21:23:57 +00006485QualType Sema::CheckMultiplyDivideOperands(
6486 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006487 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006488 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006489
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006490 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Chris Lattnerfaa54172010-01-12 21:23:57 +00006492 if (!lex->getType()->isArithmeticType() ||
6493 !rex->getType()->isArithmeticType())
6494 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006495
Chris Lattnerfaa54172010-01-12 21:23:57 +00006496 // Check for division by zero.
6497 if (isDiv &&
6498 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006499 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6500 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006501
Chris Lattnerfaa54172010-01-12 21:23:57 +00006502 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006503}
6504
Chris Lattnerfaa54172010-01-12 21:23:57 +00006505QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006506 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006507 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006508 if (lex->getType()->hasIntegerRepresentation() &&
6509 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006510 return CheckVectorOperands(Loc, lex, rex);
6511 return InvalidOperands(Loc, lex, rex);
6512 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006513
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006514 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006515
Chris Lattnerfaa54172010-01-12 21:23:57 +00006516 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6517 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006518
Chris Lattnerfaa54172010-01-12 21:23:57 +00006519 // Check for remainder by zero.
6520 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006521 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6522 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006523
Chris Lattnerfaa54172010-01-12 21:23:57 +00006524 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006525}
6526
Chris Lattnerfaa54172010-01-12 21:23:57 +00006527QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006528 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006529 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6530 QualType compType = CheckVectorOperands(Loc, lex, rex);
6531 if (CompLHSTy) *CompLHSTy = compType;
6532 return compType;
6533 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006534
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006535 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006536
Steve Naroffe4718892007-04-27 18:30:00 +00006537 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006538 if (lex->getType()->isArithmeticType() &&
6539 rex->getType()->isArithmeticType()) {
6540 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006541 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006542 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006543
Eli Friedman8e122982008-05-18 18:08:51 +00006544 // Put any potential pointer into PExp
6545 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006546 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006547 std::swap(PExp, IExp);
6548
Steve Naroff6b712a72009-07-14 18:25:06 +00006549 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006550
Eli Friedman8e122982008-05-18 18:08:51 +00006551 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006552 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006553
Chris Lattner12bdebb2009-04-24 23:50:08 +00006554 // Check for arithmetic on pointers to incomplete types.
6555 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006556 if (getLangOptions().CPlusPlus) {
6557 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006558 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006559 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006560 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006561
6562 // GNU extension: arithmetic on pointer to void
6563 Diag(Loc, diag::ext_gnu_void_ptr)
6564 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006565 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006566 if (getLangOptions().CPlusPlus) {
6567 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6568 << lex->getType() << lex->getSourceRange();
6569 return QualType();
6570 }
6571
6572 // GNU extension: arithmetic on pointer to function
6573 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6574 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006575 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006576 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006577 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006578 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006579 PExp->getType()->isObjCObjectPointerType()) &&
6580 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006581 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6582 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006583 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006584 return QualType();
6585 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006586 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006587 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006588 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6589 << PointeeTy << PExp->getSourceRange();
6590 return QualType();
6591 }
Mike Stump11289f42009-09-09 15:08:12 +00006592
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006593 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006594 QualType LHSTy = Context.isPromotableBitField(lex);
6595 if (LHSTy.isNull()) {
6596 LHSTy = lex->getType();
6597 if (LHSTy->isPromotableIntegerType())
6598 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006599 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006600 *CompLHSTy = LHSTy;
6601 }
Eli Friedman8e122982008-05-18 18:08:51 +00006602 return PExp->getType();
6603 }
6604 }
6605
Chris Lattner326f7572008-11-18 01:30:42 +00006606 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006607}
6608
Chris Lattner2a3569b2008-04-07 05:30:13 +00006609// C99 6.5.6
6610QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006611 SourceLocation Loc, QualType* CompLHSTy) {
6612 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6613 QualType compType = CheckVectorOperands(Loc, lex, rex);
6614 if (CompLHSTy) *CompLHSTy = compType;
6615 return compType;
6616 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006617
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006618 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006619
Chris Lattner4d62f422007-12-09 21:53:25 +00006620 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006621
Chris Lattner4d62f422007-12-09 21:53:25 +00006622 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006623 if (lex->getType()->isArithmeticType()
6624 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006625 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006626 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattner4d62f422007-12-09 21:53:25 +00006629 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006630 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006631 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006632
Douglas Gregorac1fb652009-03-24 19:52:54 +00006633 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006634
Douglas Gregorac1fb652009-03-24 19:52:54 +00006635 bool ComplainAboutVoid = false;
6636 Expr *ComplainAboutFunc = 0;
6637 if (lpointee->isVoidType()) {
6638 if (getLangOptions().CPlusPlus) {
6639 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6640 << lex->getSourceRange() << rex->getSourceRange();
6641 return QualType();
6642 }
6643
6644 // GNU C extension: arithmetic on pointer to void
6645 ComplainAboutVoid = true;
6646 } else if (lpointee->isFunctionType()) {
6647 if (getLangOptions().CPlusPlus) {
6648 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006649 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006650 return QualType();
6651 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006652
6653 // GNU C extension: arithmetic on pointer to function
6654 ComplainAboutFunc = lex;
6655 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006656 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006657 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006658 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006659 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006660 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006661
Chris Lattner12bdebb2009-04-24 23:50:08 +00006662 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006663 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006664 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6665 << lpointee << lex->getSourceRange();
6666 return QualType();
6667 }
Mike Stump11289f42009-09-09 15:08:12 +00006668
Chris Lattner4d62f422007-12-09 21:53:25 +00006669 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006670 if (rex->getType()->isIntegerType()) {
6671 if (ComplainAboutVoid)
6672 Diag(Loc, diag::ext_gnu_void_ptr)
6673 << lex->getSourceRange() << rex->getSourceRange();
6674 if (ComplainAboutFunc)
6675 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006676 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006677 << ComplainAboutFunc->getSourceRange();
6678
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006679 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006680 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006681 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682
Chris Lattner4d62f422007-12-09 21:53:25 +00006683 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006684 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006685 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006686
Douglas Gregorac1fb652009-03-24 19:52:54 +00006687 // RHS must be a completely-type object type.
6688 // Handle the GNU void* extension.
6689 if (rpointee->isVoidType()) {
6690 if (getLangOptions().CPlusPlus) {
6691 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6692 << lex->getSourceRange() << rex->getSourceRange();
6693 return QualType();
6694 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006695
Douglas Gregorac1fb652009-03-24 19:52:54 +00006696 ComplainAboutVoid = true;
6697 } else if (rpointee->isFunctionType()) {
6698 if (getLangOptions().CPlusPlus) {
6699 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006700 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006701 return QualType();
6702 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006703
6704 // GNU extension: arithmetic on pointer to function
6705 if (!ComplainAboutFunc)
6706 ComplainAboutFunc = rex;
6707 } else if (!rpointee->isDependentType() &&
6708 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006709 PDiag(diag::err_typecheck_sub_ptr_object)
6710 << rex->getSourceRange()
6711 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006712 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006713
Eli Friedman168fe152009-05-16 13:54:38 +00006714 if (getLangOptions().CPlusPlus) {
6715 // Pointee types must be the same: C++ [expr.add]
6716 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6717 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6718 << lex->getType() << rex->getType()
6719 << lex->getSourceRange() << rex->getSourceRange();
6720 return QualType();
6721 }
6722 } else {
6723 // Pointee types must be compatible C99 6.5.6p3
6724 if (!Context.typesAreCompatible(
6725 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6726 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6727 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6728 << lex->getType() << rex->getType()
6729 << lex->getSourceRange() << rex->getSourceRange();
6730 return QualType();
6731 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006732 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006733
Douglas Gregorac1fb652009-03-24 19:52:54 +00006734 if (ComplainAboutVoid)
6735 Diag(Loc, diag::ext_gnu_void_ptr)
6736 << lex->getSourceRange() << rex->getSourceRange();
6737 if (ComplainAboutFunc)
6738 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006739 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006740 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006741
6742 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006743 return Context.getPointerDiffType();
6744 }
6745 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006746
Chris Lattner326f7572008-11-18 01:30:42 +00006747 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006748}
6749
Douglas Gregor0bf31402010-10-08 23:50:27 +00006750static bool isScopedEnumerationType(QualType T) {
6751 if (const EnumType *ET = dyn_cast<EnumType>(T))
6752 return ET->getDecl()->isScoped();
6753 return false;
6754}
6755
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006756static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6757 SourceLocation Loc, unsigned Opc,
6758 QualType LHSTy) {
6759 llvm::APSInt Right;
6760 // Check right/shifter operand
6761 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6762 return;
6763
6764 if (Right.isNegative()) {
Ted Kremenek63657fe2011-03-01 18:09:31 +00006765 S.DiagRuntimeBehavior(Loc, rex,
6766 S.PDiag(diag::warn_shift_negative)
6767 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006768 return;
6769 }
6770 llvm::APInt LeftBits(Right.getBitWidth(),
6771 S.Context.getTypeSize(lex->getType()));
6772 if (Right.uge(LeftBits)) {
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006773 S.DiagRuntimeBehavior(Loc, rex,
6774 S.PDiag(diag::warn_shift_gt_typewidth)
6775 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006776 return;
6777 }
6778 if (Opc != BO_Shl)
6779 return;
6780
6781 // When left shifting an ICE which is signed, we can check for overflow which
6782 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6783 // integers have defined behavior modulo one more than the maximum value
6784 // representable in the result type, so never warn for those.
6785 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006786 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006787 LHSTy->hasUnsignedIntegerRepresentation())
6788 return;
6789 llvm::APInt ResultBits =
6790 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6791 if (LeftBits.uge(ResultBits))
6792 return;
6793 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6794 Result = Result.shl(Right);
6795
6796 // If we are only missing a sign bit, this is less likely to result in actual
6797 // bugs -- if the result is cast back to an unsigned type, it will have the
6798 // expected value. Thus we place this behind a different warning that can be
6799 // turned off separately if needed.
6800 if (LeftBits == ResultBits - 1) {
6801 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6802 << Result.toString(10) << LHSTy
6803 << lex->getSourceRange() << rex->getSourceRange();
6804 return;
6805 }
6806
6807 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6808 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6809 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6810}
6811
Chris Lattner2a3569b2008-04-07 05:30:13 +00006812// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006813QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006814 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006815 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006816 if (!lex->getType()->hasIntegerRepresentation() ||
6817 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006818 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006819
Douglas Gregor0bf31402010-10-08 23:50:27 +00006820 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6821 // hasIntegerRepresentation() above instead of this.
6822 if (isScopedEnumerationType(lex->getType()) ||
6823 isScopedEnumerationType(rex->getType())) {
6824 return InvalidOperands(Loc, lex, rex);
6825 }
6826
Nate Begemane46ee9a2009-10-25 02:26:48 +00006827 // Vector shifts promote their scalar inputs to vector type.
6828 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6829 return CheckVectorOperands(Loc, lex, rex);
6830
Chris Lattner5c11c412007-12-12 05:47:28 +00006831 // Shifts don't perform usual arithmetic conversions, they just do integer
6832 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006833
John McCall57cdd882010-12-16 19:28:59 +00006834 // For the LHS, do usual unary conversions, but then reset them away
6835 // if this is a compound assignment.
6836 Expr *old_lex = lex;
6837 UsualUnaryConversions(lex);
6838 QualType LHSTy = lex->getType();
6839 if (isCompAssign) lex = old_lex;
6840
6841 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006842 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006843
Ryan Flynnf53fab82009-08-07 16:20:20 +00006844 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006845 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006846
Chris Lattner5c11c412007-12-12 05:47:28 +00006847 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006848 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006849}
6850
Chandler Carruth17773fc2010-07-10 12:30:03 +00006851static bool IsWithinTemplateSpecialization(Decl *D) {
6852 if (DeclContext *DC = D->getDeclContext()) {
6853 if (isa<ClassTemplateSpecializationDecl>(DC))
6854 return true;
6855 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6856 return FD->isFunctionTemplateSpecialization();
6857 }
6858 return false;
6859}
6860
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006861// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006862QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006863 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006864 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006865
Chris Lattner9a152e22009-12-05 05:40:13 +00006866 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006867 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006868 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006869
Steve Naroff31090012007-07-16 21:54:35 +00006870 QualType lType = lex->getType();
6871 QualType rType = rex->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006872
Chandler Carruth712563b2011-02-17 08:37:06 +00006873 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6874 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6875 QualType LHSStrippedType = LHSStripped->getType();
6876 QualType RHSStrippedType = RHSStripped->getType();
6877
Douglas Gregor1beec452011-03-12 01:48:56 +00006878
6879
Chandler Carruth712563b2011-02-17 08:37:06 +00006880 // Two different enums will raise a warning when compared.
6881 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6882 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6883 if (LHSEnumType->getDecl()->getIdentifier() &&
6884 RHSEnumType->getDecl()->getIdentifier() &&
6885 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6886 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6887 << LHSStrippedType << RHSStrippedType
6888 << lex->getSourceRange() << rex->getSourceRange();
6889 }
6890 }
6891 }
6892
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006893 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006894 !(lType->isBlockPointerType() && isRelational) &&
6895 !lex->getLocStart().isMacroID() &&
6896 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006897 // For non-floating point types, check for self-comparisons of the form
6898 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6899 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006900 //
6901 // NOTE: Don't warn about comparison expressions resulting from macro
6902 // expansion. Also don't warn about comparisons which are only self
6903 // comparisons within a template specialization. The warnings should catch
6904 // obvious cases in the definition of the template anyways. The idea is to
6905 // warn when the typed comparison operator will always evaluate to the same
6906 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006907 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006908 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006909 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006910 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006911 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006912 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006913 << (Opc == BO_EQ
6914 || Opc == BO_LE
6915 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006916 } else if (lType->isArrayType() && rType->isArrayType() &&
6917 !DRL->getDecl()->getType()->isReferenceType() &&
6918 !DRR->getDecl()->getType()->isReferenceType()) {
6919 // what is it always going to eval to?
6920 char always_evals_to;
6921 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006922 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006923 always_evals_to = 0; // false
6924 break;
John McCalle3027922010-08-25 11:45:40 +00006925 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006926 always_evals_to = 1; // true
6927 break;
6928 default:
6929 // best we can say is 'a constant'
6930 always_evals_to = 2; // e.g. array1 <= array2
6931 break;
6932 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006933 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006934 << 1 // array
6935 << always_evals_to);
6936 }
6937 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006938 }
Mike Stump11289f42009-09-09 15:08:12 +00006939
Chris Lattner222b8bd2009-03-08 19:39:53 +00006940 if (isa<CastExpr>(LHSStripped))
6941 LHSStripped = LHSStripped->IgnoreParenCasts();
6942 if (isa<CastExpr>(RHSStripped))
6943 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006944
Chris Lattner222b8bd2009-03-08 19:39:53 +00006945 // Warn about comparisons against a string constant (unless the other
6946 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006947 Expr *literalString = 0;
6948 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006949 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006950 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006951 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006952 literalString = lex;
6953 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006954 } else if ((isa<StringLiteral>(RHSStripped) ||
6955 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006956 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006957 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006958 literalString = rex;
6959 literalStringStripped = RHSStripped;
6960 }
6961
6962 if (literalString) {
6963 std::string resultComparison;
6964 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006965 case BO_LT: resultComparison = ") < 0"; break;
6966 case BO_GT: resultComparison = ") > 0"; break;
6967 case BO_LE: resultComparison = ") <= 0"; break;
6968 case BO_GE: resultComparison = ") >= 0"; break;
6969 case BO_EQ: resultComparison = ") == 0"; break;
6970 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006971 default: assert(false && "Invalid comparison operator");
6972 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006973
Ted Kremenek3427fac2011-02-23 01:52:04 +00006974 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006975 PDiag(diag::warn_stringcompare)
6976 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006977 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006978 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006979 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006980
Douglas Gregorec170db2010-06-08 19:50:34 +00006981 // C99 6.5.8p3 / C99 6.5.9p4
6982 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6983 UsualArithmeticConversions(lex, rex);
6984 else {
6985 UsualUnaryConversions(lex);
6986 UsualUnaryConversions(rex);
6987 }
6988
6989 lType = lex->getType();
6990 rType = rex->getType();
6991
Douglas Gregorca63811b2008-11-19 03:25:36 +00006992 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006993 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006994
Chris Lattnerb620c342007-08-26 01:18:55 +00006995 if (isRelational) {
6996 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006997 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006998 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006999 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007000 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007001 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007002
Chris Lattnerb620c342007-08-26 01:18:55 +00007003 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007004 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007005 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007006
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007007 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007008 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007009 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007010 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007011
Douglas Gregorf267edd2010-06-15 21:38:40 +00007012 // All of the following pointer-related warnings are GCC extensions, except
7013 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007014 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007015 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007016 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007017 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007018 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007019
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007020 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007021 if (LCanPointeeTy == RCanPointeeTy)
7022 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007023 if (!isRelational &&
7024 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7025 // Valid unless comparison between non-null pointer and function pointer
7026 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007027 // In a SFINAE context, we treat this as a hard error to maintain
7028 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007029 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7030 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007031 Diag(Loc,
7032 isSFINAEContext()?
7033 diag::err_typecheck_comparison_of_fptr_to_void
7034 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007035 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007036
7037 if (isSFINAEContext())
7038 return QualType();
7039
John McCalle3027922010-08-25 11:45:40 +00007040 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007041 return ResultTy;
7042 }
7043 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007044
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007045 // C++ [expr.rel]p2:
7046 // [...] Pointer conversions (4.10) and qualification
7047 // conversions (4.4) are performed on pointer operands (or on
7048 // a pointer operand and a null pointer constant) to bring
7049 // them to their composite pointer type. [...]
7050 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007051 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007052 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007053 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007054 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007055 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007056 if (T.isNull()) {
7057 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7058 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7059 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007060 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007061 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007062 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007063 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007064 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007065 }
7066
John McCalle3027922010-08-25 11:45:40 +00007067 ImpCastExprToType(lex, T, CK_BitCast);
7068 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007069 return ResultTy;
7070 }
Eli Friedman16c209612009-08-23 00:27:47 +00007071 // C99 6.5.9p2 and C99 6.5.8p2
7072 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7073 RCanPointeeTy.getUnqualifiedType())) {
7074 // Valid unless a relational comparison of function pointers
7075 if (isRelational && LCanPointeeTy->isFunctionType()) {
7076 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7077 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7078 }
7079 } else if (!isRelational &&
7080 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7081 // Valid unless comparison between non-null pointer and function pointer
7082 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7083 && !LHSIsNull && !RHSIsNull) {
7084 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7085 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7086 }
7087 } else {
7088 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007089 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007090 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007091 }
John McCall7684dde2011-03-11 04:25:25 +00007092 if (LCanPointeeTy != RCanPointeeTy) {
7093 if (LHSIsNull && !RHSIsNull)
7094 ImpCastExprToType(lex, rType, CK_BitCast);
7095 else
7096 ImpCastExprToType(rex, lType, CK_BitCast);
7097 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007098 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007099 }
Mike Stump11289f42009-09-09 15:08:12 +00007100
Sebastian Redl576fd422009-05-10 18:38:11 +00007101 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007102 // Comparison of nullptr_t with itself.
7103 if (lType->isNullPtrType() && rType->isNullPtrType())
7104 return ResultTy;
7105
Mike Stump11289f42009-09-09 15:08:12 +00007106 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007107 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007108 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007109 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007110 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007111 ImpCastExprToType(rex, lType,
7112 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007113 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007114 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007115 return ResultTy;
7116 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007117 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007118 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007119 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007120 ImpCastExprToType(lex, rType,
7121 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007122 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007123 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007124 return ResultTy;
7125 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007126
7127 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007128 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007129 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7130 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007131 // In addition, pointers to members can be compared, or a pointer to
7132 // member and a null pointer constant. Pointer to member conversions
7133 // (4.11) and qualification conversions (4.4) are performed to bring
7134 // them to a common type. If one operand is a null pointer constant,
7135 // the common type is the type of the other operand. Otherwise, the
7136 // common type is a pointer to member type similar (4.4) to the type
7137 // of one of the operands, with a cv-qualification signature (4.4)
7138 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007139 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007140 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007141 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007142 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007143 if (T.isNull()) {
7144 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007145 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007146 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007147 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007148 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007149 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007150 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007151 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007152 }
Mike Stump11289f42009-09-09 15:08:12 +00007153
John McCalle3027922010-08-25 11:45:40 +00007154 ImpCastExprToType(lex, T, CK_BitCast);
7155 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007156 return ResultTy;
7157 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007158
7159 // Handle scoped enumeration types specifically, since they don't promote
7160 // to integers.
7161 if (lex->getType()->isEnumeralType() &&
7162 Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
7163 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007164 }
Mike Stump11289f42009-09-09 15:08:12 +00007165
Steve Naroff081c7422008-09-04 15:10:53 +00007166 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007167 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007168 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7169 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007170
Steve Naroff081c7422008-09-04 15:10:53 +00007171 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007172 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007173 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007174 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007175 }
John McCalle3027922010-08-25 11:45:40 +00007176 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007177 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007178 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007179 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007180 if (!isRelational
7181 && ((lType->isBlockPointerType() && rType->isPointerType())
7182 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007183 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007184 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007185 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007186 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007187 ->getPointeeType()->isVoidType())))
7188 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7189 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007190 }
John McCall7684dde2011-03-11 04:25:25 +00007191 if (LHSIsNull && !RHSIsNull)
7192 ImpCastExprToType(lex, rType, CK_BitCast);
7193 else
7194 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007195 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007196 }
Steve Naroff081c7422008-09-04 15:10:53 +00007197
John McCall7684dde2011-03-11 04:25:25 +00007198 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7199 const PointerType *LPT = lType->getAs<PointerType>();
7200 const PointerType *RPT = rType->getAs<PointerType>();
7201 if (LPT || RPT) {
7202 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7203 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007204
Steve Naroff753567f2008-11-17 19:49:16 +00007205 if (!LPtrToVoid && !RPtrToVoid &&
7206 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007207 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007208 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007209 }
John McCall7684dde2011-03-11 04:25:25 +00007210 if (LHSIsNull && !RHSIsNull)
7211 ImpCastExprToType(lex, rType, CK_BitCast);
7212 else
7213 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007214 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007215 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007216 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007217 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007218 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7219 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007220 if (LHSIsNull && !RHSIsNull)
7221 ImpCastExprToType(lex, rType, CK_BitCast);
7222 else
7223 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007224 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007225 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007226 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007227 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7228 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007229 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007230 bool isError = false;
7231 if ((LHSIsNull && lType->isIntegerType()) ||
7232 (RHSIsNull && rType->isIntegerType())) {
7233 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007234 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007235 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007236 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007237 else if (getLangOptions().CPlusPlus) {
7238 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7239 isError = true;
7240 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007241 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007242
Chris Lattnerd99bd522009-08-23 00:03:44 +00007243 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007244 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007245 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007246 if (isError)
7247 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007248 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007249
7250 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007251 ImpCastExprToType(lex, rType,
7252 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007253 else
John McCalle84af4e2010-11-13 01:35:44 +00007254 ImpCastExprToType(rex, lType,
7255 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007256 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007257 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007258
Steve Naroff4b191572008-09-04 16:56:14 +00007259 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007260 if (!isRelational && RHSIsNull
7261 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007262 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007263 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007264 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007265 if (!isRelational && LHSIsNull
7266 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007267 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007268 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007269 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007270
Chris Lattner326f7572008-11-18 01:30:42 +00007271 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007272}
7273
Nate Begeman191a6b12008-07-14 18:02:46 +00007274/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007275/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007276/// like a scalar comparison, a vector comparison produces a vector of integer
7277/// types.
7278QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007279 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007280 bool isRelational) {
7281 // Check to make sure we're operating on vectors of the same type and width,
7282 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007283 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007284 if (vType.isNull())
7285 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007286
Nate Begeman191a6b12008-07-14 18:02:46 +00007287 QualType lType = lex->getType();
7288 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007289
Anton Yartsev530deb92011-03-27 15:36:07 +00007290 // If AltiVec, the comparison results in a numeric type, i.e.
7291 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007292 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007293 return Context.getLogicalOperationType();
7294
Nate Begeman191a6b12008-07-14 18:02:46 +00007295 // For non-floating point types, check for self-comparisons of the form
7296 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7297 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007298 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007299 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7300 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7301 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007302 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007303 PDiag(diag::warn_comparison_always)
7304 << 0 // self-
7305 << 2 // "a constant"
7306 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007307 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007308
Nate Begeman191a6b12008-07-14 18:02:46 +00007309 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007310 if (!isRelational && lType->hasFloatingRepresentation()) {
7311 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007312 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007313 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007314
Nate Begeman191a6b12008-07-14 18:02:46 +00007315 // Return the type for the comparison, which is the same as vector type for
7316 // integer vectors, or an integer type of identical size and number of
7317 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007318 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007319 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007320
John McCall9dd450b2009-09-21 23:43:11 +00007321 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007322 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007323 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007324 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007325 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007326 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7327
Mike Stump4e1f26a2009-02-19 03:04:26 +00007328 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007329 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007330 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7331}
7332
Steve Naroff218bc2b2007-05-04 21:54:46 +00007333inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007334 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7336 if (lex->getType()->hasIntegerRepresentation() &&
7337 rex->getType()->hasIntegerRepresentation())
7338 return CheckVectorOperands(Loc, lex, rex);
7339
7340 return InvalidOperands(Loc, lex, rex);
7341 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007342
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007343 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007344
Douglas Gregor0bf31402010-10-08 23:50:27 +00007345 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7346 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007347 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007348 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007349}
7350
Steve Naroff218bc2b2007-05-04 21:54:46 +00007351inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007352 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7353
7354 // Diagnose cases where the user write a logical and/or but probably meant a
7355 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7356 // is a constant.
7357 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007358 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007359 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007360 !Loc.isMacroID()) {
7361 // If the RHS can be constant folded, and if it constant folds to something
7362 // that isn't 0 or 1 (which indicate a potential logical operation that
7363 // happened to fold to true/false) then warn.
7364 Expr::EvalResult Result;
7365 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7366 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7367 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7368 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007369 << (Opc == BO_LAnd ? "&&" : "||")
7370 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007371 }
7372 }
Chris Lattner8406c512010-07-13 19:41:32 +00007373
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007374 if (!Context.getLangOptions().CPlusPlus) {
7375 UsualUnaryConversions(lex);
7376 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007377
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007378 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7379 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007380
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007381 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007382 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007383
John McCall4a2429a2010-06-04 00:29:51 +00007384 // The following is safe because we only use this method for
7385 // non-overloadable operands.
7386
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007387 // C++ [expr.log.and]p1
7388 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007389 // The operands are both contextually converted to type bool.
7390 if (PerformContextuallyConvertToBool(lex) ||
7391 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007392 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007393
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007394 // C++ [expr.log.and]p2
7395 // C++ [expr.log.or]p2
7396 // The result is a bool.
7397 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007398}
7399
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007400/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7401/// is a read-only property; return true if so. A readonly property expression
7402/// depends on various declarations and thus must be treated specially.
7403///
Mike Stump11289f42009-09-09 15:08:12 +00007404static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007405 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7406 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007407 if (PropExpr->isImplicitProperty()) return false;
7408
7409 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7410 QualType BaseType = PropExpr->isSuperReceiver() ?
7411 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007412 PropExpr->getBase()->getType();
7413
John McCallb7bd14f2010-12-02 01:19:52 +00007414 if (const ObjCObjectPointerType *OPT =
7415 BaseType->getAsObjCInterfacePointerType())
7416 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7417 if (S.isPropertyReadonly(PDecl, IFace))
7418 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007419 }
7420 return false;
7421}
7422
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007423static bool IsConstProperty(Expr *E, Sema &S) {
7424 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7425 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7426 if (PropExpr->isImplicitProperty()) return false;
7427
7428 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7429 QualType T = PDecl->getType();
7430 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007431 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007432 CanQualType CT = S.Context.getCanonicalType(T);
7433 return CT.isConstQualified();
7434 }
7435 return false;
7436}
7437
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007438static bool IsReadonlyMessage(Expr *E, Sema &S) {
7439 if (E->getStmtClass() != Expr::MemberExprClass)
7440 return false;
7441 const MemberExpr *ME = cast<MemberExpr>(E);
7442 NamedDecl *Member = ME->getMemberDecl();
7443 if (isa<FieldDecl>(Member)) {
7444 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7445 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7446 return false;
7447 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7448 }
7449 return false;
7450}
7451
Chris Lattner30bd3272008-11-18 01:22:49 +00007452/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7453/// emit an error and return true. If so, return false.
7454static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007455 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007456 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007457 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007458 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7459 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007460 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7461 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007462 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7463 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007464 if (IsLV == Expr::MLV_Valid)
7465 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007466
Chris Lattner30bd3272008-11-18 01:22:49 +00007467 unsigned Diag = 0;
7468 bool NeedType = false;
7469 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007470 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007471 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007472 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7473 NeedType = true;
7474 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007475 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007476 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7477 NeedType = true;
7478 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007479 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007480 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7481 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007482 case Expr::MLV_Valid:
7483 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007484 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007485 case Expr::MLV_MemberFunction:
7486 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007487 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7488 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007489 case Expr::MLV_IncompleteType:
7490 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007491 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007492 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007493 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007494 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007495 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7496 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007497 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007498 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7499 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007500 case Expr::MLV_ReadonlyProperty:
7501 Diag = diag::error_readonly_property_assignment;
7502 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007503 case Expr::MLV_NoSetterProperty:
7504 Diag = diag::error_nosetter_property_assignment;
7505 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007506 case Expr::MLV_InvalidMessageExpression:
7507 Diag = diag::error_readonly_message_assignment;
7508 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007509 case Expr::MLV_SubObjCPropertySetting:
7510 Diag = diag::error_no_subobject_property_setting;
7511 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007512 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007513
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007514 SourceRange Assign;
7515 if (Loc != OrigLoc)
7516 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007517 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007518 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007519 else
Mike Stump11289f42009-09-09 15:08:12 +00007520 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007521 return true;
7522}
7523
7524
7525
7526// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007527QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7528 SourceLocation Loc,
7529 QualType CompoundType) {
7530 // Verify that LHS is a modifiable lvalue, and emit error if not.
7531 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007532 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007533
7534 QualType LHSType = LHS->getType();
7535 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007536 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007537 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007538 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007539 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007540 if (LHS->getObjectKind() == OK_ObjCProperty)
7541 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007542 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007543 // Special case of NSObject attributes on c-style pointer types.
7544 if (ConvTy == IncompatiblePointer &&
7545 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007546 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007547 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007548 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007549 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007550
John McCall7decc9e2010-11-18 06:31:45 +00007551 if (ConvTy == Compatible &&
7552 getLangOptions().ObjCNonFragileABI &&
7553 LHSType->isObjCObjectType())
7554 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7555 << LHSType;
7556
Chris Lattnerea714382008-08-21 18:04:13 +00007557 // If the RHS is a unary plus or minus, check to see if they = and + are
7558 // right next to each other. If so, the user may have typo'd "x =+ 4"
7559 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007560 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007561 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7562 RHSCheck = ICE->getSubExpr();
7563 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007564 if ((UO->getOpcode() == UO_Plus ||
7565 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007566 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007567 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007568 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7569 // And there is a space or other character before the subexpr of the
7570 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007571 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7572 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007573 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007574 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007575 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007576 }
Chris Lattnerea714382008-08-21 18:04:13 +00007577 }
7578 } else {
7579 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007580 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007581 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007582
Chris Lattner326f7572008-11-18 01:30:42 +00007583 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007584 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007585 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007586
Chris Lattner39561062010-07-07 06:14:23 +00007587
7588 // Check to see if the destination operand is a dereferenced null pointer. If
7589 // so, and if not volatile-qualified, this is undefined behavior that the
7590 // optimizer will delete, so warn about it. People sometimes try to use this
7591 // to get a deterministic trap and are surprised by clang's behavior. This
7592 // only handles the pattern "*null = whatever", which is a very syntactic
7593 // check.
7594 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007595 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007596 UO->getSubExpr()->IgnoreParenCasts()->
7597 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7598 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007599 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7600 PDiag(diag::warn_indirection_through_null)
7601 << UO->getSubExpr()->getSourceRange());
7602 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7603 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007604 }
7605
Ted Kremenek64699be2011-02-16 01:57:07 +00007606 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007607 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007608
Steve Naroff98cf3e92007-06-06 18:38:38 +00007609 // C99 6.5.16p3: The type of an assignment expression is the type of the
7610 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007611 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007612 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7613 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007614 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007615 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007616 return (getLangOptions().CPlusPlus
7617 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007618}
7619
Chris Lattner326f7572008-11-18 01:30:42 +00007620// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007621static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007622 SourceLocation Loc) {
7623 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007624
John McCall4bc41ae2010-11-18 19:01:18 +00007625 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007626 if (LHSResult.isInvalid())
7627 return QualType();
7628
John McCall4bc41ae2010-11-18 19:01:18 +00007629 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007630 if (RHSResult.isInvalid())
7631 return QualType();
7632 RHS = RHSResult.take();
7633
John McCall73d36182010-10-12 07:14:40 +00007634 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7635 // operands, but not unary promotions.
7636 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007637
John McCall34376a62010-12-04 03:47:34 +00007638 // So we treat the LHS as a ignored value, and in C++ we allow the
7639 // containing site to determine what should be done with the RHS.
7640 S.IgnoredValueConversions(LHS);
7641
7642 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007643 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007644 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007645 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007646 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007647
Chris Lattner326f7572008-11-18 01:30:42 +00007648 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007649}
7650
Steve Naroff7a5af782007-07-13 16:58:59 +00007651/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7652/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007653static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7654 ExprValueKind &VK,
7655 SourceLocation OpLoc,
7656 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007657 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007658 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007659
Chris Lattner6b0cf142008-11-21 07:05:48 +00007660 QualType ResType = Op->getType();
7661 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007662
John McCall4bc41ae2010-11-18 19:01:18 +00007663 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007664 // Decrement of bool is not allowed.
7665 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007666 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007667 return QualType();
7668 }
7669 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007670 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007671 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007672 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007673 } else if (ResType->isAnyPointerType()) {
7674 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007675
Chris Lattner6b0cf142008-11-21 07:05:48 +00007676 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007677 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007678 if (S.getLangOptions().CPlusPlus) {
7679 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007680 << Op->getSourceRange();
7681 return QualType();
7682 }
7683
7684 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007685 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007686 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007687 if (S.getLangOptions().CPlusPlus) {
7688 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007689 << Op->getType() << Op->getSourceRange();
7690 return QualType();
7691 }
7692
John McCall4bc41ae2010-11-18 19:01:18 +00007693 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007694 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007695 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7696 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007697 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007698 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007699 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007700 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007701 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7702 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007703 << PointeeTy << Op->getSourceRange();
7704 return QualType();
7705 }
Eli Friedman090addd2010-01-03 00:20:48 +00007706 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007707 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007708 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007709 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007710 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007711 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007712 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007713 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7714 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007715 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7716 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007717 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007718 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007719 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007720 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007721 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007722 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007723 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007724 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007725 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007726 // In C++, a prefix increment is the same type as the operand. Otherwise
7727 // (in C or with postfix), the increment is the unqualified type of the
7728 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007729 if (isPrefix && S.getLangOptions().CPlusPlus) {
7730 VK = VK_LValue;
7731 return ResType;
7732 } else {
7733 VK = VK_RValue;
7734 return ResType.getUnqualifiedType();
7735 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007736}
7737
John McCall34376a62010-12-04 03:47:34 +00007738void Sema::ConvertPropertyForRValue(Expr *&E) {
7739 assert(E->getValueKind() == VK_LValue &&
7740 E->getObjectKind() == OK_ObjCProperty);
7741 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7742
7743 ExprValueKind VK = VK_RValue;
7744 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007745 if (const ObjCMethodDecl *GetterMethod =
7746 PRE->getImplicitPropertyGetter()) {
7747 QualType Result = GetterMethod->getResultType();
7748 VK = Expr::getValueKindForType(Result);
7749 }
7750 else {
7751 Diag(PRE->getLocation(), diag::err_getter_not_found)
7752 << PRE->getBase()->getType();
7753 }
John McCall34376a62010-12-04 03:47:34 +00007754 }
7755
7756 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7757 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007758
7759 ExprResult Result = MaybeBindToTemporary(E);
7760 if (!Result.isInvalid())
7761 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007762}
7763
7764void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7765 assert(LHS->getValueKind() == VK_LValue &&
7766 LHS->getObjectKind() == OK_ObjCProperty);
7767 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7768
7769 if (PRE->isImplicitProperty()) {
7770 // If using property-dot syntax notation for assignment, and there is a
7771 // setter, RHS expression is being passed to the setter argument. So,
7772 // type conversion (and comparison) is RHS to setter's argument type.
7773 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7774 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7775 LHSTy = (*P)->getType();
7776
7777 // Otherwise, if the getter returns an l-value, just call that.
7778 } else {
7779 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7780 ExprValueKind VK = Expr::getValueKindForType(Result);
7781 if (VK == VK_LValue) {
7782 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7783 CK_GetObjCProperty, LHS, 0, VK);
7784 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007785 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007786 }
John McCall34376a62010-12-04 03:47:34 +00007787 }
7788
7789 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007790 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007791 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007792 Expr *Arg = RHS;
7793 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7794 Owned(Arg));
7795 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007796 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007797 }
7798}
7799
7800
Anders Carlsson806700f2008-02-01 07:15:58 +00007801/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007802/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007803/// where the declaration is needed for type checking. We only need to
7804/// handle cases when the expression references a function designator
7805/// or is an lvalue. Here are some examples:
7806/// - &(x) => x
7807/// - &*****f => f for f a function designator.
7808/// - &s.xx => s
7809/// - &s.zz[1].yy -> s, if zz is an array
7810/// - *(x + 1) -> x, if x is an array
7811/// - &"123"[2] -> 0
7812/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007813static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007814 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007815 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007816 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007817 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007818 // If this is an arrow operator, the address is an offset from
7819 // the base's value, so the object the base refers to is
7820 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007821 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007822 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007823 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007824 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007825 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007826 // FIXME: This code shouldn't be necessary! We should catch the implicit
7827 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007828 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7829 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7830 if (ICE->getSubExpr()->getType()->isArrayType())
7831 return getPrimaryDecl(ICE->getSubExpr());
7832 }
7833 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007834 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007835 case Stmt::UnaryOperatorClass: {
7836 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007837
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007838 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007839 case UO_Real:
7840 case UO_Imag:
7841 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007842 return getPrimaryDecl(UO->getSubExpr());
7843 default:
7844 return 0;
7845 }
7846 }
Steve Naroff47500512007-04-19 23:00:49 +00007847 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007848 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007849 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007850 // If the result of an implicit cast is an l-value, we care about
7851 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007852 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007853 default:
7854 return 0;
7855 }
7856}
7857
7858/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007859/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007860/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007861/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007862/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007863/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007864/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007865static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7866 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007867 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007868 return S.Context.DependentTy;
7869 if (OrigOp->getType() == S.Context.OverloadTy)
7870 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007871
John McCall4bc41ae2010-11-18 19:01:18 +00007872 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007873 if (PR.isInvalid()) return QualType();
7874 OrigOp = PR.take();
7875
John McCall8d08b9b2010-08-27 09:08:28 +00007876 // Make sure to ignore parentheses in subsequent checks
7877 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007878
John McCall4bc41ae2010-11-18 19:01:18 +00007879 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007880 // Implement C99-only parts of addressof rules.
7881 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007882 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007883 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7884 // (assuming the deref expression is valid).
7885 return uOp->getSubExpr()->getType();
7886 }
7887 // Technically, there should be a check for array subscript
7888 // expressions here, but the result of one is always an lvalue anyway.
7889 }
John McCallf3a88602011-02-03 08:15:49 +00007890 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007891 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007892
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007893 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007894 bool sfinae = S.isSFINAEContext();
7895 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7896 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007897 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007898 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007899 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007900 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007901 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007902 } else if (lval == Expr::LV_MemberFunction) {
7903 // If it's an instance method, make a member pointer.
7904 // The expression must have exactly the form &A::foo.
7905
7906 // If the underlying expression isn't a decl ref, give up.
7907 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007908 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007909 << OrigOp->getSourceRange();
7910 return QualType();
7911 }
7912 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7913 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7914
7915 // The id-expression was parenthesized.
7916 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007917 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007918 << OrigOp->getSourceRange();
7919
7920 // The method was named without a qualifier.
7921 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007922 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007923 << op->getSourceRange();
7924 }
7925
John McCall4bc41ae2010-11-18 19:01:18 +00007926 return S.Context.getMemberPointerType(op->getType(),
7927 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007928 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007929 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007930 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007931 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007932 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007933 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007934 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007935 return QualType();
7936 }
John McCall086a4642010-11-24 05:12:34 +00007937 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007938 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007939 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007940 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007941 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007942 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007943 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007944 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007945 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007946 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007947 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007948 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007949 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007950 << "property expression" << op->getSourceRange();
7951 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007952 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007953 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007954 // with the register storage-class specifier.
7955 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007956 // in C++ it is not error to take address of a register
7957 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007958 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007959 !S.getLangOptions().CPlusPlus) {
7960 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007961 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007962 return QualType();
7963 }
John McCalld14a8642009-11-21 08:51:07 +00007964 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007965 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007966 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007967 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007968 // Could be a pointer to member, though, if there is an explicit
7969 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007970 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007971 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007972 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007973 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007974 S.Diag(OpLoc,
7975 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007976 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007977 return QualType();
7978 }
Mike Stump11289f42009-09-09 15:08:12 +00007979
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007980 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7981 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007982 return S.Context.getMemberPointerType(op->getType(),
7983 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007984 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007985 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007986 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007987 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007988 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007989
Eli Friedmance7f9002009-05-16 23:27:50 +00007990 if (lval == Expr::LV_IncompleteVoidType) {
7991 // Taking the address of a void variable is technically illegal, but we
7992 // allow it in cases which are otherwise valid.
7993 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007994 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007995 }
7996
Steve Naroff47500512007-04-19 23:00:49 +00007997 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007998 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007999 return S.Context.getObjCObjectPointerType(op->getType());
8000 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008001}
8002
Chris Lattner9156f1b2010-07-05 19:17:26 +00008003/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008004static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8005 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008006 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008007 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008008
John McCall4bc41ae2010-11-18 19:01:18 +00008009 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00008010 QualType OpTy = Op->getType();
8011 QualType Result;
8012
8013 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8014 // is an incomplete type or void. It would be possible to warn about
8015 // dereferencing a void pointer, but it's completely well-defined, and such a
8016 // warning is unlikely to catch any mistakes.
8017 if (const PointerType *PT = OpTy->getAs<PointerType>())
8018 Result = PT->getPointeeType();
8019 else if (const ObjCObjectPointerType *OPT =
8020 OpTy->getAs<ObjCObjectPointerType>())
8021 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008022 else {
John McCall4bc41ae2010-11-18 19:01:18 +00008023 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008024 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008025 if (PR.take() != Op)
8026 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008027 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008028
Chris Lattner9156f1b2010-07-05 19:17:26 +00008029 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008030 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008031 << OpTy << Op->getSourceRange();
8032 return QualType();
8033 }
John McCall4bc41ae2010-11-18 19:01:18 +00008034
8035 // Dereferences are usually l-values...
8036 VK = VK_LValue;
8037
8038 // ...except that certain expressions are never l-values in C.
8039 if (!S.getLangOptions().CPlusPlus &&
8040 IsCForbiddenLValueType(S.Context, Result))
8041 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008042
8043 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008044}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008045
John McCalle3027922010-08-25 11:45:40 +00008046static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008047 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008048 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008049 switch (Kind) {
8050 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008051 case tok::periodstar: Opc = BO_PtrMemD; break;
8052 case tok::arrowstar: Opc = BO_PtrMemI; break;
8053 case tok::star: Opc = BO_Mul; break;
8054 case tok::slash: Opc = BO_Div; break;
8055 case tok::percent: Opc = BO_Rem; break;
8056 case tok::plus: Opc = BO_Add; break;
8057 case tok::minus: Opc = BO_Sub; break;
8058 case tok::lessless: Opc = BO_Shl; break;
8059 case tok::greatergreater: Opc = BO_Shr; break;
8060 case tok::lessequal: Opc = BO_LE; break;
8061 case tok::less: Opc = BO_LT; break;
8062 case tok::greaterequal: Opc = BO_GE; break;
8063 case tok::greater: Opc = BO_GT; break;
8064 case tok::exclaimequal: Opc = BO_NE; break;
8065 case tok::equalequal: Opc = BO_EQ; break;
8066 case tok::amp: Opc = BO_And; break;
8067 case tok::caret: Opc = BO_Xor; break;
8068 case tok::pipe: Opc = BO_Or; break;
8069 case tok::ampamp: Opc = BO_LAnd; break;
8070 case tok::pipepipe: Opc = BO_LOr; break;
8071 case tok::equal: Opc = BO_Assign; break;
8072 case tok::starequal: Opc = BO_MulAssign; break;
8073 case tok::slashequal: Opc = BO_DivAssign; break;
8074 case tok::percentequal: Opc = BO_RemAssign; break;
8075 case tok::plusequal: Opc = BO_AddAssign; break;
8076 case tok::minusequal: Opc = BO_SubAssign; break;
8077 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8078 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8079 case tok::ampequal: Opc = BO_AndAssign; break;
8080 case tok::caretequal: Opc = BO_XorAssign; break;
8081 case tok::pipeequal: Opc = BO_OrAssign; break;
8082 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008083 }
8084 return Opc;
8085}
8086
John McCalle3027922010-08-25 11:45:40 +00008087static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008088 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008089 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008090 switch (Kind) {
8091 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008092 case tok::plusplus: Opc = UO_PreInc; break;
8093 case tok::minusminus: Opc = UO_PreDec; break;
8094 case tok::amp: Opc = UO_AddrOf; break;
8095 case tok::star: Opc = UO_Deref; break;
8096 case tok::plus: Opc = UO_Plus; break;
8097 case tok::minus: Opc = UO_Minus; break;
8098 case tok::tilde: Opc = UO_Not; break;
8099 case tok::exclaim: Opc = UO_LNot; break;
8100 case tok::kw___real: Opc = UO_Real; break;
8101 case tok::kw___imag: Opc = UO_Imag; break;
8102 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008103 }
8104 return Opc;
8105}
8106
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008107/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8108/// This warning is only emitted for builtin assignment operations. It is also
8109/// suppressed in the event of macro expansions.
8110static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8111 SourceLocation OpLoc) {
8112 if (!S.ActiveTemplateInstantiations.empty())
8113 return;
8114 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8115 return;
8116 lhs = lhs->IgnoreParenImpCasts();
8117 rhs = rhs->IgnoreParenImpCasts();
8118 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8119 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8120 if (!LeftDeclRef || !RightDeclRef ||
8121 LeftDeclRef->getLocation().isMacroID() ||
8122 RightDeclRef->getLocation().isMacroID())
8123 return;
8124 const ValueDecl *LeftDecl =
8125 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8126 const ValueDecl *RightDecl =
8127 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8128 if (LeftDecl != RightDecl)
8129 return;
8130 if (LeftDecl->getType().isVolatileQualified())
8131 return;
8132 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8133 if (RefTy->getPointeeType().isVolatileQualified())
8134 return;
8135
8136 S.Diag(OpLoc, diag::warn_self_assignment)
8137 << LeftDeclRef->getType()
8138 << lhs->getSourceRange() << rhs->getSourceRange();
8139}
8140
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008141/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8142/// operator @p Opc at location @c TokLoc. This routine only supports
8143/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008144ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008145 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00008146 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008147 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008148 // The following two variables are used for compound assignment operators
8149 QualType CompLHSTy; // Type of LHS after promotions for computation
8150 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008151 ExprValueKind VK = VK_RValue;
8152 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008153
Douglas Gregor1beec452011-03-12 01:48:56 +00008154 // Check if a 'foo<int>' involved in a binary op, identifies a single
8155 // function unambiguously (i.e. an lvalue ala 13.4)
8156 // But since an assignment can trigger target based overload, exclude it in
8157 // our blind search. i.e:
8158 // template<class T> void f(); template<class T, class U> void f(U);
8159 // f<int> == 0; // resolve f<int> blindly
8160 // void (*p)(int); p = f<int>; // resolve f<int> using target
8161 if (Opc != BO_Assign) {
8162 if (lhs->getType() == Context.OverloadTy) {
8163 ExprResult resolvedLHS =
8164 ResolveAndFixSingleFunctionTemplateSpecialization(lhs);
8165 if (resolvedLHS.isUsable()) lhs = resolvedLHS.release();
8166 }
8167 if (rhs->getType() == Context.OverloadTy) {
8168 ExprResult resolvedRHS =
8169 ResolveAndFixSingleFunctionTemplateSpecialization(rhs);
8170 if (resolvedRHS.isUsable()) rhs = resolvedRHS.release();
8171 }
8172 }
8173
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008174 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008175 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008176 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008177 if (getLangOptions().CPlusPlus &&
8178 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00008179 VK = lhs->getValueKind();
8180 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008181 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008182 if (!ResultTy.isNull())
8183 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008184 break;
John McCalle3027922010-08-25 11:45:40 +00008185 case BO_PtrMemD:
8186 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008187 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008188 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008189 break;
John McCalle3027922010-08-25 11:45:40 +00008190 case BO_Mul:
8191 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008192 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008193 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008194 break;
John McCalle3027922010-08-25 11:45:40 +00008195 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008196 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8197 break;
John McCalle3027922010-08-25 11:45:40 +00008198 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008199 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8200 break;
John McCalle3027922010-08-25 11:45:40 +00008201 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008202 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8203 break;
John McCalle3027922010-08-25 11:45:40 +00008204 case BO_Shl:
8205 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008206 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008207 break;
John McCalle3027922010-08-25 11:45:40 +00008208 case BO_LE:
8209 case BO_LT:
8210 case BO_GE:
8211 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008212 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008213 break;
John McCalle3027922010-08-25 11:45:40 +00008214 case BO_EQ:
8215 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008216 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008217 break;
John McCalle3027922010-08-25 11:45:40 +00008218 case BO_And:
8219 case BO_Xor:
8220 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008221 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8222 break;
John McCalle3027922010-08-25 11:45:40 +00008223 case BO_LAnd:
8224 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008225 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008226 break;
John McCalle3027922010-08-25 11:45:40 +00008227 case BO_MulAssign:
8228 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008229 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008230 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008231 CompLHSTy = CompResultTy;
8232 if (!CompResultTy.isNull())
8233 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008234 break;
John McCalle3027922010-08-25 11:45:40 +00008235 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008236 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8237 CompLHSTy = CompResultTy;
8238 if (!CompResultTy.isNull())
8239 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008240 break;
John McCalle3027922010-08-25 11:45:40 +00008241 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008242 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8243 if (!CompResultTy.isNull())
8244 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008245 break;
John McCalle3027922010-08-25 11:45:40 +00008246 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008247 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8248 if (!CompResultTy.isNull())
8249 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008250 break;
John McCalle3027922010-08-25 11:45:40 +00008251 case BO_ShlAssign:
8252 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008253 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008254 CompLHSTy = CompResultTy;
8255 if (!CompResultTy.isNull())
8256 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008257 break;
John McCalle3027922010-08-25 11:45:40 +00008258 case BO_AndAssign:
8259 case BO_XorAssign:
8260 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008261 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8262 CompLHSTy = CompResultTy;
8263 if (!CompResultTy.isNull())
8264 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008265 break;
John McCalle3027922010-08-25 11:45:40 +00008266 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008267 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008268 if (getLangOptions().CPlusPlus) {
8269 VK = rhs->getValueKind();
8270 OK = rhs->getObjectKind();
8271 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008272 break;
8273 }
8274 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008275 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008276 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008277 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8278 VK, OK, OpLoc));
8279
John McCall34376a62010-12-04 03:47:34 +00008280 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008281 VK = VK_LValue;
8282 OK = lhs->getObjectKind();
8283 }
8284 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8285 VK, OK, CompLHSTy,
8286 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008287}
8288
Sebastian Redl44615072009-10-27 12:10:02 +00008289/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8290/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008291static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8292 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008293 const PartialDiagnostic &FirstNote,
8294 SourceRange FirstParenRange,
8295 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008296 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008297 Self.Diag(Loc, PD);
8298
8299 if (!FirstNote.getDiagID())
8300 return;
8301
8302 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8303 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8304 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008305 return;
8306 }
8307
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008308 Self.Diag(Loc, FirstNote)
8309 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008310 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008311
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008312 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008313 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008314
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008315 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8316 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8317 // We can't display the parentheses, so just dig the
8318 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008319 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008320 return;
8321 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008322
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008323 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008324 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8325 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008326}
8327
Sebastian Redl44615072009-10-27 12:10:02 +00008328/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8329/// operators are mixed in a way that suggests that the programmer forgot that
8330/// comparison operators have higher precedence. The most typical example of
8331/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008332static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008333 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008334 typedef BinaryOperator BinOp;
8335 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8336 rhsopc = static_cast<BinOp::Opcode>(-1);
8337 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008338 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008339 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008340 rhsopc = BO->getOpcode();
8341
8342 // Subs are not binary operators.
8343 if (lhsopc == -1 && rhsopc == -1)
8344 return;
8345
8346 // Bitwise operations are sometimes used as eager logical ops.
8347 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008348 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8349 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008350 return;
8351
Sebastian Redl44615072009-10-27 12:10:02 +00008352 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008353 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008354 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008355 << SourceRange(lhs->getLocStart(), OpLoc)
8356 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008357 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008358 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008359 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8360 Self.PDiag(diag::note_precedence_bitwise_silence)
8361 << BinOp::getOpcodeStr(lhsopc),
8362 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008363 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008364 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008365 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008366 << SourceRange(OpLoc, rhs->getLocEnd())
8367 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008368 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008369 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008370 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8371 Self.PDiag(diag::note_precedence_bitwise_silence)
8372 << BinOp::getOpcodeStr(rhsopc),
8373 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008374}
8375
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008376/// \brief It accepts a '&&' expr that is inside a '||' one.
8377/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8378/// in parentheses.
8379static void
8380EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8381 Expr *E) {
8382 assert(isa<BinaryOperator>(E) &&
8383 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8384 SuggestParentheses(Self, OpLoc,
8385 Self.PDiag(diag::warn_logical_and_in_logical_or)
8386 << E->getSourceRange(),
8387 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8388 E->getSourceRange(),
8389 Self.PDiag(0), SourceRange());
8390}
8391
8392/// \brief Returns true if the given expression can be evaluated as a constant
8393/// 'true'.
8394static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8395 bool Res;
8396 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8397}
8398
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008399/// \brief Returns true if the given expression can be evaluated as a constant
8400/// 'false'.
8401static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8402 bool Res;
8403 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8404}
8405
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008406/// \brief Look for '&&' in the left hand of a '||' expr.
8407static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008408 Expr *OrLHS, Expr *OrRHS) {
8409 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008410 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008411 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8412 if (EvaluatesAsFalse(S, OrRHS))
8413 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008414 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8415 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8416 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8417 } else if (Bop->getOpcode() == BO_LOr) {
8418 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8419 // If it's "a || b && 1 || c" we didn't warn earlier for
8420 // "a || b && 1", but warn now.
8421 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8422 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8423 }
8424 }
8425 }
8426}
8427
8428/// \brief Look for '&&' in the right hand of a '||' expr.
8429static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008430 Expr *OrLHS, Expr *OrRHS) {
8431 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008432 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008433 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8434 if (EvaluatesAsFalse(S, OrLHS))
8435 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008436 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8437 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8438 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008439 }
8440 }
8441}
8442
Sebastian Redl43028242009-10-26 15:24:15 +00008443/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008444/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008445static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008446 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008447 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008448 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008449 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8450
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008451 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8452 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008453 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008454 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8455 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008456 }
Sebastian Redl43028242009-10-26 15:24:15 +00008457}
8458
Steve Naroff218bc2b2007-05-04 21:54:46 +00008459// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008460ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008461 tok::TokenKind Kind,
8462 Expr *lhs, Expr *rhs) {
8463 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008464 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8465 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008466
Sebastian Redl43028242009-10-26 15:24:15 +00008467 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8468 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8469
Douglas Gregor5287f092009-11-05 00:51:44 +00008470 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8471}
8472
John McCalldadc5752010-08-24 06:29:42 +00008473ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008474 BinaryOperatorKind Opc,
8475 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008476 if (getLangOptions().CPlusPlus) {
8477 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008478
John McCall622114c2010-12-06 05:26:58 +00008479 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8480 UseBuiltinOperator = false;
8481 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8482 UseBuiltinOperator = true;
8483 } else {
8484 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8485 !rhs->getType()->isOverloadableType();
8486 }
8487
8488 if (!UseBuiltinOperator) {
8489 // Find all of the overloaded operators visible from this
8490 // point. We perform both an operator-name lookup from the local
8491 // scope and an argument-dependent lookup based on the types of
8492 // the arguments.
8493 UnresolvedSet<16> Functions;
8494 OverloadedOperatorKind OverOp
8495 = BinaryOperator::getOverloadedOperator(Opc);
8496 if (S && OverOp != OO_None)
8497 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8498 Functions);
8499
8500 // Build the (potentially-overloaded, potentially-dependent)
8501 // binary operation.
8502 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8503 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008504 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008505
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008506 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008507 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008508}
8509
John McCalldadc5752010-08-24 06:29:42 +00008510ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008511 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008512 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008513 ExprValueKind VK = VK_RValue;
8514 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008515 QualType resultType;
8516 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008517 case UO_PreInc:
8518 case UO_PreDec:
8519 case UO_PostInc:
8520 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008521 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008522 Opc == UO_PreInc ||
8523 Opc == UO_PostInc,
8524 Opc == UO_PreInc ||
8525 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008526 break;
John McCalle3027922010-08-25 11:45:40 +00008527 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008528 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008529 break;
John McCalle3027922010-08-25 11:45:40 +00008530 case UO_Deref:
Douglas Gregor1beec452011-03-12 01:48:56 +00008531 if (Input->getType() == Context.OverloadTy ) {
8532 ExprResult er = ResolveAndFixSingleFunctionTemplateSpecialization(Input);
8533 if (er.isUsable())
8534 Input = er.release();
8535 }
Douglas Gregorb92a1562010-02-03 00:27:59 +00008536 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008537 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008538 break;
John McCalle3027922010-08-25 11:45:40 +00008539 case UO_Plus:
8540 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008541 UsualUnaryConversions(Input);
8542 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008543 if (resultType->isDependentType())
8544 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008545 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8546 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008547 break;
8548 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8549 resultType->isEnumeralType())
8550 break;
8551 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008552 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008553 resultType->isPointerType())
8554 break;
John McCall36226622010-10-12 02:09:17 +00008555 else if (resultType->isPlaceholderType()) {
8556 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8557 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008558 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008559 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008560
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008561 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8562 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008563 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008564 UsualUnaryConversions(Input);
8565 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008566 if (resultType->isDependentType())
8567 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008568 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8569 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8570 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008571 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008572 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008573 else if (resultType->hasIntegerRepresentation())
8574 break;
8575 else if (resultType->isPlaceholderType()) {
8576 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8577 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008578 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008579 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008580 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8581 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008582 }
Steve Naroff35d85152007-05-07 00:24:15 +00008583 break;
John McCalle3027922010-08-25 11:45:40 +00008584 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008585 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008586 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008587 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008588 if (resultType->isDependentType())
8589 break;
John McCall36226622010-10-12 02:09:17 +00008590 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8591 // ok, fallthrough
8592 } else if (resultType->isPlaceholderType()) {
8593 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8594 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008595 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008596 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008597 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8598 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008599 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008600
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008601 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008602 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008603 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008604 break;
John McCalle3027922010-08-25 11:45:40 +00008605 case UO_Real:
8606 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008607 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008608 // _Real and _Imag map ordinary l-values into ordinary l-values.
8609 if (Input->getValueKind() != VK_RValue &&
8610 Input->getObjectKind() == OK_Ordinary)
8611 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008612 break;
John McCalle3027922010-08-25 11:45:40 +00008613 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008614 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008615 VK = Input->getValueKind();
8616 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008617 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008618 }
8619 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008620 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008621
John McCall7decc9e2010-11-18 06:31:45 +00008622 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8623 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008624}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008625
John McCalldadc5752010-08-24 06:29:42 +00008626ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008627 UnaryOperatorKind Opc,
8628 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008629 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008630 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008631 // Find all of the overloaded operators visible from this
8632 // point. We perform both an operator-name lookup from the local
8633 // scope and an argument-dependent lookup based on the types of
8634 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008635 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008636 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008637 if (S && OverOp != OO_None)
8638 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8639 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008640
John McCallb268a282010-08-23 23:25:46 +00008641 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008642 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008643
John McCallb268a282010-08-23 23:25:46 +00008644 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008645}
8646
Douglas Gregor5287f092009-11-05 00:51:44 +00008647// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008648ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008649 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008650 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008651}
8652
Steve Naroff66356bd2007-09-16 14:56:35 +00008653/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008654ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008655 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008656 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008657 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008658 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008659 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008660}
8661
John McCalldadc5752010-08-24 06:29:42 +00008662ExprResult
John McCallb268a282010-08-23 23:25:46 +00008663Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008664 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008665 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8666 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8667
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008668 bool isFileScope
8669 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008670 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008671 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008672
Chris Lattner366727f2007-07-24 16:58:17 +00008673 // FIXME: there are a variety of strange constraints to enforce here, for
8674 // example, it is not possible to goto into a stmt expression apparently.
8675 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008676
Chris Lattner366727f2007-07-24 16:58:17 +00008677 // If there are sub stmts in the compound stmt, take the type of the last one
8678 // as the type of the stmtexpr.
8679 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008680 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008681 if (!Compound->body_empty()) {
8682 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008683 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008684 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008685 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8686 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008687 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008688 }
8689 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008690 // Do function/array conversion on the last expression, but not
8691 // lvalue-to-rvalue. However, initialize an unqualified type.
8692 DefaultFunctionArrayConversion(LastExpr);
8693 Ty = LastExpr->getType().getUnqualifiedType();
8694
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008695 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8696 ExprResult Res = PerformCopyInitialization(
8697 InitializedEntity::InitializeResult(LPLoc,
8698 Ty,
8699 false),
8700 SourceLocation(),
8701 Owned(LastExpr));
8702 if (Res.isInvalid())
8703 return ExprError();
8704 if ((LastExpr = Res.takeAs<Expr>())) {
8705 if (!LastLabelStmt)
8706 Compound->setLastStmt(LastExpr);
8707 else
8708 LastLabelStmt->setSubStmt(LastExpr);
8709 StmtExprMayBindToTemp = true;
8710 }
8711 }
8712 }
Chris Lattner944d3062008-07-26 19:51:01 +00008713 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008714
Eli Friedmanba961a92009-03-23 00:24:07 +00008715 // FIXME: Check that expression type is complete/non-abstract; statement
8716 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008717 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8718 if (StmtExprMayBindToTemp)
8719 return MaybeBindToTemporary(ResStmtExpr);
8720 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008721}
Steve Naroff78864672007-08-01 22:05:33 +00008722
John McCalldadc5752010-08-24 06:29:42 +00008723ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008724 TypeSourceInfo *TInfo,
8725 OffsetOfComponent *CompPtr,
8726 unsigned NumComponents,
8727 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008728 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008729 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008730 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008731
Chris Lattnerf17bd422007-08-30 17:45:32 +00008732 // We must have at least one component that refers to the type, and the first
8733 // one is known to be a field designator. Verify that the ArgTy represents
8734 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008735 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008736 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8737 << ArgTy << TypeRange);
8738
8739 // Type must be complete per C99 7.17p3 because a declaring a variable
8740 // with an incomplete type would be ill-formed.
8741 if (!Dependent
8742 && RequireCompleteType(BuiltinLoc, ArgTy,
8743 PDiag(diag::err_offsetof_incomplete_type)
8744 << TypeRange))
8745 return ExprError();
8746
Chris Lattner78502cf2007-08-31 21:49:13 +00008747 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8748 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008749 // FIXME: This diagnostic isn't actually visible because the location is in
8750 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008751 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008752 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8753 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008754
8755 bool DidWarnAboutNonPOD = false;
8756 QualType CurrentType = ArgTy;
8757 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8758 llvm::SmallVector<OffsetOfNode, 4> Comps;
8759 llvm::SmallVector<Expr*, 4> Exprs;
8760 for (unsigned i = 0; i != NumComponents; ++i) {
8761 const OffsetOfComponent &OC = CompPtr[i];
8762 if (OC.isBrackets) {
8763 // Offset of an array sub-field. TODO: Should we allow vector elements?
8764 if (!CurrentType->isDependentType()) {
8765 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8766 if(!AT)
8767 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8768 << CurrentType);
8769 CurrentType = AT->getElementType();
8770 } else
8771 CurrentType = Context.DependentTy;
8772
8773 // The expression must be an integral expression.
8774 // FIXME: An integral constant expression?
8775 Expr *Idx = static_cast<Expr*>(OC.U.E);
8776 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8777 !Idx->getType()->isIntegerType())
8778 return ExprError(Diag(Idx->getLocStart(),
8779 diag::err_typecheck_subscript_not_integer)
8780 << Idx->getSourceRange());
8781
8782 // Record this array index.
8783 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8784 Exprs.push_back(Idx);
8785 continue;
8786 }
8787
8788 // Offset of a field.
8789 if (CurrentType->isDependentType()) {
8790 // We have the offset of a field, but we can't look into the dependent
8791 // type. Just record the identifier of the field.
8792 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8793 CurrentType = Context.DependentTy;
8794 continue;
8795 }
8796
8797 // We need to have a complete type to look into.
8798 if (RequireCompleteType(OC.LocStart, CurrentType,
8799 diag::err_offsetof_incomplete_type))
8800 return ExprError();
8801
8802 // Look for the designated field.
8803 const RecordType *RC = CurrentType->getAs<RecordType>();
8804 if (!RC)
8805 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8806 << CurrentType);
8807 RecordDecl *RD = RC->getDecl();
8808
8809 // C++ [lib.support.types]p5:
8810 // The macro offsetof accepts a restricted set of type arguments in this
8811 // International Standard. type shall be a POD structure or a POD union
8812 // (clause 9).
8813 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8814 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008815 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008816 PDiag(diag::warn_offsetof_non_pod_type)
8817 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8818 << CurrentType))
8819 DidWarnAboutNonPOD = true;
8820 }
8821
8822 // Look for the field.
8823 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8824 LookupQualifiedName(R, RD);
8825 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008826 IndirectFieldDecl *IndirectMemberDecl = 0;
8827 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008828 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008829 MemberDecl = IndirectMemberDecl->getAnonField();
8830 }
8831
Douglas Gregor882211c2010-04-28 22:16:22 +00008832 if (!MemberDecl)
8833 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8834 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8835 OC.LocEnd));
8836
Douglas Gregor10982ea2010-04-28 22:36:06 +00008837 // C99 7.17p3:
8838 // (If the specified member is a bit-field, the behavior is undefined.)
8839 //
8840 // We diagnose this as an error.
8841 if (MemberDecl->getBitWidth()) {
8842 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8843 << MemberDecl->getDeclName()
8844 << SourceRange(BuiltinLoc, RParenLoc);
8845 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8846 return ExprError();
8847 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008848
8849 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008850 if (IndirectMemberDecl)
8851 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008852
Douglas Gregord1702062010-04-29 00:18:15 +00008853 // If the member was found in a base class, introduce OffsetOfNodes for
8854 // the base class indirections.
8855 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8856 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008857 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008858 CXXBasePath &Path = Paths.front();
8859 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8860 B != BEnd; ++B)
8861 Comps.push_back(OffsetOfNode(B->Base));
8862 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008863
Francois Pichet783dd6e2010-11-21 06:08:52 +00008864 if (IndirectMemberDecl) {
8865 for (IndirectFieldDecl::chain_iterator FI =
8866 IndirectMemberDecl->chain_begin(),
8867 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8868 assert(isa<FieldDecl>(*FI));
8869 Comps.push_back(OffsetOfNode(OC.LocStart,
8870 cast<FieldDecl>(*FI), OC.LocEnd));
8871 }
8872 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008873 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008874
Douglas Gregor882211c2010-04-28 22:16:22 +00008875 CurrentType = MemberDecl->getType().getNonReferenceType();
8876 }
8877
8878 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8879 TInfo, Comps.data(), Comps.size(),
8880 Exprs.data(), Exprs.size(), RParenLoc));
8881}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008882
John McCalldadc5752010-08-24 06:29:42 +00008883ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008884 SourceLocation BuiltinLoc,
8885 SourceLocation TypeLoc,
8886 ParsedType argty,
8887 OffsetOfComponent *CompPtr,
8888 unsigned NumComponents,
8889 SourceLocation RPLoc) {
8890
Douglas Gregor882211c2010-04-28 22:16:22 +00008891 TypeSourceInfo *ArgTInfo;
8892 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8893 if (ArgTy.isNull())
8894 return ExprError();
8895
Eli Friedman06dcfd92010-08-05 10:15:45 +00008896 if (!ArgTInfo)
8897 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8898
8899 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8900 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008901}
8902
8903
John McCalldadc5752010-08-24 06:29:42 +00008904ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008905 Expr *CondExpr,
8906 Expr *LHSExpr, Expr *RHSExpr,
8907 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008908 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8909
John McCall7decc9e2010-11-18 06:31:45 +00008910 ExprValueKind VK = VK_RValue;
8911 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008912 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008913 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008914 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008915 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008916 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008917 } else {
8918 // The conditional expression is required to be a constant expression.
8919 llvm::APSInt condEval(32);
8920 SourceLocation ExpLoc;
8921 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008922 return ExprError(Diag(ExpLoc,
8923 diag::err_typecheck_choose_expr_requires_constant)
8924 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008925
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008926 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008927 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8928
8929 resType = ActiveExpr->getType();
8930 ValueDependent = ActiveExpr->isValueDependent();
8931 VK = ActiveExpr->getValueKind();
8932 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008933 }
8934
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008935 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008936 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008937 resType->isDependentType(),
8938 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008939}
8940
Steve Naroffc540d662008-09-03 18:15:37 +00008941//===----------------------------------------------------------------------===//
8942// Clang Extensions.
8943//===----------------------------------------------------------------------===//
8944
8945/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008946void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008947 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8948 PushBlockScope(BlockScope, Block);
8949 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008950 if (BlockScope)
8951 PushDeclContext(BlockScope, Block);
8952 else
8953 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008954}
8955
Mike Stump82f071f2009-02-04 22:31:32 +00008956void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008957 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008958 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008959 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008960
John McCall8cb7bdf2010-06-04 23:28:52 +00008961 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008962 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008963
John McCall3882ace2011-01-05 12:14:39 +00008964 // GetTypeForDeclarator always produces a function type for a block
8965 // literal signature. Furthermore, it is always a FunctionProtoType
8966 // unless the function was written with a typedef.
8967 assert(T->isFunctionType() &&
8968 "GetTypeForDeclarator made a non-function block signature");
8969
8970 // Look for an explicit signature in that function type.
8971 FunctionProtoTypeLoc ExplicitSignature;
8972
8973 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8974 if (isa<FunctionProtoTypeLoc>(tmp)) {
8975 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8976
8977 // Check whether that explicit signature was synthesized by
8978 // GetTypeForDeclarator. If so, don't save that as part of the
8979 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008980 if (ExplicitSignature.getLocalRangeBegin() ==
8981 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008982 // This would be much cheaper if we stored TypeLocs instead of
8983 // TypeSourceInfos.
8984 TypeLoc Result = ExplicitSignature.getResultLoc();
8985 unsigned Size = Result.getFullDataSize();
8986 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8987 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8988
8989 ExplicitSignature = FunctionProtoTypeLoc();
8990 }
John McCalla3ccba02010-06-04 11:21:44 +00008991 }
Mike Stump11289f42009-09-09 15:08:12 +00008992
John McCall3882ace2011-01-05 12:14:39 +00008993 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8994 CurBlock->FunctionType = T;
8995
8996 const FunctionType *Fn = T->getAs<FunctionType>();
8997 QualType RetTy = Fn->getResultType();
8998 bool isVariadic =
8999 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9000
John McCall8e346702010-06-04 19:02:56 +00009001 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009002
John McCalla3ccba02010-06-04 11:21:44 +00009003 // Don't allow returning a objc interface by value.
9004 if (RetTy->isObjCObjectType()) {
9005 Diag(ParamInfo.getSourceRange().getBegin(),
9006 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9007 return;
9008 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009009
John McCalla3ccba02010-06-04 11:21:44 +00009010 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009011 // return type. TODO: what should we do with declarators like:
9012 // ^ * { ... }
9013 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009014 if (RetTy != Context.DependentTy)
9015 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009016
John McCalla3ccba02010-06-04 11:21:44 +00009017 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009018 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009019 if (ExplicitSignature) {
9020 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9021 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009022 if (Param->getIdentifier() == 0 &&
9023 !Param->isImplicit() &&
9024 !Param->isInvalidDecl() &&
9025 !getLangOptions().CPlusPlus)
9026 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009027 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009028 }
John McCalla3ccba02010-06-04 11:21:44 +00009029
9030 // Fake up parameter variables if we have a typedef, like
9031 // ^ fntype { ... }
9032 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9033 for (FunctionProtoType::arg_type_iterator
9034 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9035 ParmVarDecl *Param =
9036 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9037 ParamInfo.getSourceRange().getBegin(),
9038 *I);
John McCall8e346702010-06-04 19:02:56 +00009039 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009040 }
Steve Naroffc540d662008-09-03 18:15:37 +00009041 }
John McCalla3ccba02010-06-04 11:21:44 +00009042
John McCall8e346702010-06-04 19:02:56 +00009043 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009044 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009045 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009046 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9047 CurBlock->TheDecl->param_end(),
9048 /*CheckParameterNames=*/false);
9049 }
9050
John McCalla3ccba02010-06-04 11:21:44 +00009051 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009052 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009053
John McCall8e346702010-06-04 19:02:56 +00009054 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009055 Diag(ParamInfo.getAttributes()->getLoc(),
9056 diag::warn_attribute_sentinel_not_variadic) << 1;
9057 // FIXME: remove the attribute.
9058 }
9059
9060 // Put the parameter variables in scope. We can bail out immediately
9061 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009062 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009063 return;
9064
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009065 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009066 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9067 (*AI)->setOwningFunction(CurBlock->TheDecl);
9068
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009069 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009070 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009071 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009072
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009073 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009074 }
John McCallf7b2fb52010-01-22 00:28:27 +00009075 }
Steve Naroffc540d662008-09-03 18:15:37 +00009076}
9077
9078/// ActOnBlockError - If there is an error parsing a block, this callback
9079/// is invoked to pop the information about the block from the action impl.
9080void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009081 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009082 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009083 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009084}
9085
9086/// ActOnBlockStmtExpr - This is called when the body of a block statement
9087/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009088ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009089 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009090 // If blocks are disabled, emit an error.
9091 if (!LangOpts.Blocks)
9092 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009093
Douglas Gregor9a28e842010-03-01 23:15:13 +00009094 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009095
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009096 PopDeclContext();
9097
Steve Naroffc540d662008-09-03 18:15:37 +00009098 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009099 if (!BSI->ReturnType.isNull())
9100 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009101
Mike Stump3bf1ab42009-07-28 22:04:01 +00009102 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009103 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009104
John McCallc63de662011-02-02 13:00:07 +00009105 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009106 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9107 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009108
John McCall8e346702010-06-04 19:02:56 +00009109 // If the user wrote a function type in some form, try to use that.
9110 if (!BSI->FunctionType.isNull()) {
9111 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9112
9113 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9114 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9115
9116 // Turn protoless block types into nullary block types.
9117 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009118 FunctionProtoType::ExtProtoInfo EPI;
9119 EPI.ExtInfo = Ext;
9120 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009121
9122 // Otherwise, if we don't need to change anything about the function type,
9123 // preserve its sugar structure.
9124 } else if (FTy->getResultType() == RetTy &&
9125 (!NoReturn || FTy->getNoReturnAttr())) {
9126 BlockTy = BSI->FunctionType;
9127
9128 // Otherwise, make the minimal modifications to the function type.
9129 } else {
9130 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009131 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9132 EPI.TypeQuals = 0; // FIXME: silently?
9133 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009134 BlockTy = Context.getFunctionType(RetTy,
9135 FPT->arg_type_begin(),
9136 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009137 EPI);
John McCall8e346702010-06-04 19:02:56 +00009138 }
9139
9140 // If we don't have a function type, just build one from nothing.
9141 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009142 FunctionProtoType::ExtProtoInfo EPI;
9143 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
9144 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009145 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009146
John McCall8e346702010-06-04 19:02:56 +00009147 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9148 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009149 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009150
Chris Lattner45542ea2009-04-19 05:28:12 +00009151 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009152 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009153 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009154
Chris Lattner60f84492011-02-17 23:58:47 +00009155 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009156
John McCallc63de662011-02-02 13:00:07 +00009157 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009158
Ted Kremenek1767a272011-02-23 01:51:48 +00009159 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9160 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009161 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009162}
9163
John McCalldadc5752010-08-24 06:29:42 +00009164ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009165 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009166 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009167 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009168 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009169 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009170}
9171
John McCalldadc5752010-08-24 06:29:42 +00009172ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009173 Expr *E, TypeSourceInfo *TInfo,
9174 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009175 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009176
Eli Friedman121ba0c2008-08-09 23:32:40 +00009177 // Get the va_list type
9178 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009179 if (VaListType->isArrayType()) {
9180 // Deal with implicit array decay; for example, on x86-64,
9181 // va_list is an array, but it's supposed to decay to
9182 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009183 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009184 // Make sure the input expression also decays appropriately.
9185 UsualUnaryConversions(E);
9186 } else {
9187 // Otherwise, the va_list argument must be an l-value because
9188 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009189 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009190 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009191 return ExprError();
9192 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009193
Douglas Gregorad3150c2009-05-19 23:10:31 +00009194 if (!E->isTypeDependent() &&
9195 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009196 return ExprError(Diag(E->getLocStart(),
9197 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009198 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009199 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009200
Eli Friedmanba961a92009-03-23 00:24:07 +00009201 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009202 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009203
Abramo Bagnara27db2392010-08-10 10:06:15 +00009204 QualType T = TInfo->getType().getNonLValueExprType(Context);
9205 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009206}
9207
John McCalldadc5752010-08-24 06:29:42 +00009208ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009209 // The type of __null will be int or long, depending on the size of
9210 // pointers on the target.
9211 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009212 unsigned pw = Context.Target.getPointerWidth(0);
9213 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009214 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009215 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009216 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009217 else if (pw == Context.Target.getLongLongWidth())
9218 Ty = Context.LongLongTy;
9219 else {
9220 assert(!"I don't know size of pointer!");
9221 Ty = Context.IntTy;
9222 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009223
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009224 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009225}
9226
Alexis Huntc46382e2010-04-28 23:02:27 +00009227static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009228 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009229 if (!SemaRef.getLangOptions().ObjC1)
9230 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009231
Anders Carlssonace5d072009-11-10 04:46:30 +00009232 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9233 if (!PT)
9234 return;
9235
9236 // Check if the destination is of type 'id'.
9237 if (!PT->isObjCIdType()) {
9238 // Check if the destination is the 'NSString' interface.
9239 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9240 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9241 return;
9242 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009243
Anders Carlssonace5d072009-11-10 04:46:30 +00009244 // Strip off any parens and casts.
9245 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9246 if (!SL || SL->isWide())
9247 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009248
Douglas Gregora771f462010-03-31 17:46:05 +00009249 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009250}
9251
Chris Lattner9bad62c2008-01-04 18:04:52 +00009252bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9253 SourceLocation Loc,
9254 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009255 Expr *SrcExpr, AssignmentAction Action,
9256 bool *Complained) {
9257 if (Complained)
9258 *Complained = false;
9259
Chris Lattner9bad62c2008-01-04 18:04:52 +00009260 // Decode the result (notice that AST's are still created for extensions).
9261 bool isInvalid = false;
9262 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009263 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009264
Chris Lattner9bad62c2008-01-04 18:04:52 +00009265 switch (ConvTy) {
9266 default: assert(0 && "Unknown conversion type");
9267 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009268 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009269 DiagKind = diag::ext_typecheck_convert_pointer_int;
9270 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009271 case IntToPointer:
9272 DiagKind = diag::ext_typecheck_convert_int_pointer;
9273 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009274 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009275 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009276 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9277 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009278 case IncompatiblePointerSign:
9279 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9280 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009281 case FunctionVoidPointer:
9282 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9283 break;
John McCall4fff8f62011-02-01 00:10:29 +00009284 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009285 // Perform array-to-pointer decay if necessary.
9286 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9287
John McCall4fff8f62011-02-01 00:10:29 +00009288 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9289 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9290 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9291 DiagKind = diag::err_typecheck_incompatible_address_space;
9292 break;
9293 }
9294
9295 llvm_unreachable("unknown error case for discarding qualifiers!");
9296 // fallthrough
9297 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009298 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009299 // If the qualifiers lost were because we were applying the
9300 // (deprecated) C++ conversion from a string literal to a char*
9301 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9302 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009303 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009304 // bit of refactoring (so that the second argument is an
9305 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009306 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009307 // C++ semantics.
9308 if (getLangOptions().CPlusPlus &&
9309 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9310 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009311 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9312 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009313 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009314 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009315 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009316 case IntToBlockPointer:
9317 DiagKind = diag::err_int_to_block_pointer;
9318 break;
9319 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009320 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009321 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009322 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009323 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009324 // it can give a more specific diagnostic.
9325 DiagKind = diag::warn_incompatible_qualified_id;
9326 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009327 case IncompatibleVectors:
9328 DiagKind = diag::warn_incompatible_vectors;
9329 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009330 case Incompatible:
9331 DiagKind = diag::err_typecheck_convert_incompatible;
9332 isInvalid = true;
9333 break;
9334 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009335
Douglas Gregorc68e1402010-04-09 00:35:39 +00009336 QualType FirstType, SecondType;
9337 switch (Action) {
9338 case AA_Assigning:
9339 case AA_Initializing:
9340 // The destination type comes first.
9341 FirstType = DstType;
9342 SecondType = SrcType;
9343 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009344
Douglas Gregorc68e1402010-04-09 00:35:39 +00009345 case AA_Returning:
9346 case AA_Passing:
9347 case AA_Converting:
9348 case AA_Sending:
9349 case AA_Casting:
9350 // The source type comes first.
9351 FirstType = SrcType;
9352 SecondType = DstType;
9353 break;
9354 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009355
Douglas Gregorc68e1402010-04-09 00:35:39 +00009356 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009357 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009358 if (Complained)
9359 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009360 return isInvalid;
9361}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009362
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009363bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009364 llvm::APSInt ICEResult;
9365 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9366 if (Result)
9367 *Result = ICEResult;
9368 return false;
9369 }
9370
Anders Carlssone54e8a12008-11-30 19:50:32 +00009371 Expr::EvalResult EvalResult;
9372
Mike Stump4e1f26a2009-02-19 03:04:26 +00009373 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009374 EvalResult.HasSideEffects) {
9375 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9376
9377 if (EvalResult.Diag) {
9378 // We only show the note if it's not the usual "invalid subexpression"
9379 // or if it's actually in a subexpression.
9380 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9381 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9382 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9383 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009384
Anders Carlssone54e8a12008-11-30 19:50:32 +00009385 return true;
9386 }
9387
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009388 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9389 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009390
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009391 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009392 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9393 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009394 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009395
Anders Carlssone54e8a12008-11-30 19:50:32 +00009396 if (Result)
9397 *Result = EvalResult.Val.getInt();
9398 return false;
9399}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009400
Douglas Gregorff790f12009-11-26 00:44:06 +00009401void
Mike Stump11289f42009-09-09 15:08:12 +00009402Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009403 ExprEvalContexts.push_back(
9404 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009405}
9406
Mike Stump11289f42009-09-09 15:08:12 +00009407void
Douglas Gregorff790f12009-11-26 00:44:06 +00009408Sema::PopExpressionEvaluationContext() {
9409 // Pop the current expression evaluation context off the stack.
9410 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9411 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009412
Douglas Gregorfab31f42009-12-12 07:57:52 +00009413 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9414 if (Rec.PotentiallyReferenced) {
9415 // Mark any remaining declarations in the current position of the stack
9416 // as "referenced". If they were not meant to be referenced, semantic
9417 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009418 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009419 I = Rec.PotentiallyReferenced->begin(),
9420 IEnd = Rec.PotentiallyReferenced->end();
9421 I != IEnd; ++I)
9422 MarkDeclarationReferenced(I->first, I->second);
9423 }
9424
9425 if (Rec.PotentiallyDiagnosed) {
9426 // Emit any pending diagnostics.
9427 for (PotentiallyEmittedDiagnostics::iterator
9428 I = Rec.PotentiallyDiagnosed->begin(),
9429 IEnd = Rec.PotentiallyDiagnosed->end();
9430 I != IEnd; ++I)
9431 Diag(I->first, I->second);
9432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009433 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009434
9435 // When are coming out of an unevaluated context, clear out any
9436 // temporaries that we may have created as part of the evaluation of
9437 // the expression in that context: they aren't relevant because they
9438 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009439 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009440 ExprTemporaries.size() > Rec.NumTemporaries)
9441 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9442 ExprTemporaries.end());
9443
9444 // Destroy the popped expression evaluation record.
9445 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009446}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009447
9448/// \brief Note that the given declaration was referenced in the source code.
9449///
9450/// This routine should be invoke whenever a given declaration is referenced
9451/// in the source code, and where that reference occurred. If this declaration
9452/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9453/// C99 6.9p3), then the declaration will be marked as used.
9454///
9455/// \param Loc the location where the declaration was referenced.
9456///
9457/// \param D the declaration that has been referenced by the source code.
9458void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9459 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009460
Douglas Gregorebada0772010-06-17 23:14:26 +00009461 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009462 return;
Mike Stump11289f42009-09-09 15:08:12 +00009463
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009464 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9465 // template or not. The reason for this is that unevaluated expressions
9466 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9467 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009468 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009469 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009470 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009471 return;
9472 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009473
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009474 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9475 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009476
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009477 // Do not mark anything as "used" within a dependent context; wait for
9478 // an instantiation.
9479 if (CurContext->isDependentContext())
9480 return;
Mike Stump11289f42009-09-09 15:08:12 +00009481
Douglas Gregorff790f12009-11-26 00:44:06 +00009482 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009483 case Unevaluated:
9484 // We are in an expression that is not potentially evaluated; do nothing.
9485 return;
Mike Stump11289f42009-09-09 15:08:12 +00009486
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009487 case PotentiallyEvaluated:
9488 // We are in a potentially-evaluated expression, so this declaration is
9489 // "used"; handle this below.
9490 break;
Mike Stump11289f42009-09-09 15:08:12 +00009491
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009492 case PotentiallyPotentiallyEvaluated:
9493 // We are in an expression that may be potentially evaluated; queue this
9494 // declaration reference until we know whether the expression is
9495 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009496 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009497 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009498
9499 case PotentiallyEvaluatedIfUsed:
9500 // Referenced declarations will only be used if the construct in the
9501 // containing expression is used.
9502 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009503 }
Mike Stump11289f42009-09-09 15:08:12 +00009504
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009505 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009506 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009507 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009508 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009509 if (Constructor->getParent()->hasTrivialConstructor())
9510 return;
9511 if (!Constructor->isUsed(false))
9512 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009513 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009514 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009515 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009516 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9517 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009518
Douglas Gregor88d292c2010-05-13 16:44:06 +00009519 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009520 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009521 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009522 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009523 if (Destructor->isVirtual())
9524 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009525 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9526 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9527 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009528 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009529 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009530 } else if (MethodDecl->isVirtual())
9531 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009532 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009533 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009534 // Recursive functions should be marked when used from another function.
9535 if (CurContext == Function) return;
9536
Mike Stump11289f42009-09-09 15:08:12 +00009537 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009538 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009539 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009540 bool AlreadyInstantiated = false;
9541 if (FunctionTemplateSpecializationInfo *SpecInfo
9542 = Function->getTemplateSpecializationInfo()) {
9543 if (SpecInfo->getPointOfInstantiation().isInvalid())
9544 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009545 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009546 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009547 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009548 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009549 = Function->getMemberSpecializationInfo()) {
9550 if (MSInfo->getPointOfInstantiation().isInvalid())
9551 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009552 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009553 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009554 AlreadyInstantiated = true;
9555 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009556
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009557 if (!AlreadyInstantiated) {
9558 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9559 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9560 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9561 Loc));
9562 else
Chandler Carruth54080172010-08-25 08:44:16 +00009563 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009564 }
John McCall83779672011-02-19 02:53:41 +00009565 } else {
9566 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009567 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9568 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009569 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009570 MarkDeclarationReferenced(Loc, *i);
9571 }
John McCall83779672011-02-19 02:53:41 +00009572 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009573
John McCall83779672011-02-19 02:53:41 +00009574 // Keep track of used but undefined functions.
9575 if (!Function->isPure() && !Function->hasBody() &&
9576 Function->getLinkage() != ExternalLinkage) {
9577 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9578 if (old.isInvalid()) old = Loc;
9579 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009580
John McCall83779672011-02-19 02:53:41 +00009581 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009582 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009583 }
Mike Stump11289f42009-09-09 15:08:12 +00009584
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009585 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009586 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009587 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009588 Var->getInstantiatedFromStaticDataMember()) {
9589 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9590 assert(MSInfo && "Missing member specialization information?");
9591 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9592 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9593 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009594 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009595 }
9596 }
Mike Stump11289f42009-09-09 15:08:12 +00009597
John McCall15dd4042011-02-21 19:25:48 +00009598 // Keep track of used but undefined variables. We make a hole in
9599 // the warning for static const data members with in-line
9600 // initializers.
John McCall83779672011-02-19 02:53:41 +00009601 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009602 && Var->getLinkage() != ExternalLinkage
9603 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009604 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9605 if (old.isInvalid()) old = Loc;
9606 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009607
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009608 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009609 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009610 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009611}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009612
Douglas Gregor5597ab42010-05-07 23:12:07 +00009613namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009614 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009615 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009616 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009617 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9618 Sema &S;
9619 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009620
Douglas Gregor5597ab42010-05-07 23:12:07 +00009621 public:
9622 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009623
Douglas Gregor5597ab42010-05-07 23:12:07 +00009624 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009625
9626 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9627 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009628 };
9629}
9630
Chandler Carruthaf80f662010-06-09 08:17:30 +00009631bool MarkReferencedDecls::TraverseTemplateArgument(
9632 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009633 if (Arg.getKind() == TemplateArgument::Declaration) {
9634 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9635 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009636
9637 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009638}
9639
Chandler Carruthaf80f662010-06-09 08:17:30 +00009640bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009641 if (ClassTemplateSpecializationDecl *Spec
9642 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9643 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009644 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009645 }
9646
Chandler Carruthc65667c2010-06-10 10:31:57 +00009647 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009648}
9649
9650void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9651 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009652 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009653}
9654
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009655namespace {
9656 /// \brief Helper class that marks all of the declarations referenced by
9657 /// potentially-evaluated subexpressions as "referenced".
9658 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9659 Sema &S;
9660
9661 public:
9662 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9663
9664 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9665
9666 void VisitDeclRefExpr(DeclRefExpr *E) {
9667 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9668 }
9669
9670 void VisitMemberExpr(MemberExpr *E) {
9671 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009672 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009673 }
9674
9675 void VisitCXXNewExpr(CXXNewExpr *E) {
9676 if (E->getConstructor())
9677 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9678 if (E->getOperatorNew())
9679 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9680 if (E->getOperatorDelete())
9681 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009682 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009683 }
9684
9685 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9686 if (E->getOperatorDelete())
9687 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009688 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9689 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9690 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9691 S.MarkDeclarationReferenced(E->getLocStart(),
9692 S.LookupDestructor(Record));
9693 }
9694
Douglas Gregor32b3de52010-09-11 23:32:50 +00009695 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009696 }
9697
9698 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9699 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009700 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009701 }
9702
9703 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9704 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9705 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009706
9707 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9708 Visit(E->getExpr());
9709 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009710 };
9711}
9712
9713/// \brief Mark any declarations that appear within this expression or any
9714/// potentially-evaluated subexpressions as "referenced".
9715void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9716 EvaluatedExprMarker(*this).Visit(E);
9717}
9718
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009719/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9720/// of the program being compiled.
9721///
9722/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009723/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009724/// possibility that the code will actually be executable. Code in sizeof()
9725/// expressions, code used only during overload resolution, etc., are not
9726/// potentially evaluated. This routine will suppress such diagnostics or,
9727/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009728/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009729/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009730///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009731/// This routine should be used for all diagnostics that describe the run-time
9732/// behavior of a program, such as passing a non-POD value through an ellipsis.
9733/// Failure to do so will likely result in spurious diagnostics or failures
9734/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009735bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009736 const PartialDiagnostic &PD) {
9737 switch (ExprEvalContexts.back().Context ) {
9738 case Unevaluated:
9739 // The argument will never be evaluated, so don't complain.
9740 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009741
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009742 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009743 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009744 if (stmt && getCurFunctionOrMethodDecl()) {
9745 FunctionScopes.back()->PossiblyUnreachableDiags.
9746 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9747 }
9748 else
9749 Diag(Loc, PD);
9750
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009751 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009752
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009753 case PotentiallyPotentiallyEvaluated:
9754 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9755 break;
9756 }
9757
9758 return false;
9759}
9760
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009761bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9762 CallExpr *CE, FunctionDecl *FD) {
9763 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9764 return false;
9765
9766 PartialDiagnostic Note =
9767 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9768 << FD->getDeclName() : PDiag();
9769 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009770
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009771 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009772 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009773 PDiag(diag::err_call_function_incomplete_return)
9774 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009775 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009776 << CE->getSourceRange(),
9777 std::make_pair(NoteLoc, Note)))
9778 return true;
9779
9780 return false;
9781}
9782
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009783// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009784// will prevent this condition from triggering, which is what we want.
9785void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9786 SourceLocation Loc;
9787
John McCall0506e4a2009-11-11 02:41:58 +00009788 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009789 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009790
John McCalld5707ab2009-10-12 21:59:07 +00009791 if (isa<BinaryOperator>(E)) {
9792 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009793 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009794 return;
9795
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009796 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9797
John McCallb0e419e2009-11-12 00:06:05 +00009798 // Greylist some idioms by putting them into a warning subcategory.
9799 if (ObjCMessageExpr *ME
9800 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9801 Selector Sel = ME->getSelector();
9802
John McCallb0e419e2009-11-12 00:06:05 +00009803 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009804 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009805 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9806
9807 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009808 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009809 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9810 }
John McCall0506e4a2009-11-11 02:41:58 +00009811
John McCalld5707ab2009-10-12 21:59:07 +00009812 Loc = Op->getOperatorLoc();
9813 } else if (isa<CXXOperatorCallExpr>(E)) {
9814 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009815 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009816 return;
9817
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009818 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009819 Loc = Op->getOperatorLoc();
9820 } else {
9821 // Not an assignment.
9822 return;
9823 }
9824
John McCalld5707ab2009-10-12 21:59:07 +00009825 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009826 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009827
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009828 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009829
9830 if (IsOrAssign)
9831 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9832 << FixItHint::CreateReplacement(Loc, "!=");
9833 else
9834 Diag(Loc, diag::note_condition_assign_to_comparison)
9835 << FixItHint::CreateReplacement(Loc, "==");
9836
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009837 Diag(Loc, diag::note_condition_assign_silence)
9838 << FixItHint::CreateInsertion(Open, "(")
9839 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009840}
9841
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009842/// \brief Redundant parentheses over an equality comparison can indicate
9843/// that the user intended an assignment used as condition.
9844void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009845 // Don't warn if the parens came from a macro.
9846 SourceLocation parenLoc = parenE->getLocStart();
9847 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9848 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009849 // Don't warn for dependent expressions.
9850 if (parenE->isTypeDependent())
9851 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009852
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009853 Expr *E = parenE->IgnoreParens();
9854
9855 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009856 if (opE->getOpcode() == BO_EQ &&
9857 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9858 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009859 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009860
Ted Kremenekae022092011-02-02 02:20:30 +00009861 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9862 Diag(Loc, diag::note_equality_comparison_to_assign)
9863 << FixItHint::CreateReplacement(Loc, "=");
9864 Diag(Loc, diag::note_equality_comparison_silence)
9865 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9866 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009867 }
9868}
9869
John McCalld5707ab2009-10-12 21:59:07 +00009870bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9871 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009872 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9873 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009874
9875 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009876 if (E->isBoundMemberFunction(Context))
9877 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9878 << E->getSourceRange();
9879
John McCall34376a62010-12-04 03:47:34 +00009880 if (getLangOptions().CPlusPlus)
9881 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9882
9883 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009884
9885 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009886 if (!T->isScalarType()) // C99 6.8.4.1p1
9887 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9888 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009889 }
9890
9891 return false;
9892}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009893
John McCalldadc5752010-08-24 06:29:42 +00009894ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9895 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009896 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009897 return ExprError();
9898
Douglas Gregorb412e172010-07-25 18:17:45 +00009899 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009900 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009901
9902 return Owned(Sub);
9903}
John McCall36e7fe32010-10-12 00:20:44 +00009904
9905/// Check for operands with placeholder types and complain if found.
9906/// Returns true if there was an error and no recovery was possible.
9907ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9908 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9909 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9910
9911 // If this is overload, check for a single overload.
Richard Smith30482bc2011-02-20 03:19:35 +00009912 assert(BT->getKind() == BuiltinType::Overload);
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009913 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
9914 E->getSourceRange(),
9915 QualType(),
9916 diag::err_ovl_unresolvable);
John McCall36e7fe32010-10-12 00:20:44 +00009917}