blob: a822c45b90d79c7ba35961a787f09d46ead3d407 [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;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000747 if (Literal.AnyWide)
748 StrTy = Context.getWCharType();
749 else if (Literal.Pascal)
750 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000751
752 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000753 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000754 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000755
Chris Lattner36fc8792008-02-11 00:02:17 +0000756 // Get an array type for the string, according to C99 6.4.5. This includes
757 // the nul terminator character as well as the string length for pascal
758 // strings.
759 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000760 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000761 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000762
Chris Lattner5b183d82006-11-10 05:03:26 +0000763 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000764 return Owned(StringLiteral::Create(Context, Literal.GetString(),
765 Literal.GetStringLength(),
766 Literal.AnyWide, StrTy,
767 &StringTokLocs[0],
768 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000769}
770
John McCallc63de662011-02-02 13:00:07 +0000771enum CaptureResult {
772 /// No capture is required.
773 CR_NoCapture,
774
775 /// A capture is required.
776 CR_Capture,
777
John McCall351762c2011-02-07 10:33:21 +0000778 /// A by-ref capture is required.
779 CR_CaptureByRef,
780
John McCallc63de662011-02-02 13:00:07 +0000781 /// An error occurred when trying to capture the given variable.
782 CR_Error
783};
784
785/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000786///
John McCallc63de662011-02-02 13:00:07 +0000787/// \param var - the variable referenced
788/// \param DC - the context which we couldn't capture through
789static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000790diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000791 VarDecl *var, DeclContext *DC) {
792 switch (S.ExprEvalContexts.back().Context) {
793 case Sema::Unevaluated:
794 // The argument will never be evaluated, so don't complain.
795 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000796
John McCallc63de662011-02-02 13:00:07 +0000797 case Sema::PotentiallyEvaluated:
798 case Sema::PotentiallyEvaluatedIfUsed:
799 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000800
John McCallc63de662011-02-02 13:00:07 +0000801 case Sema::PotentiallyPotentiallyEvaluated:
802 // FIXME: delay these!
803 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
John McCallc63de662011-02-02 13:00:07 +0000806 // Don't diagnose about capture if we're not actually in code right
807 // now; in general, there are more appropriate places that will
808 // diagnose this.
809 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
810
John McCall92d627e2011-03-22 23:15:50 +0000811 // Certain madnesses can happen with parameter declarations, which
812 // we want to ignore.
813 if (isa<ParmVarDecl>(var)) {
814 // - If the parameter still belongs to the translation unit, then
815 // we're actually just using one parameter in the declaration of
816 // the next. This is useful in e.g. VLAs.
817 if (isa<TranslationUnitDecl>(var->getDeclContext()))
818 return CR_NoCapture;
819
820 // - This particular madness can happen in ill-formed default
821 // arguments; claim it's okay and let downstream code handle it.
822 if (S.CurContext == var->getDeclContext()->getParent())
823 return CR_NoCapture;
824 }
John McCallc63de662011-02-02 13:00:07 +0000825
826 DeclarationName functionName;
827 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
828 functionName = fn->getDeclName();
829 // FIXME: variable from enclosing block that we couldn't capture from!
830
831 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
832 << var->getIdentifier() << functionName;
833 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
834 << var->getIdentifier();
835
836 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000837}
838
John McCall351762c2011-02-07 10:33:21 +0000839/// There is a well-formed capture at a particular scope level;
840/// propagate it through all the nested blocks.
841static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
842 const BlockDecl::Capture &capture) {
843 VarDecl *var = capture.getVariable();
844
845 // Update all the inner blocks with the capture information.
846 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
847 i != e; ++i) {
848 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
849 innerBlock->Captures.push_back(
850 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
851 /*nested*/ true, capture.getCopyExpr()));
852 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
853 }
854
855 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
856}
857
858/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000859/// given value in the current context requires a variable capture.
860///
861/// This also keeps the captures set in the BlockScopeInfo records
862/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000863static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000864 ValueDecl *value) {
865 // Only variables ever require capture.
866 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000867 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000868
869 // Fast path: variables from the current context never require capture.
870 DeclContext *DC = S.CurContext;
871 if (var->getDeclContext() == DC) return CR_NoCapture;
872
873 // Only variables with local storage require capture.
874 // FIXME: What about 'const' variables in C++?
875 if (!var->hasLocalStorage()) return CR_NoCapture;
876
877 // Otherwise, we need to capture.
878
879 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000880 do {
881 // Only blocks (and eventually C++0x closures) can capture; other
882 // scopes don't work.
883 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000884 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000885
886 BlockScopeInfo *blockScope =
887 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
888 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
889
John McCall351762c2011-02-07 10:33:21 +0000890 // Check whether we've already captured it in this block. If so,
891 // we're done.
892 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
893 return propagateCapture(S, functionScopesIndex,
894 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000895
896 functionScopesIndex--;
897 DC = cast<BlockDecl>(DC)->getDeclContext();
898 } while (var->getDeclContext() != DC);
899
John McCall351762c2011-02-07 10:33:21 +0000900 // Okay, we descended all the way to the block that defines the variable.
901 // Actually try to capture it.
902 QualType type = var->getType();
903
904 // Prohibit variably-modified types.
905 if (type->isVariablyModifiedType()) {
906 S.Diag(loc, diag::err_ref_vm_type);
907 S.Diag(var->getLocation(), diag::note_declared_at);
908 return CR_Error;
909 }
910
911 // Prohibit arrays, even in __block variables, but not references to
912 // them.
913 if (type->isArrayType()) {
914 S.Diag(loc, diag::err_ref_array_type);
915 S.Diag(var->getLocation(), diag::note_declared_at);
916 return CR_Error;
917 }
918
919 S.MarkDeclarationReferenced(loc, var);
920
921 // The BlocksAttr indicates the variable is bound by-reference.
922 bool byRef = var->hasAttr<BlocksAttr>();
923
924 // Build a copy expression.
925 Expr *copyExpr = 0;
926 if (!byRef && S.getLangOptions().CPlusPlus &&
927 !type->isDependentType() && type->isStructureOrClassType()) {
928 // According to the blocks spec, the capture of a variable from
929 // the stack requires a const copy constructor. This is not true
930 // of the copy/move done to move a __block variable to the heap.
931 type.addConst();
932
933 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
934 ExprResult result =
935 S.PerformCopyInitialization(
936 InitializedEntity::InitializeBlock(var->getLocation(),
937 type, false),
938 loc, S.Owned(declRef));
939
940 // Build a full-expression copy expression if initialization
941 // succeeded and used a non-trivial constructor. Recover from
942 // errors by pretending that the copy isn't necessary.
943 if (!result.isInvalid() &&
944 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
945 result = S.MaybeCreateExprWithCleanups(result);
946 copyExpr = result.take();
947 }
948 }
949
950 // We're currently at the declarer; go back to the closure.
951 functionScopesIndex++;
952 BlockScopeInfo *blockScope =
953 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
954
955 // Build a valid capture in this scope.
956 blockScope->Captures.push_back(
957 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
958 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
959
960 // Propagate that to inner captures if necessary.
961 return propagateCapture(S, functionScopesIndex,
962 blockScope->Captures.back());
963}
964
965static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
966 const DeclarationNameInfo &NameInfo,
967 bool byRef) {
968 assert(isa<VarDecl>(vd) && "capturing non-variable");
969
970 VarDecl *var = cast<VarDecl>(vd);
971 assert(var->hasLocalStorage() && "capturing non-local");
972 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
973
974 QualType exprType = var->getType().getNonReferenceType();
975
976 BlockDeclRefExpr *BDRE;
977 if (!byRef) {
978 // The variable will be bound by copy; make it const within the
979 // closure, but record that this was done in the expression.
980 bool constAdded = !exprType.isConstQualified();
981 exprType.addConst();
982
983 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
984 NameInfo.getLoc(), false,
985 constAdded);
986 } else {
987 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
988 NameInfo.getLoc(), true);
989 }
990
991 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000992}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000993
John McCalldadc5752010-08-24 06:29:42 +0000994ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000995Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000996 SourceLocation Loc,
997 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000998 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000999 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001000}
1001
John McCallf4cd4f92011-02-09 01:13:10 +00001002/// BuildDeclRefExpr - Build an expression that references a
1003/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001004ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001005Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001006 const DeclarationNameInfo &NameInfo,
1007 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001008 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001009
John McCall086a4642010-11-24 05:12:34 +00001010 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001011 SS? SS->getWithLocInContext(Context)
1012 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001013 D, NameInfo, Ty, VK);
1014
1015 // Just in case we're building an illegal pointer-to-member.
1016 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1017 E->setObjectKind(OK_BitField);
1018
1019 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001020}
1021
John McCallfeb624a2010-11-23 20:48:44 +00001022static ExprResult
1023BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1024 const CXXScopeSpec &SS, FieldDecl *Field,
1025 DeclAccessPair FoundDecl,
1026 const DeclarationNameInfo &MemberNameInfo);
1027
John McCalldadc5752010-08-24 06:29:42 +00001028ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001029Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1030 SourceLocation loc,
1031 IndirectFieldDecl *indirectField,
1032 Expr *baseObjectExpr,
1033 SourceLocation opLoc) {
1034 // First, build the expression that refers to the base object.
1035
1036 bool baseObjectIsPointer = false;
1037 Qualifiers baseQuals;
1038
1039 // Case 1: the base of the indirect field is not a field.
1040 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001041 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001042 if (baseVariable) {
1043 assert(baseVariable->getType()->isRecordType());
1044
1045 // In principle we could have a member access expression that
1046 // accesses an anonymous struct/union that's a static member of
1047 // the base object's class. However, under the current standard,
1048 // static data members cannot be anonymous structs or unions.
1049 // Supporting this is as easy as building a MemberExpr here.
1050 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1051
1052 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1053
1054 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001055 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001056 if (result.isInvalid()) return ExprError();
1057
1058 baseObjectExpr = result.take();
1059 baseObjectIsPointer = false;
1060 baseQuals = baseObjectExpr->getType().getQualifiers();
1061
1062 // Case 2: the base of the indirect field is a field and the user
1063 // wrote a member expression.
1064 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001065 // The caller provided the base object expression. Determine
1066 // whether its a pointer and whether it adds any qualifiers to the
1067 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001068 QualType objectType = baseObjectExpr->getType();
1069
1070 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1071 baseObjectIsPointer = true;
1072 objectType = ptr->getPointeeType();
1073 } else {
1074 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001075 }
John McCallf3a88602011-02-03 08:15:49 +00001076 baseQuals = objectType.getQualifiers();
1077
1078 // Case 3: the base of the indirect field is a field and we should
1079 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001080 } else {
1081 // We've found a member of an anonymous struct/union that is
1082 // inside a non-anonymous struct/union, so in a well-formed
1083 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001084 CXXMethodDecl *method = tryCaptureCXXThis();
1085 if (!method) {
1086 Diag(loc, diag::err_invalid_member_use_in_static_method)
1087 << indirectField->getDeclName();
1088 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001089 }
1090
John McCallf3a88602011-02-03 08:15:49 +00001091 // Our base object expression is "this".
1092 baseObjectExpr =
1093 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1094 /*isImplicit=*/ true);
1095 baseObjectIsPointer = true;
1096 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001097 }
1098
1099 // Build the implicit member references to the field of the
1100 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001101 Expr *result = baseObjectExpr;
1102 IndirectFieldDecl::chain_iterator
1103 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001104
John McCallf3a88602011-02-03 08:15:49 +00001105 // Build the first member access in the chain with full information.
1106 if (!baseVariable) {
1107 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001108
John McCallf3a88602011-02-03 08:15:49 +00001109 // FIXME: use the real found-decl info!
1110 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001111
John McCallf3a88602011-02-03 08:15:49 +00001112 // Make a nameInfo that properly uses the anonymous name.
1113 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001114
John McCallf3a88602011-02-03 08:15:49 +00001115 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001116 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001117 memberNameInfo).take();
1118 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001119
John McCallf3a88602011-02-03 08:15:49 +00001120 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001121 }
1122
John McCallf3a88602011-02-03 08:15:49 +00001123 // In all cases, we should now skip the first declaration in the chain.
1124 ++FI;
1125
Douglas Gregore10f36d2011-02-18 02:44:58 +00001126 while (FI != FEnd) {
1127 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001128
1129 // FIXME: these are somewhat meaningless
1130 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1131 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001132
1133 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001134 (FI == FEnd? SS : EmptySS), field,
1135 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001136 .take();
1137 }
1138
1139 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001140}
1141
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001142/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001143/// possibly a list of template arguments.
1144///
1145/// If this produces template arguments, it is permitted to call
1146/// DecomposeTemplateName.
1147///
1148/// This actually loses a lot of source location information for
1149/// non-standard name kinds; we should consider preserving that in
1150/// some way.
1151static void DecomposeUnqualifiedId(Sema &SemaRef,
1152 const UnqualifiedId &Id,
1153 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001154 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001155 const TemplateArgumentListInfo *&TemplateArgs) {
1156 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1157 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1158 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1159
1160 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1161 Id.TemplateId->getTemplateArgs(),
1162 Id.TemplateId->NumArgs);
1163 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1164 TemplateArgsPtr.release();
1165
John McCall3e56fd42010-08-23 07:28:44 +00001166 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001167 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1168 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001169 TemplateArgs = &Buffer;
1170 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001171 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001172 TemplateArgs = 0;
1173 }
1174}
1175
John McCall2d74de92009-12-01 22:10:20 +00001176/// Determines if the given class is provably not derived from all of
1177/// the prospective base classes.
1178static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1179 CXXRecordDecl *Record,
1180 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001181 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001182 return false;
1183
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001184 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001185 if (!RD) return false;
1186 Record = cast<CXXRecordDecl>(RD);
1187
John McCall2d74de92009-12-01 22:10:20 +00001188 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1189 E = Record->bases_end(); I != E; ++I) {
1190 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1191 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1192 if (!BaseRT) return false;
1193
1194 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001195 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1196 return false;
1197 }
1198
1199 return true;
1200}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001201
John McCall2d74de92009-12-01 22:10:20 +00001202enum IMAKind {
1203 /// The reference is definitely not an instance member access.
1204 IMA_Static,
1205
1206 /// The reference may be an implicit instance member access.
1207 IMA_Mixed,
1208
1209 /// The reference may be to an instance member, but it is invalid if
1210 /// so, because the context is not an instance method.
1211 IMA_Mixed_StaticContext,
1212
1213 /// The reference may be to an instance member, but it is invalid if
1214 /// so, because the context is from an unrelated class.
1215 IMA_Mixed_Unrelated,
1216
1217 /// The reference is definitely an implicit instance member access.
1218 IMA_Instance,
1219
1220 /// The reference may be to an unresolved using declaration.
1221 IMA_Unresolved,
1222
1223 /// The reference may be to an unresolved using declaration and the
1224 /// context is not an instance method.
1225 IMA_Unresolved_StaticContext,
1226
John McCall2d74de92009-12-01 22:10:20 +00001227 /// All possible referrents are instance members and the current
1228 /// context is not an instance method.
1229 IMA_Error_StaticContext,
1230
1231 /// All possible referrents are instance members of an unrelated
1232 /// class.
1233 IMA_Error_Unrelated
1234};
1235
1236/// The given lookup names class member(s) and is not being used for
1237/// an address-of-member expression. Classify the type of access
1238/// according to whether it's possible that this reference names an
1239/// instance member. This is best-effort; it is okay to
1240/// conservatively answer "yes", in which case some errors will simply
1241/// not be caught until template-instantiation.
1242static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1243 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001244 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001245
John McCall87fe5d52010-05-20 01:18:31 +00001246 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001247 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001248 (!isa<CXXMethodDecl>(DC) ||
1249 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001250
1251 if (R.isUnresolvableResult())
1252 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1253
1254 // Collect all the declaring classes of instance members we find.
1255 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001256 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001257 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1258 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001259 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001260
John McCalla8ae2222010-04-06 21:38:20 +00001261 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001262 if (dyn_cast<FieldDecl>(D))
1263 hasField = true;
1264
John McCall2d74de92009-12-01 22:10:20 +00001265 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001266 Classes.insert(R->getCanonicalDecl());
1267 }
1268 else
1269 hasNonInstance = true;
1270 }
1271
1272 // If we didn't find any instance members, it can't be an implicit
1273 // member reference.
1274 if (Classes.empty())
1275 return IMA_Static;
1276
1277 // If the current context is not an instance method, it can't be
1278 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001279 if (isStaticContext) {
1280 if (hasNonInstance)
1281 return IMA_Mixed_StaticContext;
1282
1283 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1284 // C++0x [expr.prim.general]p10:
1285 // An id-expression that denotes a non-static data member or non-static
1286 // member function of a class can only be used:
1287 // (...)
1288 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1289 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1290 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1291 if (isUnevaluatedExpression)
1292 return IMA_Mixed_StaticContext;
1293 }
1294
1295 return IMA_Error_StaticContext;
1296 }
John McCall2d74de92009-12-01 22:10:20 +00001297
1298 // If we can prove that the current context is unrelated to all the
1299 // declaring classes, it can't be an implicit member reference (in
1300 // which case it's an error if any of those members are selected).
1301 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001302 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001303 Classes))
1304 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1305
1306 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1307}
1308
1309/// Diagnose a reference to a field with no object available.
1310static void DiagnoseInstanceReference(Sema &SemaRef,
1311 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001312 NamedDecl *rep,
1313 const DeclarationNameInfo &nameInfo) {
1314 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001315 SourceRange Range(Loc);
1316 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1317
John McCallf3a88602011-02-03 08:15:49 +00001318 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1320 if (MD->isStatic()) {
1321 // "invalid use of member 'x' in static member function"
1322 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001323 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001324 return;
1325 }
1326 }
1327
1328 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001329 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001330 return;
1331 }
1332
1333 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001334}
1335
John McCalld681c392009-12-16 08:11:27 +00001336/// Diagnose an empty lookup.
1337///
1338/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001339bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1340 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001341 DeclarationName Name = R.getLookupName();
1342
John McCalld681c392009-12-16 08:11:27 +00001343 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001344 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001345 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1346 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001347 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001348 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001349 diagnostic_suggest = diag::err_undeclared_use_suggest;
1350 }
John McCalld681c392009-12-16 08:11:27 +00001351
Douglas Gregor598b08f2009-12-31 05:20:13 +00001352 // If the original lookup was an unqualified lookup, fake an
1353 // unqualified lookup. This is useful when (for example) the
1354 // original lookup would not have found something because it was a
1355 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001356 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001357 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001358 if (isa<CXXRecordDecl>(DC)) {
1359 LookupQualifiedName(R, DC);
1360
1361 if (!R.empty()) {
1362 // Don't give errors about ambiguities in this lookup.
1363 R.suppressDiagnostics();
1364
1365 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1366 bool isInstance = CurMethod &&
1367 CurMethod->isInstance() &&
1368 DC == CurMethod->getParent();
1369
1370 // Give a code modification hint to insert 'this->'.
1371 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1372 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001373 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001374 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1375 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001376 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001377 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001378 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001379 Diag(R.getNameLoc(), diagnostic) << Name
1380 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1381 QualType DepThisType = DepMethod->getThisType(Context);
1382 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1383 R.getNameLoc(), DepThisType, false);
1384 TemplateArgumentListInfo TList;
1385 if (ULE->hasExplicitTemplateArgs())
1386 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001387
Douglas Gregore16af532011-02-28 18:50:33 +00001388 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001389 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001390 CXXDependentScopeMemberExpr *DepExpr =
1391 CXXDependentScopeMemberExpr::Create(
1392 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001393 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001394 R.getLookupNameInfo(), &TList);
1395 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001396 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001397 // FIXME: we should be able to handle this case too. It is correct
1398 // to add this-> here. This is a workaround for PR7947.
1399 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001400 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001401 } else {
John McCalld681c392009-12-16 08:11:27 +00001402 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001403 }
John McCalld681c392009-12-16 08:11:27 +00001404
1405 // Do we really want to note all of these?
1406 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1407 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1408
1409 // Tell the callee to try to recover.
1410 return false;
1411 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001412
1413 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001414 }
1415 }
1416
Douglas Gregor598b08f2009-12-31 05:20:13 +00001417 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001418 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001419 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001420 if (!R.empty()) {
1421 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1422 if (SS.isEmpty())
1423 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1424 << FixItHint::CreateReplacement(R.getNameLoc(),
1425 R.getLookupName().getAsString());
1426 else
1427 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1428 << Name << computeDeclContext(SS, false) << R.getLookupName()
1429 << SS.getRange()
1430 << FixItHint::CreateReplacement(R.getNameLoc(),
1431 R.getLookupName().getAsString());
1432 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1433 Diag(ND->getLocation(), diag::note_previous_decl)
1434 << ND->getDeclName();
1435
1436 // Tell the callee to try to recover.
1437 return false;
1438 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001439
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001440 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1441 // FIXME: If we ended up with a typo for a type name or
1442 // Objective-C class name, we're in trouble because the parser
1443 // is in the wrong place to recover. Suggest the typo
1444 // correction, but don't make it a fix-it since we're not going
1445 // to recover well anyway.
1446 if (SS.isEmpty())
1447 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1448 else
1449 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1450 << Name << computeDeclContext(SS, false) << R.getLookupName()
1451 << SS.getRange();
1452
1453 // Don't try to recover; it won't work.
1454 return true;
1455 }
1456 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001457 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001458 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001459 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001460 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001461 else
Douglas Gregor25363982010-01-01 00:15:04 +00001462 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001463 << Name << computeDeclContext(SS, false) << Corrected
1464 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001465 return true;
1466 }
Douglas Gregor25363982010-01-01 00:15:04 +00001467 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001468 }
1469
1470 // Emit a special diagnostic for failed member lookups.
1471 // FIXME: computing the declaration context might fail here (?)
1472 if (!SS.isEmpty()) {
1473 Diag(R.getNameLoc(), diag::err_no_member)
1474 << Name << computeDeclContext(SS, false)
1475 << SS.getRange();
1476 return true;
1477 }
1478
John McCalld681c392009-12-16 08:11:27 +00001479 // Give up, we can't recover.
1480 Diag(R.getNameLoc(), diagnostic) << Name;
1481 return true;
1482}
1483
Douglas Gregor05fcf842010-11-02 20:36:02 +00001484ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1485 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001486 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1487 if (!IDecl)
1488 return 0;
1489 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1490 if (!ClassImpDecl)
1491 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001492 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001493 if (!property)
1494 return 0;
1495 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001496 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1497 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001498 return 0;
1499 return property;
1500}
1501
Douglas Gregor05fcf842010-11-02 20:36:02 +00001502bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1503 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1504 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1505 if (!IDecl)
1506 return false;
1507 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1508 if (!ClassImpDecl)
1509 return false;
1510 if (ObjCPropertyImplDecl *PIDecl
1511 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1512 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1513 PIDecl->getPropertyIvarDecl())
1514 return false;
1515
1516 return true;
1517}
1518
Fariborz Jahanian18722982010-07-17 00:59:30 +00001519static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001520 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001521 IdentifierInfo *II,
1522 SourceLocation NameLoc) {
1523 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001524 bool LookForIvars;
1525 if (Lookup.empty())
1526 LookForIvars = true;
1527 else if (CurMeth->isClassMethod())
1528 LookForIvars = false;
1529 else
1530 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001531 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1532 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001533 if (!LookForIvars)
1534 return 0;
1535
Fariborz Jahanian18722982010-07-17 00:59:30 +00001536 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1537 if (!IDecl)
1538 return 0;
1539 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001540 if (!ClassImpDecl)
1541 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001542 bool DynamicImplSeen = false;
1543 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1544 if (!property)
1545 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001546 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001547 DynamicImplSeen =
1548 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001549 // property implementation has a designated ivar. No need to assume a new
1550 // one.
1551 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1552 return 0;
1553 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001554 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001555 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1556 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001557 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001558 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001559 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001560 (Expr *)0, true);
1561 ClassImpDecl->addDecl(Ivar);
1562 IDecl->makeDeclVisibleInContext(Ivar, false);
1563 property->setPropertyIvarDecl(Ivar);
1564 return Ivar;
1565 }
1566 return 0;
1567}
1568
John McCalldadc5752010-08-24 06:29:42 +00001569ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001570 CXXScopeSpec &SS,
1571 UnqualifiedId &Id,
1572 bool HasTrailingLParen,
1573 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001574 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1575 "cannot be direct & operand and have a trailing lparen");
1576
1577 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001578 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001579
John McCall10eae182009-11-30 22:42:35 +00001580 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001581
1582 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001583 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001584 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001586
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001588 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001589 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001590
John McCalle66edc12009-11-24 19:00:30 +00001591 // C++ [temp.dep.expr]p3:
1592 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001593 // -- an identifier that was declared with a dependent type,
1594 // (note: handled after lookup)
1595 // -- a template-id that is dependent,
1596 // (note: handled in BuildTemplateIdExpr)
1597 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001598 // -- a nested-name-specifier that contains a class-name that
1599 // names a dependent type.
1600 // Determine whether this is a member of an unknown specialization;
1601 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001602 bool DependentID = false;
1603 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1604 Name.getCXXNameType()->isDependentType()) {
1605 DependentID = true;
1606 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001607 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001608 if (RequireCompleteDeclContext(SS, DC))
1609 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001610 } else {
1611 DependentID = true;
1612 }
1613 }
1614
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001615 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001616 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001617 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001618
Fariborz Jahanian86151342010-07-22 23:33:21 +00001619 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001620 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001621 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001622 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001623 // Lookup the template name again to correctly establish the context in
1624 // which it was found. This is really unfortunate as we already did the
1625 // lookup to determine that it was a template name in the first place. If
1626 // this becomes a performance hit, we can work harder to preserve those
1627 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001628 bool MemberOfUnknownSpecialization;
1629 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1630 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001631
1632 if (MemberOfUnknownSpecialization ||
1633 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1634 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1635 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001636 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001637 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001638 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Douglas Gregora5226932011-02-04 13:35:07 +00001640 // If the result might be in a dependent base class, this is a dependent
1641 // id-expression.
1642 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1643 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1644 TemplateArgs);
1645
John McCalle66edc12009-11-24 19:00:30 +00001646 // If this reference is in an Objective-C method, then we need to do
1647 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001648 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001649 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001650 if (E.isInvalid())
1651 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001652
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001653 if (Expr *Ex = E.takeAs<Expr>())
1654 return Owned(Ex);
1655
1656 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001657 if (getLangOptions().ObjCDefaultSynthProperties &&
1658 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001659 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1660 if (const ObjCPropertyDecl *Property =
1661 canSynthesizeProvisionalIvar(II)) {
1662 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1663 Diag(Property->getLocation(), diag::note_property_declare);
1664 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001665 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1666 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001667 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001668 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001669 // for further use, this must be set to false if in class method.
1670 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001671 }
Chris Lattner59a25942008-03-31 00:36:02 +00001672 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001673
John McCalle66edc12009-11-24 19:00:30 +00001674 if (R.isAmbiguous())
1675 return ExprError();
1676
Douglas Gregor171c45a2009-02-18 21:56:37 +00001677 // Determine whether this name might be a candidate for
1678 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001679 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001680
John McCalle66edc12009-11-24 19:00:30 +00001681 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001682 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001683 // in C90, extension in C99, forbidden in C++).
1684 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1685 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1686 if (D) R.addDecl(D);
1687 }
1688
1689 // If this name wasn't predeclared and if this is not a function
1690 // call, diagnose the problem.
1691 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001692 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001693 return ExprError();
1694
1695 assert(!R.empty() &&
1696 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001697
1698 // If we found an Objective-C instance variable, let
1699 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001700 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001701 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1702 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001703 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001704 assert(E.isInvalid() || E.get());
1705 return move(E);
1706 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001707 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCalle66edc12009-11-24 19:00:30 +00001710 // This is guaranteed from this point on.
1711 assert(!R.empty() || ADL);
1712
John McCall2d74de92009-12-01 22:10:20 +00001713 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001714 // C++ [class.mfct.non-static]p3:
1715 // When an id-expression that is not part of a class member access
1716 // syntax and not used to form a pointer to member is used in the
1717 // body of a non-static member function of class X, if name lookup
1718 // resolves the name in the id-expression to a non-static non-type
1719 // member of some class C, the id-expression is transformed into a
1720 // class member access expression using (*this) as the
1721 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001722 //
1723 // But we don't actually need to do this for '&' operands if R
1724 // resolved to a function or overloaded function set, because the
1725 // expression is ill-formed if it actually works out to be a
1726 // non-static member function:
1727 //
1728 // C++ [expr.ref]p4:
1729 // Otherwise, if E1.E2 refers to a non-static member function. . .
1730 // [t]he expression can be used only as the left-hand operand of a
1731 // member function call.
1732 //
1733 // There are other safeguards against such uses, but it's important
1734 // to get this right here so that we don't end up making a
1735 // spuriously dependent expression if we're inside a dependent
1736 // instance method.
John McCall57500772009-12-16 12:17:52 +00001737 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001738 bool MightBeImplicitMember;
1739 if (!isAddressOfOperand)
1740 MightBeImplicitMember = true;
1741 else if (!SS.isEmpty())
1742 MightBeImplicitMember = false;
1743 else if (R.isOverloadedResult())
1744 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001745 else if (R.isUnresolvableResult())
1746 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001747 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001748 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1749 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001750
1751 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001752 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001753 }
1754
John McCalle66edc12009-11-24 19:00:30 +00001755 if (TemplateArgs)
1756 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001757
John McCalle66edc12009-11-24 19:00:30 +00001758 return BuildDeclarationNameExpr(SS, R, ADL);
1759}
1760
John McCall57500772009-12-16 12:17:52 +00001761/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001762ExprResult
John McCall57500772009-12-16 12:17:52 +00001763Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1764 LookupResult &R,
1765 const TemplateArgumentListInfo *TemplateArgs) {
1766 switch (ClassifyImplicitMemberAccess(*this, R)) {
1767 case IMA_Instance:
1768 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1769
John McCall57500772009-12-16 12:17:52 +00001770 case IMA_Mixed:
1771 case IMA_Mixed_Unrelated:
1772 case IMA_Unresolved:
1773 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1774
1775 case IMA_Static:
1776 case IMA_Mixed_StaticContext:
1777 case IMA_Unresolved_StaticContext:
1778 if (TemplateArgs)
1779 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1780 return BuildDeclarationNameExpr(SS, R, false);
1781
1782 case IMA_Error_StaticContext:
1783 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001784 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1785 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001786 return ExprError();
1787 }
1788
1789 llvm_unreachable("unexpected instance member access kind");
1790 return ExprError();
1791}
1792
John McCall10eae182009-11-30 22:42:35 +00001793/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1794/// declaration name, generally during template instantiation.
1795/// There's a large number of things which don't need to be done along
1796/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001797ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001798Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001799 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001800 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001801 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001802 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001803
John McCall0b66eb32010-05-01 00:40:08 +00001804 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001805 return ExprError();
1806
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001807 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001808 LookupQualifiedName(R, DC);
1809
1810 if (R.isAmbiguous())
1811 return ExprError();
1812
1813 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001814 Diag(NameInfo.getLoc(), diag::err_no_member)
1815 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001816 return ExprError();
1817 }
1818
1819 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1820}
1821
1822/// LookupInObjCMethod - The parser has read a name in, and Sema has
1823/// detected that we're currently inside an ObjC method. Perform some
1824/// additional lookup.
1825///
1826/// Ideally, most of this would be done by lookup, but there's
1827/// actually quite a lot of extra work involved.
1828///
1829/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001830ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001831Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001832 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001833 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001834 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001835
John McCalle66edc12009-11-24 19:00:30 +00001836 // There are two cases to handle here. 1) scoped lookup could have failed,
1837 // in which case we should look for an ivar. 2) scoped lookup could have
1838 // found a decl, but that decl is outside the current instance method (i.e.
1839 // a global variable). In these two cases, we do a lookup for an ivar with
1840 // this name, if the lookup sucedes, we replace it our current decl.
1841
1842 // If we're in a class method, we don't normally want to look for
1843 // ivars. But if we don't find anything else, and there's an
1844 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001845 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001846
1847 bool LookForIvars;
1848 if (Lookup.empty())
1849 LookForIvars = true;
1850 else if (IsClassMethod)
1851 LookForIvars = false;
1852 else
1853 LookForIvars = (Lookup.isSingleResult() &&
1854 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001855 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001856 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001857 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001858 ObjCInterfaceDecl *ClassDeclared;
1859 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1860 // Diagnose using an ivar in a class method.
1861 if (IsClassMethod)
1862 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1863 << IV->getDeclName());
1864
1865 // If we're referencing an invalid decl, just return this as a silent
1866 // error node. The error diagnostic was already emitted on the decl.
1867 if (IV->isInvalidDecl())
1868 return ExprError();
1869
1870 // Check if referencing a field with __attribute__((deprecated)).
1871 if (DiagnoseUseOfDecl(IV, Loc))
1872 return ExprError();
1873
1874 // Diagnose the use of an ivar outside of the declaring class.
1875 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1876 ClassDeclared != IFace)
1877 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1878
1879 // FIXME: This should use a new expr for a direct reference, don't
1880 // turn this into Self->ivar, just return a BareIVarExpr or something.
1881 IdentifierInfo &II = Context.Idents.get("self");
1882 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001883 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001884 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001885 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001886 SelfName, false, false);
1887 if (SelfExpr.isInvalid())
1888 return ExprError();
1889
John McCall27584242010-12-06 20:48:59 +00001890 Expr *SelfE = SelfExpr.take();
1891 DefaultLvalueConversion(SelfE);
1892
John McCalle66edc12009-11-24 19:00:30 +00001893 MarkDeclarationReferenced(Loc, IV);
1894 return Owned(new (Context)
1895 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001896 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001897 }
Chris Lattner87313662010-04-12 05:10:17 +00001898 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001899 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001900 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001901 ObjCInterfaceDecl *ClassDeclared;
1902 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1903 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1904 IFace == ClassDeclared)
1905 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1906 }
1907 }
1908
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001909 if (Lookup.empty() && II && AllowBuiltinCreation) {
1910 // FIXME. Consolidate this with similar code in LookupName.
1911 if (unsigned BuiltinID = II->getBuiltinID()) {
1912 if (!(getLangOptions().CPlusPlus &&
1913 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1914 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1915 S, Lookup.isForRedeclaration(),
1916 Lookup.getNameLoc());
1917 if (D) Lookup.addDecl(D);
1918 }
1919 }
1920 }
John McCalle66edc12009-11-24 19:00:30 +00001921 // Sentinel value saying that we didn't do anything special.
1922 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001923}
John McCalld14a8642009-11-21 08:51:07 +00001924
John McCall16df1e52010-03-30 21:47:33 +00001925/// \brief Cast a base object to a member's actual type.
1926///
1927/// Logically this happens in three phases:
1928///
1929/// * First we cast from the base type to the naming class.
1930/// The naming class is the class into which we were looking
1931/// when we found the member; it's the qualifier type if a
1932/// qualifier was provided, and otherwise it's the base type.
1933///
1934/// * Next we cast from the naming class to the declaring class.
1935/// If the member we found was brought into a class's scope by
1936/// a using declaration, this is that class; otherwise it's
1937/// the class declaring the member.
1938///
1939/// * Finally we cast from the declaring class to the "true"
1940/// declaring class of the member. This conversion does not
1941/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001942bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001943Sema::PerformObjectMemberConversion(Expr *&From,
1944 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001945 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 NamedDecl *Member) {
1947 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1948 if (!RD)
1949 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001950
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001951 QualType DestRecordType;
1952 QualType DestType;
1953 QualType FromRecordType;
1954 QualType FromType = From->getType();
1955 bool PointerConversions = false;
1956 if (isa<FieldDecl>(Member)) {
1957 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 if (FromType->getAs<PointerType>()) {
1960 DestType = Context.getPointerType(DestRecordType);
1961 FromRecordType = FromType->getPointeeType();
1962 PointerConversions = true;
1963 } else {
1964 DestType = DestRecordType;
1965 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001966 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001967 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1968 if (Method->isStatic())
1969 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001970
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001971 DestType = Method->getThisType(Context);
1972 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 if (FromType->getAs<PointerType>()) {
1975 FromRecordType = FromType->getPointeeType();
1976 PointerConversions = true;
1977 } else {
1978 FromRecordType = FromType;
1979 DestType = DestRecordType;
1980 }
1981 } else {
1982 // No conversion necessary.
1983 return false;
1984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001985
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 if (DestType->isDependentType() || FromType->isDependentType())
1987 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001988
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 // If the unqualified types are the same, no conversion is necessary.
1990 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1991 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001992
John McCall16df1e52010-03-30 21:47:33 +00001993 SourceRange FromRange = From->getSourceRange();
1994 SourceLocation FromLoc = FromRange.getBegin();
1995
John McCall2536c6d2010-08-25 10:28:54 +00001996 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001997
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001999 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002000 // class name.
2001 //
2002 // If the member was a qualified name and the qualified referred to a
2003 // specific base subobject type, we'll cast to that intermediate type
2004 // first and then to the object in which the member is declared. That allows
2005 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2006 //
2007 // class Base { public: int x; };
2008 // class Derived1 : public Base { };
2009 // class Derived2 : public Base { };
2010 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2011 //
2012 // void VeryDerived::f() {
2013 // x = 17; // error: ambiguous base subobjects
2014 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2015 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002016 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002017 QualType QType = QualType(Qualifier->getAsType(), 0);
2018 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2019 assert(QType->isRecordType() && "lookup done with non-record type");
2020
2021 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2022
2023 // In C++98, the qualifier type doesn't actually have to be a base
2024 // type of the object type, in which case we just ignore it.
2025 // Otherwise build the appropriate casts.
2026 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002027 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002028 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002029 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002030 return true;
2031
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002032 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002033 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002034 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2035 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002036
2037 FromType = QType;
2038 FromRecordType = QRecordType;
2039
2040 // If the qualifier type was the same as the destination type,
2041 // we're done.
2042 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2043 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002044 }
2045 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002046
John McCall16df1e52010-03-30 21:47:33 +00002047 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048
John McCall16df1e52010-03-30 21:47:33 +00002049 // If we actually found the member through a using declaration, cast
2050 // down to the using declaration's type.
2051 //
2052 // Pointer equality is fine here because only one declaration of a
2053 // class ever has member declarations.
2054 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2055 assert(isa<UsingShadowDecl>(FoundDecl));
2056 QualType URecordType = Context.getTypeDeclType(
2057 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2058
2059 // We only need to do this if the naming-class to declaring-class
2060 // conversion is non-trivial.
2061 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2062 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002063 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002064 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002065 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002066 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002067
John McCall16df1e52010-03-30 21:47:33 +00002068 QualType UType = URecordType;
2069 if (PointerConversions)
2070 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002071 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002072 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002073 FromType = UType;
2074 FromRecordType = URecordType;
2075 }
2076
2077 // We don't do access control for the conversion from the
2078 // declaring class to the true declaring class.
2079 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002080 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002081
John McCallcf142162010-08-07 06:22:56 +00002082 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002083 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2084 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002085 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002086 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002087
John McCalle3027922010-08-25 11:45:40 +00002088 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002089 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002090 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002091}
Douglas Gregor3256d042009-06-30 15:47:41 +00002092
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002093/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002094static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002095 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002096 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002097 const DeclarationNameInfo &MemberNameInfo,
2098 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002099 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002100 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002101 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002102 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002103 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002104}
2105
John McCallfeb624a2010-11-23 20:48:44 +00002106static ExprResult
2107BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2108 const CXXScopeSpec &SS, FieldDecl *Field,
2109 DeclAccessPair FoundDecl,
2110 const DeclarationNameInfo &MemberNameInfo) {
2111 // x.a is an l-value if 'a' has a reference type. Otherwise:
2112 // x.a is an l-value/x-value/pr-value if the base is (and note
2113 // that *x is always an l-value), except that if the base isn't
2114 // an ordinary object then we must have an rvalue.
2115 ExprValueKind VK = VK_LValue;
2116 ExprObjectKind OK = OK_Ordinary;
2117 if (!IsArrow) {
2118 if (BaseExpr->getObjectKind() == OK_Ordinary)
2119 VK = BaseExpr->getValueKind();
2120 else
2121 VK = VK_RValue;
2122 }
2123 if (VK != VK_RValue && Field->isBitField())
2124 OK = OK_BitField;
2125
2126 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2127 QualType MemberType = Field->getType();
2128 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2129 MemberType = Ref->getPointeeType();
2130 VK = VK_LValue;
2131 } else {
2132 QualType BaseType = BaseExpr->getType();
2133 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2134
2135 Qualifiers BaseQuals = BaseType.getQualifiers();
2136
2137 // GC attributes are never picked up by members.
2138 BaseQuals.removeObjCGCAttr();
2139
2140 // CVR attributes from the base are picked up by members,
2141 // except that 'mutable' members don't pick up 'const'.
2142 if (Field->isMutable()) BaseQuals.removeConst();
2143
2144 Qualifiers MemberQuals
2145 = S.Context.getCanonicalType(MemberType).getQualifiers();
2146
2147 // TR 18037 does not allow fields to be declared with address spaces.
2148 assert(!MemberQuals.hasAddressSpace());
2149
2150 Qualifiers Combined = BaseQuals + MemberQuals;
2151 if (Combined != MemberQuals)
2152 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2153 }
2154
2155 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2156 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2157 FoundDecl, Field))
2158 return ExprError();
2159 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2160 Field, FoundDecl, MemberNameInfo,
2161 MemberType, VK, OK));
2162}
2163
John McCall2d74de92009-12-01 22:10:20 +00002164/// Builds an implicit member access expression. The current context
2165/// is known to be an instance method, and the given unqualified lookup
2166/// set is known to contain only instance members, at least one of which
2167/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002168ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002169Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2170 LookupResult &R,
2171 const TemplateArgumentListInfo *TemplateArgs,
2172 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002173 assert(!R.empty() && !R.isAmbiguous());
2174
John McCallf3a88602011-02-03 08:15:49 +00002175 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002176
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002177 // We may have found a field within an anonymous union or struct
2178 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002179 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002180 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002181 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002182
John McCallf3a88602011-02-03 08:15:49 +00002183 // If this is known to be an instance access, go ahead and build an
2184 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002185 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002186 CXXMethodDecl *method = tryCaptureCXXThis();
2187 assert(method && "didn't correctly pre-flight capture of 'this'");
2188
2189 QualType thisType = method->getThisType(Context);
2190 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002191 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002192 SourceLocation Loc = R.getNameLoc();
2193 if (SS.getRange().isValid())
2194 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002195 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002196 }
2197
John McCallf3a88602011-02-03 08:15:49 +00002198 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002199 /*OpLoc*/ SourceLocation(),
2200 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002201 SS,
2202 /*FirstQualifierInScope*/ 0,
2203 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002204}
2205
John McCalle66edc12009-11-24 19:00:30 +00002206bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002207 const LookupResult &R,
2208 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002209 // Only when used directly as the postfix-expression of a call.
2210 if (!HasTrailingLParen)
2211 return false;
2212
2213 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002214 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002215 return false;
2216
2217 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002218 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002219 return false;
2220
2221 // Turn off ADL when we find certain kinds of declarations during
2222 // normal lookup:
2223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2224 NamedDecl *D = *I;
2225
2226 // C++0x [basic.lookup.argdep]p3:
2227 // -- a declaration of a class member
2228 // Since using decls preserve this property, we check this on the
2229 // original decl.
John McCall57500772009-12-16 12:17:52 +00002230 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002231 return false;
2232
2233 // C++0x [basic.lookup.argdep]p3:
2234 // -- a block-scope function declaration that is not a
2235 // using-declaration
2236 // NOTE: we also trigger this for function templates (in fact, we
2237 // don't check the decl type at all, since all other decl types
2238 // turn off ADL anyway).
2239 if (isa<UsingShadowDecl>(D))
2240 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2241 else if (D->getDeclContext()->isFunctionOrMethod())
2242 return false;
2243
2244 // C++0x [basic.lookup.argdep]p3:
2245 // -- a declaration that is neither a function or a function
2246 // template
2247 // And also for builtin functions.
2248 if (isa<FunctionDecl>(D)) {
2249 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2250
2251 // But also builtin functions.
2252 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2253 return false;
2254 } else if (!isa<FunctionTemplateDecl>(D))
2255 return false;
2256 }
2257
2258 return true;
2259}
2260
2261
John McCalld14a8642009-11-21 08:51:07 +00002262/// Diagnoses obvious problems with the use of the given declaration
2263/// as an expression. This is only actually called for lookups that
2264/// were not overloaded, and it doesn't promise that the declaration
2265/// will in fact be used.
2266static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2267 if (isa<TypedefDecl>(D)) {
2268 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2269 return true;
2270 }
2271
2272 if (isa<ObjCInterfaceDecl>(D)) {
2273 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2274 return true;
2275 }
2276
2277 if (isa<NamespaceDecl>(D)) {
2278 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2279 return true;
2280 }
2281
2282 return false;
2283}
2284
John McCalldadc5752010-08-24 06:29:42 +00002285ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002286Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002287 LookupResult &R,
2288 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002289 // If this is a single, fully-resolved result and we don't need ADL,
2290 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002291 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002292 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2293 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002294
2295 // We only need to check the declaration if there's exactly one
2296 // result, because in the overloaded case the results can only be
2297 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002298 if (R.isSingleResult() &&
2299 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002300 return ExprError();
2301
John McCall58cc69d2010-01-27 01:50:18 +00002302 // Otherwise, just build an unresolved lookup expression. Suppress
2303 // any lookup-related diagnostics; we'll hash these out later, when
2304 // we've picked a target.
2305 R.suppressDiagnostics();
2306
John McCalld14a8642009-11-21 08:51:07 +00002307 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002308 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002309 SS.getWithLocInContext(Context),
2310 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002311 NeedsADL, R.isOverloadedResult(),
2312 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002313
2314 return Owned(ULE);
2315}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002316
John McCalld14a8642009-11-21 08:51:07 +00002317/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002318ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002319Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002320 const DeclarationNameInfo &NameInfo,
2321 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002322 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002323 assert(!isa<FunctionTemplateDecl>(D) &&
2324 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002325
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002326 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002327 if (CheckDeclInExpr(*this, Loc, D))
2328 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002329
Douglas Gregore7488b92009-12-01 16:58:18 +00002330 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2331 // Specifically diagnose references to class templates that are missing
2332 // a template argument list.
2333 Diag(Loc, diag::err_template_decl_ref)
2334 << Template << SS.getRange();
2335 Diag(Template->getLocation(), diag::note_template_decl_here);
2336 return ExprError();
2337 }
2338
2339 // Make sure that we're referring to a value.
2340 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2341 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002342 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002343 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002344 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002345 return ExprError();
2346 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002347
Douglas Gregor171c45a2009-02-18 21:56:37 +00002348 // Check whether this declaration can be used. Note that we suppress
2349 // this check when we're going to perform argument-dependent lookup
2350 // on this function name, because this might not be the function
2351 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002352 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002353 return ExprError();
2354
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002355 // Only create DeclRefExpr's for valid Decl's.
2356 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002357 return ExprError();
2358
John McCallf3a88602011-02-03 08:15:49 +00002359 // Handle members of anonymous structs and unions. If we got here,
2360 // and the reference is to a class member indirect field, then this
2361 // must be the subject of a pointer-to-member expression.
2362 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2363 if (!indirectField->isCXXClassMember())
2364 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2365 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002366
Chris Lattner2a9d9892008-10-20 05:16:36 +00002367 // If the identifier reference is inside a block, and it refers to a value
2368 // that is outside the block, create a BlockDeclRefExpr instead of a
2369 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2370 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002371 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002372 // We do not do this for things like enum constants, global variables, etc,
2373 // as they do not get snapshotted.
2374 //
John McCall351762c2011-02-07 10:33:21 +00002375 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002376 case CR_Error:
2377 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002378
John McCallc63de662011-02-02 13:00:07 +00002379 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002380 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2381 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2382
2383 case CR_CaptureByRef:
2384 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2385 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002386
2387 case CR_NoCapture: {
2388 // If this reference is not in a block or if the referenced
2389 // variable is within the block, create a normal DeclRefExpr.
2390
2391 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002392 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002393
2394 switch (D->getKind()) {
2395 // Ignore all the non-ValueDecl kinds.
2396#define ABSTRACT_DECL(kind)
2397#define VALUE(type, base)
2398#define DECL(type, base) \
2399 case Decl::type:
2400#include "clang/AST/DeclNodes.inc"
2401 llvm_unreachable("invalid value decl kind");
2402 return ExprError();
2403
2404 // These shouldn't make it here.
2405 case Decl::ObjCAtDefsField:
2406 case Decl::ObjCIvar:
2407 llvm_unreachable("forming non-member reference to ivar?");
2408 return ExprError();
2409
2410 // Enum constants are always r-values and never references.
2411 // Unresolved using declarations are dependent.
2412 case Decl::EnumConstant:
2413 case Decl::UnresolvedUsingValue:
2414 valueKind = VK_RValue;
2415 break;
2416
2417 // Fields and indirect fields that got here must be for
2418 // pointer-to-member expressions; we just call them l-values for
2419 // internal consistency, because this subexpression doesn't really
2420 // exist in the high-level semantics.
2421 case Decl::Field:
2422 case Decl::IndirectField:
2423 assert(getLangOptions().CPlusPlus &&
2424 "building reference to field in C?");
2425
2426 // These can't have reference type in well-formed programs, but
2427 // for internal consistency we do this anyway.
2428 type = type.getNonReferenceType();
2429 valueKind = VK_LValue;
2430 break;
2431
2432 // Non-type template parameters are either l-values or r-values
2433 // depending on the type.
2434 case Decl::NonTypeTemplateParm: {
2435 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2436 type = reftype->getPointeeType();
2437 valueKind = VK_LValue; // even if the parameter is an r-value reference
2438 break;
2439 }
2440
2441 // For non-references, we need to strip qualifiers just in case
2442 // the template parameter was declared as 'const int' or whatever.
2443 valueKind = VK_RValue;
2444 type = type.getUnqualifiedType();
2445 break;
2446 }
2447
2448 case Decl::Var:
2449 // In C, "extern void blah;" is valid and is an r-value.
2450 if (!getLangOptions().CPlusPlus &&
2451 !type.hasQualifiers() &&
2452 type->isVoidType()) {
2453 valueKind = VK_RValue;
2454 break;
2455 }
2456 // fallthrough
2457
2458 case Decl::ImplicitParam:
2459 case Decl::ParmVar:
2460 // These are always l-values.
2461 valueKind = VK_LValue;
2462 type = type.getNonReferenceType();
2463 break;
2464
2465 case Decl::Function: {
2466 // Functions are l-values in C++.
2467 if (getLangOptions().CPlusPlus) {
2468 valueKind = VK_LValue;
2469 break;
2470 }
2471
2472 // C99 DR 316 says that, if a function type comes from a
2473 // function definition (without a prototype), that type is only
2474 // used for checking compatibility. Therefore, when referencing
2475 // the function, we pretend that we don't have the full function
2476 // type.
2477 if (!cast<FunctionDecl>(VD)->hasPrototype())
2478 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2479 type = Context.getFunctionNoProtoType(proto->getResultType(),
2480 proto->getExtInfo());
2481
2482 // Functions are r-values in C.
2483 valueKind = VK_RValue;
2484 break;
2485 }
2486
2487 case Decl::CXXMethod:
2488 // C++ methods are l-values if static, r-values if non-static.
2489 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2490 valueKind = VK_LValue;
2491 break;
2492 }
2493 // fallthrough
2494
2495 case Decl::CXXConversion:
2496 case Decl::CXXDestructor:
2497 case Decl::CXXConstructor:
2498 valueKind = VK_RValue;
2499 break;
2500 }
2501
2502 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2503 }
2504
John McCallc63de662011-02-02 13:00:07 +00002505 }
John McCall7decc9e2010-11-18 06:31:45 +00002506
John McCall351762c2011-02-07 10:33:21 +00002507 llvm_unreachable("unknown capture result");
2508 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002509}
Chris Lattnere168f762006-11-10 05:29:30 +00002510
John McCalldadc5752010-08-24 06:29:42 +00002511ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002513 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002514
Chris Lattnere168f762006-11-10 05:29:30 +00002515 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002516 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002517 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2518 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2519 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002520 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002521
Chris Lattnera81a0272008-01-12 08:14:25 +00002522 // Pre-defined identifiers are of type char[x], where x is the length of the
2523 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002524
Anders Carlsson2fb08242009-09-08 18:24:21 +00002525 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002526 if (!currentDecl && getCurBlock())
2527 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002528 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002529 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002530 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002531 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002532
Anders Carlsson0b209a82009-09-11 01:22:35 +00002533 QualType ResTy;
2534 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2535 ResTy = Context.DependentTy;
2536 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002537 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002538
Anders Carlsson0b209a82009-09-11 01:22:35 +00002539 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002540 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002541 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2542 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002543 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002544}
2545
John McCalldadc5752010-08-24 06:29:42 +00002546ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002547 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002548 bool Invalid = false;
2549 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2550 if (Invalid)
2551 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002552
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002553 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2554 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002555 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002556 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002557
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002558 QualType Ty;
2559 if (!getLangOptions().CPlusPlus)
2560 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2561 else if (Literal.isWide())
2562 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002563 else if (Literal.isMultiChar())
2564 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002565 else
2566 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002567
Sebastian Redl20614a72009-01-20 22:23:13 +00002568 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2569 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002570 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002571}
2572
John McCalldadc5752010-08-24 06:29:42 +00002573ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002574 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002575 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2576 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002577 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002578 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002579 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002580 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002581 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002582
Chris Lattner23b7eb62007-06-15 23:05:46 +00002583 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002584 // Add padding so that NumericLiteralParser can overread by one character.
2585 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002586 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002587
Chris Lattner67ca9252007-05-21 01:08:44 +00002588 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002589 bool Invalid = false;
2590 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2591 if (Invalid)
2592 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002593
Mike Stump11289f42009-09-09 15:08:12 +00002594 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002595 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002596 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002597 return ExprError();
2598
Chris Lattner1c20a172007-08-26 03:42:43 +00002599 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002600
Chris Lattner1c20a172007-08-26 03:42:43 +00002601 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002602 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002603 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002604 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002605 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002606 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002607 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002608 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002609
2610 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2611
John McCall53b93a02009-12-24 09:08:04 +00002612 using llvm::APFloat;
2613 APFloat Val(Format);
2614
2615 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002616
2617 // Overflow is always an error, but underflow is only an error if
2618 // we underflowed to zero (APFloat reports denormals as underflow).
2619 if ((result & APFloat::opOverflow) ||
2620 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002621 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002622 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002623 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002624 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002625 APFloat::getLargest(Format).toString(buffer);
2626 } else {
John McCall62abc942010-02-26 23:35:57 +00002627 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002628 APFloat::getSmallest(Format).toString(buffer);
2629 }
2630
2631 Diag(Tok.getLocation(), diagnostic)
2632 << Ty
2633 << llvm::StringRef(buffer.data(), buffer.size());
2634 }
2635
2636 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002637 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002638
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002639 if (Ty == Context.DoubleTy) {
2640 if (getLangOptions().SinglePrecisionConstants) {
2641 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2642 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2643 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2644 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2645 }
2646 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002647 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002648 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002649 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002650 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002651
Neil Boothac582c52007-08-29 22:00:19 +00002652 // long long is a C99 feature.
2653 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002654 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002655 Diag(Tok.getLocation(), diag::ext_longlong);
2656
Chris Lattner67ca9252007-05-21 01:08:44 +00002657 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002658 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002659
Chris Lattner67ca9252007-05-21 01:08:44 +00002660 if (Literal.GetIntegerValue(ResultVal)) {
2661 // If this value didn't fit into uintmax_t, warn and force to ull.
2662 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002663 Ty = Context.UnsignedLongLongTy;
2664 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002665 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002666 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002667 // If this value fits into a ULL, try to figure out what else it fits into
2668 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002669
Chris Lattner67ca9252007-05-21 01:08:44 +00002670 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2671 // be an unsigned int.
2672 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2673
2674 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002675 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002676 if (!Literal.isLong && !Literal.isLongLong) {
2677 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002678 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002679
Chris Lattner67ca9252007-05-21 01:08:44 +00002680 // Does it fit in a unsigned int?
2681 if (ResultVal.isIntN(IntSize)) {
2682 // Does it fit in a signed int?
2683 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002685 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002686 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002687 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002688 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002690
Chris Lattner67ca9252007-05-21 01:08:44 +00002691 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002692 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002693 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002694
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 // Does it fit in a unsigned long?
2696 if (ResultVal.isIntN(LongSize)) {
2697 // Does it fit in a signed long?
2698 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002699 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002700 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002701 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002702 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002703 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002704 }
2705
Chris Lattner67ca9252007-05-21 01:08:44 +00002706 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002707 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002708 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002709
Chris Lattner67ca9252007-05-21 01:08:44 +00002710 // Does it fit in a unsigned long long?
2711 if (ResultVal.isIntN(LongLongSize)) {
2712 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002713 // To be compatible with MSVC, hex integer literals ending with the
2714 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002715 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2716 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002718 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002719 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002720 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002721 }
2722 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002723
Chris Lattner67ca9252007-05-21 01:08:44 +00002724 // If we still couldn't decide a type, we probably have something that
2725 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002726 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002727 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002728 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002729 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002730 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002731
Chris Lattner55258cf2008-05-09 05:59:00 +00002732 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002733 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002734 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002735 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002736 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002737
Chris Lattner1c20a172007-08-26 03:42:43 +00002738 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2739 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002740 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002741 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002742
2743 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002744}
2745
John McCalldadc5752010-08-24 06:29:42 +00002746ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002747 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002748 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002749 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002750}
2751
Steve Naroff71b59a92007-06-04 22:22:31 +00002752/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002753/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002754bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2755 SourceLocation OpLoc,
2756 SourceRange ExprRange,
2757 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002758 if (exprType->isDependentType())
2759 return false;
2760
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002761 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2762 // the result is the size of the referenced type."
2763 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2764 // result shall be the alignment of the referenced type."
2765 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2766 exprType = Ref->getPointeeType();
2767
Peter Collingbournee190dee2011-03-11 19:24:49 +00002768 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2769 // scalar or vector data type argument..."
2770 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2771 // type (C99 6.2.5p18) or void.
2772 if (ExprKind == UETT_VecStep) {
2773 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2774 exprType->isVectorType())) {
2775 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2776 << exprType << ExprRange;
2777 return true;
2778 }
2779 }
2780
Steve Naroff043d45d2007-05-15 02:32:35 +00002781 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002782 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002783 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002784 if (ExprKind == UETT_SizeOf)
2785 Diag(OpLoc, diag::ext_sizeof_function_type)
2786 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002787 return false;
2788 }
Mike Stump11289f42009-09-09 15:08:12 +00002789
Peter Collingbournee190dee2011-03-11 19:24:49 +00002790 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2791 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002792 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002793 if (ExprKind != UETT_VecStep)
2794 Diag(OpLoc, diag::ext_sizeof_void_type)
2795 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002796 return false;
2797 }
Mike Stump11289f42009-09-09 15:08:12 +00002798
Chris Lattner62975a72009-04-24 00:30:45 +00002799 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002800 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002801 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002802 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002803
Chris Lattner62975a72009-04-24 00:30:45 +00002804 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002805 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002806 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002807 << exprType << (ExprKind == UETT_SizeOf)
2808 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002809 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
Chris Lattner62975a72009-04-24 00:30:45 +00002812 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002813}
2814
John McCall36e7fe32010-10-12 00:20:44 +00002815static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2816 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002817 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002818
Mike Stump11289f42009-09-09 15:08:12 +00002819 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002820 if (isa<DeclRefExpr>(E))
2821 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002822
2823 // Cannot know anything else if the expression is dependent.
2824 if (E->isTypeDependent())
2825 return false;
2826
Douglas Gregor71235ec2009-05-02 02:18:30 +00002827 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002828 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002829 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002830 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002831
2832 // Alignment of a field access is always okay, so long as it isn't a
2833 // bit-field.
2834 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002835 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002836 return false;
2837
Peter Collingbournee190dee2011-03-11 19:24:49 +00002838 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2839 UETT_AlignOf);
2840}
2841
2842bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2843 SourceRange ExprRange) {
2844 E = E->IgnoreParens();
2845
2846 // Cannot know anything else if the expression is dependent.
2847 if (E->isTypeDependent())
2848 return false;
2849
2850 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2851 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002852}
2853
Douglas Gregor0950e412009-03-13 21:01:28 +00002854/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002855ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002856Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2857 SourceLocation OpLoc,
2858 UnaryExprOrTypeTrait ExprKind,
2859 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002860 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002861 return ExprError();
2862
John McCallbcd03502009-12-07 02:54:59 +00002863 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002864
Douglas Gregor0950e412009-03-13 21:01:28 +00002865 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002866 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002867 return ExprError();
2868
2869 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002870 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2871 Context.getSizeType(),
2872 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002873}
2874
2875/// \brief Build a sizeof or alignof expression given an expression
2876/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002877ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002878Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2879 UnaryExprOrTypeTrait ExprKind,
2880 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002881 // Verify that the operand is valid.
2882 bool isInvalid = false;
2883 if (E->isTypeDependent()) {
2884 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002885 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002886 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002887 } else if (ExprKind == UETT_VecStep) {
2888 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002889 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002890 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2891 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002892 } else if (E->getType()->isPlaceholderType()) {
2893 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2894 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002895 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002896 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2898 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002899 }
2900
2901 if (isInvalid)
2902 return ExprError();
2903
2904 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002905 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2906 Context.getSizeType(),
2907 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002908}
2909
Peter Collingbournee190dee2011-03-11 19:24:49 +00002910/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2911/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002912/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002913ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002914Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2915 UnaryExprOrTypeTrait ExprKind, bool isType,
2916 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002917 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002918 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002919
Sebastian Redl6f282892008-11-11 17:56:53 +00002920 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002921 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002922 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002923 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002924 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002925
Douglas Gregor0950e412009-03-13 21:01:28 +00002926 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002927 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002928 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2929 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002930
Douglas Gregor0950e412009-03-13 21:01:28 +00002931 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002932}
2933
John McCall4bc41ae2010-11-18 19:01:18 +00002934static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2935 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002936 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002937 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002938
John McCall34376a62010-12-04 03:47:34 +00002939 // _Real and _Imag are only l-values for normal l-values.
2940 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002941 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002942
Chris Lattnere267f5d2007-08-26 05:39:26 +00002943 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002944 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002945 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002946
Chris Lattnere267f5d2007-08-26 05:39:26 +00002947 // Otherwise they pass through real integer and floating point types here.
2948 if (V->getType()->isArithmeticType())
2949 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002950
John McCall36226622010-10-12 02:09:17 +00002951 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002952 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002953 if (PR.isInvalid()) return QualType();
2954 if (PR.take() != V) {
2955 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002956 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002957 }
2958
Chris Lattnere267f5d2007-08-26 05:39:26 +00002959 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002960 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002961 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002962 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002963}
2964
2965
Chris Lattnere168f762006-11-10 05:29:30 +00002966
John McCalldadc5752010-08-24 06:29:42 +00002967ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002969 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002970 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002971 switch (Kind) {
2972 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002973 case tok::plusplus: Opc = UO_PostInc; break;
2974 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002975 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002976
John McCallb268a282010-08-23 23:25:46 +00002977 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002978}
2979
John McCall4bc41ae2010-11-18 19:01:18 +00002980/// Expressions of certain arbitrary types are forbidden by C from
2981/// having l-value type. These are:
2982/// - 'void', but not qualified void
2983/// - function types
2984///
2985/// The exact rule here is C99 6.3.2.1:
2986/// An lvalue is an expression with an object type or an incomplete
2987/// type other than void.
2988static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2989 return ((T->isVoidType() && !T.hasQualifiers()) ||
2990 T->isFunctionType());
2991}
2992
John McCalldadc5752010-08-24 06:29:42 +00002993ExprResult
John McCallb268a282010-08-23 23:25:46 +00002994Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2995 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002996 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002997 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002998 if (Result.isInvalid()) return ExprError();
2999 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003000
John McCallb268a282010-08-23 23:25:46 +00003001 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003002
Douglas Gregor40412ac2008-11-19 17:17:41 +00003003 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003004 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003005 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003006 Context.DependentTy,
3007 VK_LValue, OK_Ordinary,
3008 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003009 }
3010
Mike Stump11289f42009-09-09 15:08:12 +00003011 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003012 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003013 LHSExp->getType()->isEnumeralType() ||
3014 RHSExp->getType()->isRecordType() ||
3015 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003016 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003017 }
3018
John McCallb268a282010-08-23 23:25:46 +00003019 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003020}
3021
3022
John McCalldadc5752010-08-24 06:29:42 +00003023ExprResult
John McCallb268a282010-08-23 23:25:46 +00003024Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3025 Expr *Idx, SourceLocation RLoc) {
3026 Expr *LHSExp = Base;
3027 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003028
Chris Lattner36d572b2007-07-16 00:14:47 +00003029 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00003030 if (!LHSExp->getType()->getAs<VectorType>())
3031 DefaultFunctionArrayLvalueConversion(LHSExp);
3032 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003033
Chris Lattner36d572b2007-07-16 00:14:47 +00003034 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003035 ExprValueKind VK = VK_LValue;
3036 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003037
Steve Naroffc1aadb12007-03-28 21:49:40 +00003038 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003039 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003040 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003041 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003042 Expr *BaseExpr, *IndexExpr;
3043 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003044 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3045 BaseExpr = LHSExp;
3046 IndexExpr = RHSExp;
3047 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003048 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003049 BaseExpr = LHSExp;
3050 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003051 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003052 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003053 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003054 BaseExpr = RHSExp;
3055 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003056 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003057 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003058 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003059 BaseExpr = LHSExp;
3060 IndexExpr = RHSExp;
3061 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003062 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003063 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003064 // Handle the uncommon case of "123[Ptr]".
3065 BaseExpr = RHSExp;
3066 IndexExpr = LHSExp;
3067 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003068 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003069 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003070 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003071 VK = LHSExp->getValueKind();
3072 if (VK != VK_RValue)
3073 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003074
Chris Lattner36d572b2007-07-16 00:14:47 +00003075 // FIXME: need to deal with const...
3076 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003077 } else if (LHSTy->isArrayType()) {
3078 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003079 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003080 // wasn't promoted because of the C90 rule that doesn't
3081 // allow promoting non-lvalue arrays. Warn, then
3082 // force the promotion here.
3083 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3084 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003085 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003086 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003087 LHSTy = LHSExp->getType();
3088
3089 BaseExpr = LHSExp;
3090 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003091 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003092 } else if (RHSTy->isArrayType()) {
3093 // Same as previous, except for 123[f().a] case
3094 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3095 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003096 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003097 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003098 RHSTy = RHSExp->getType();
3099
3100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003102 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003103 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003104 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3105 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003106 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003107 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003108 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003109 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3110 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003111
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003112 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003113 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3114 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003115 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3116
Douglas Gregorac1fb652009-03-24 19:52:54 +00003117 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003118 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3119 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003120 // incomplete types are not object types.
3121 if (ResultType->isFunctionType()) {
3122 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3123 << ResultType << BaseExpr->getSourceRange();
3124 return ExprError();
3125 }
Mike Stump11289f42009-09-09 15:08:12 +00003126
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003127 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3128 // GNU extension: subscripting on pointer to void
3129 Diag(LLoc, diag::ext_gnu_void_ptr)
3130 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003131
3132 // C forbids expressions of unqualified void type from being l-values.
3133 // See IsCForbiddenLValueType.
3134 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003135 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003136 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003137 PDiag(diag::err_subscript_incomplete_type)
3138 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003139 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003140
Chris Lattner62975a72009-04-24 00:30:45 +00003141 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003142 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003143 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3144 << ResultType << BaseExpr->getSourceRange();
3145 return ExprError();
3146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
John McCall4bc41ae2010-11-18 19:01:18 +00003148 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3149 !IsCForbiddenLValueType(Context, ResultType));
3150
Mike Stump4e1f26a2009-02-19 03:04:26 +00003151 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003152 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003153}
3154
John McCall4bc41ae2010-11-18 19:01:18 +00003155/// Check an ext-vector component access expression.
3156///
3157/// VK should be set in advance to the value kind of the base
3158/// expression.
3159static QualType
3160CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3161 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003162 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003163 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3164 // see FIXME there.
3165 //
3166 // FIXME: This logic can be greatly simplified by splitting it along
3167 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003168 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003169
Steve Narofff8fd09e2007-07-27 22:15:19 +00003170 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003171 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003172
Mike Stump4e1f26a2009-02-19 03:04:26 +00003173 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003174 // special names that indicate a subset of exactly half the elements are
3175 // to be selected.
3176 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003177
Nate Begemanbb70bf62009-01-18 01:47:54 +00003178 // This flag determines whether or not CompName has an 's' char prefix,
3179 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003180 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003181
John McCall4bc41ae2010-11-18 19:01:18 +00003182 bool HasRepeated = false;
3183 bool HasIndex[16] = {};
3184
3185 int Idx;
3186
Nate Begemanf322eab2008-05-09 06:41:27 +00003187 // Check that we've found one of the special components, or that the component
3188 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003189 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003190 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3191 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003192 } else if (!HexSwizzle &&
3193 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3194 do {
3195 if (HasIndex[Idx]) HasRepeated = true;
3196 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003197 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003198 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3199 } else {
3200 if (HexSwizzle) compStr++;
3201 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3202 if (HasIndex[Idx]) HasRepeated = true;
3203 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003204 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003205 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003206 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003207
Mike Stump4e1f26a2009-02-19 03:04:26 +00003208 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003209 // We didn't get to the end of the string. This means the component names
3210 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003211 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003212 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003213 return QualType();
3214 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003215
Nate Begemanbb70bf62009-01-18 01:47:54 +00003216 // Ensure no component accessor exceeds the width of the vector type it
3217 // operates on.
3218 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003219 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003220
3221 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003222 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003223
3224 while (*compStr) {
3225 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003226 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003227 << baseType << SourceRange(CompLoc);
3228 return QualType();
3229 }
3230 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003231 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003232
Steve Narofff8fd09e2007-07-27 22:15:19 +00003233 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003234 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003235 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003236 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003237 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003238 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003239 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003240 if (HexSwizzle)
3241 CompSize--;
3242
Steve Narofff8fd09e2007-07-27 22:15:19 +00003243 if (CompSize == 1)
3244 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003245
John McCall4bc41ae2010-11-18 19:01:18 +00003246 if (HasRepeated) VK = VK_RValue;
3247
3248 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003249 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003250 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003251 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3252 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3253 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003254 }
3255 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003256}
3257
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003258static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003259 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003260 const Selector &Sel,
3261 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003262 if (Member)
3263 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3264 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003265 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003266 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003267
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003268 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3269 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003270 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3271 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003272 return D;
3273 }
3274 return 0;
3275}
3276
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003277static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3278 IdentifierInfo *Member,
3279 const Selector &Sel,
3280 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003281 // Check protocols on qualified interfaces.
3282 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003283 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003284 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003285 if (Member)
3286 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3287 GDecl = PD;
3288 break;
3289 }
3290 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003291 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003292 GDecl = OMD;
3293 break;
3294 }
3295 }
3296 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003297 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003298 E = QIdTy->qual_end(); I != E; ++I) {
3299 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003300 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3301 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003302 if (GDecl)
3303 return GDecl;
3304 }
3305 }
3306 return GDecl;
3307}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003308
John McCalldadc5752010-08-24 06:29:42 +00003309ExprResult
John McCallb268a282010-08-23 23:25:46 +00003310Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003311 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003312 const CXXScopeSpec &SS,
3313 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003314 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003315 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003316 // Even in dependent contexts, try to diagnose base expressions with
3317 // obviously wrong types, e.g.:
3318 //
3319 // T* t;
3320 // t.f;
3321 //
3322 // In Obj-C++, however, the above expression is valid, since it could be
3323 // accessing the 'f' property if T is an Obj-C interface. The extra check
3324 // allows this, while still reporting an error if T is a struct pointer.
3325 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003326 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003327 if (PT && (!getLangOptions().ObjC1 ||
3328 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003329 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003330 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003331 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003332 return ExprError();
3333 }
3334 }
3335
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003336 assert(BaseType->isDependentType() ||
3337 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003338 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003339
3340 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3341 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003342 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003343 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003344 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003345 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003346 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003347}
3348
3349/// We know that the given qualified member reference points only to
3350/// declarations which do not belong to the static type of the base
3351/// expression. Diagnose the problem.
3352static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3353 Expr *BaseExpr,
3354 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003355 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003356 NamedDecl *rep,
3357 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003358 // If this is an implicit member access, use a different set of
3359 // diagnostics.
3360 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003361 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003362
John McCallf3a88602011-02-03 08:15:49 +00003363 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3364 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003365}
3366
3367// Check whether the declarations we found through a nested-name
3368// specifier in a member expression are actually members of the base
3369// type. The restriction here is:
3370//
3371// C++ [expr.ref]p2:
3372// ... In these cases, the id-expression shall name a
3373// member of the class or of one of its base classes.
3374//
3375// So it's perfectly legitimate for the nested-name specifier to name
3376// an unrelated class, and for us to find an overload set including
3377// decls from classes which are not superclasses, as long as the decl
3378// we actually pick through overload resolution is from a superclass.
3379bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3380 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003381 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003382 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003383 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3384 if (!BaseRT) {
3385 // We can't check this yet because the base type is still
3386 // dependent.
3387 assert(BaseType->isDependentType());
3388 return false;
3389 }
3390 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003391
3392 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003393 // If this is an implicit member reference and we find a
3394 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003395 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003396 return false;
John McCall10eae182009-11-30 22:42:35 +00003397
John McCall2d74de92009-12-01 22:10:20 +00003398 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003399 DeclContext *DC = (*I)->getDeclContext();
3400 while (DC->isTransparentContext())
3401 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003402
Douglas Gregora9c3e822010-07-28 22:27:52 +00003403 if (!DC->isRecord())
3404 continue;
3405
John McCall2d74de92009-12-01 22:10:20 +00003406 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003407 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003408
3409 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3410 return false;
3411 }
3412
John McCallf3a88602011-02-03 08:15:49 +00003413 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3414 R.getRepresentativeDecl(),
3415 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003416 return true;
3417}
3418
3419static bool
3420LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3421 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003422 SourceLocation OpLoc, CXXScopeSpec &SS,
3423 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003424 RecordDecl *RDecl = RTy->getDecl();
3425 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003426 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003427 << BaseRange))
3428 return true;
3429
John McCalle9cccd82010-06-16 08:42:20 +00003430 if (HasTemplateArgs) {
3431 // LookupTemplateName doesn't expect these both to exist simultaneously.
3432 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3433
3434 bool MOUS;
3435 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3436 return false;
3437 }
3438
John McCall2d74de92009-12-01 22:10:20 +00003439 DeclContext *DC = RDecl;
3440 if (SS.isSet()) {
3441 // If the member name was a qualified-id, look into the
3442 // nested-name-specifier.
3443 DC = SemaRef.computeDeclContext(SS, false);
3444
John McCall0b66eb32010-05-01 00:40:08 +00003445 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003446 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3447 << SS.getRange() << DC;
3448 return true;
3449 }
3450
John McCall2d74de92009-12-01 22:10:20 +00003451 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003452
John McCall2d74de92009-12-01 22:10:20 +00003453 if (!isa<TypeDecl>(DC)) {
3454 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3455 << DC << SS.getRange();
3456 return true;
John McCall10eae182009-11-30 22:42:35 +00003457 }
3458 }
3459
John McCall2d74de92009-12-01 22:10:20 +00003460 // The record definition is complete, now look up the member.
3461 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003462
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003463 if (!R.empty())
3464 return false;
3465
3466 // We didn't find anything with the given name, so try to correct
3467 // for typos.
3468 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003469 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003470 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003471 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3472 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3473 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003474 << FixItHint::CreateReplacement(R.getNameLoc(),
3475 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003476 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3477 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3478 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003479 return false;
3480 } else {
3481 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003482 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003483 }
3484
John McCall10eae182009-11-30 22:42:35 +00003485 return false;
3486}
3487
John McCalldadc5752010-08-24 06:29:42 +00003488ExprResult
John McCallb268a282010-08-23 23:25:46 +00003489Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003490 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003491 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003492 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003493 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003494 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003495 if (BaseType->isDependentType() ||
3496 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003497 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003498 IsArrow, OpLoc,
3499 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003500 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003501
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003502 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003503
John McCall2d74de92009-12-01 22:10:20 +00003504 // Implicit member accesses.
3505 if (!Base) {
3506 QualType RecordTy = BaseType;
3507 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3508 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3509 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003510 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003511 return ExprError();
3512
3513 // Explicit member accesses.
3514 } else {
John McCalldadc5752010-08-24 06:29:42 +00003515 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003516 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003517 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003518
3519 if (Result.isInvalid()) {
3520 Owned(Base);
3521 return ExprError();
3522 }
3523
3524 if (Result.get())
3525 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003526
3527 // LookupMemberExpr can modify Base, and thus change BaseType
3528 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003529 }
3530
John McCallb268a282010-08-23 23:25:46 +00003531 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003532 OpLoc, IsArrow, SS, FirstQualifierInScope,
3533 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003534}
3535
John McCalldadc5752010-08-24 06:29:42 +00003536ExprResult
John McCallb268a282010-08-23 23:25:46 +00003537Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003538 SourceLocation OpLoc, bool IsArrow,
3539 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003540 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003541 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003542 const TemplateArgumentListInfo *TemplateArgs,
3543 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003544 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003545 if (IsArrow) {
3546 assert(BaseType->isPointerType());
3547 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3548 }
John McCalla8ae2222010-04-06 21:38:20 +00003549 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003550
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003551 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3552 DeclarationName MemberName = MemberNameInfo.getName();
3553 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003554
3555 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003556 return ExprError();
3557
John McCall10eae182009-11-30 22:42:35 +00003558 if (R.empty()) {
3559 // Rederive where we looked up.
3560 DeclContext *DC = (SS.isSet()
3561 ? computeDeclContext(SS, false)
3562 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003563
John McCall10eae182009-11-30 22:42:35 +00003564 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003565 << MemberName << DC
3566 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003567 return ExprError();
3568 }
3569
John McCall38836f02010-01-15 08:34:02 +00003570 // Diagnose lookups that find only declarations from a non-base
3571 // type. This is possible for either qualified lookups (which may
3572 // have been qualified with an unrelated type) or implicit member
3573 // expressions (which were found with unqualified lookup and thus
3574 // may have come from an enclosing scope). Note that it's okay for
3575 // lookup to find declarations from a non-base type as long as those
3576 // aren't the ones picked by overload resolution.
3577 if ((SS.isSet() || !BaseExpr ||
3578 (isa<CXXThisExpr>(BaseExpr) &&
3579 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003580 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003581 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003582 return ExprError();
3583
3584 // Construct an unresolved result if we in fact got an unresolved
3585 // result.
3586 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003587 // Suppress any lookup-related diagnostics; we'll do these when we
3588 // pick a member.
3589 R.suppressDiagnostics();
3590
John McCall10eae182009-11-30 22:42:35 +00003591 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003592 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003593 BaseExpr, BaseExprType,
3594 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003595 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003596 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003597 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003598
3599 return Owned(MemExpr);
3600 }
3601
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003602 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003603 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003604 NamedDecl *MemberDecl = R.getFoundDecl();
3605
3606 // FIXME: diagnose the presence of template arguments now.
3607
3608 // If the decl being referenced had an error, return an error for this
3609 // sub-expr without emitting another error, in order to avoid cascading
3610 // error cases.
3611 if (MemberDecl->isInvalidDecl())
3612 return ExprError();
3613
John McCall2d74de92009-12-01 22:10:20 +00003614 // Handle the implicit-member-access case.
3615 if (!BaseExpr) {
3616 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003617 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003618 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003619
Douglas Gregorb15af892010-01-07 23:12:05 +00003620 SourceLocation Loc = R.getNameLoc();
3621 if (SS.getRange().isValid())
3622 Loc = SS.getRange().getBegin();
3623 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003624 }
3625
John McCall10eae182009-11-30 22:42:35 +00003626 bool ShouldCheckUse = true;
3627 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3628 // Don't diagnose the use of a virtual member function unless it's
3629 // explicitly qualified.
3630 if (MD->isVirtual() && !SS.isSet())
3631 ShouldCheckUse = false;
3632 }
3633
3634 // Check the use of this member.
3635 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3636 Owned(BaseExpr);
3637 return ExprError();
3638 }
3639
John McCall34376a62010-12-04 03:47:34 +00003640 // Perform a property load on the base regardless of whether we
3641 // actually need it for the declaration.
3642 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3643 ConvertPropertyForRValue(BaseExpr);
3644
John McCallfeb624a2010-11-23 20:48:44 +00003645 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3646 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3647 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003648
Francois Pichet783dd6e2010-11-21 06:08:52 +00003649 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3650 // We may have found a field within an anonymous union or struct
3651 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003652 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003653 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003654
John McCall10eae182009-11-30 22:42:35 +00003655 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3656 MarkDeclarationReferenced(MemberLoc, Var);
3657 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003658 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003659 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003660 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003661 }
3662
John McCall7decc9e2010-11-18 06:31:45 +00003663 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003664 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3665 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003666 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003667 MemberFn->getType(),
3668 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3669 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003670 }
John McCall7decc9e2010-11-18 06:31:45 +00003671 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003672
3673 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3674 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3675 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003676 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003677 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003678 }
3679
3680 Owned(BaseExpr);
3681
Douglas Gregor861eb802010-04-25 20:55:08 +00003682 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003683 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003684 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003685 << MemberName << BaseType << int(IsArrow);
3686 else
3687 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3688 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003689
Douglas Gregor861eb802010-04-25 20:55:08 +00003690 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3691 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003692 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003693 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003694}
3695
John McCall68fc88ec2010-12-15 16:46:44 +00003696/// Given that normal member access failed on the given expression,
3697/// and given that the expression's type involves builtin-id or
3698/// builtin-Class, decide whether substituting in the redefinition
3699/// types would be profitable. The redefinition type is whatever
3700/// this translation unit tried to typedef to id/Class; we store
3701/// it to the side and then re-use it in places like this.
3702static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3703 const ObjCObjectPointerType *opty
3704 = base->getType()->getAs<ObjCObjectPointerType>();
3705 if (!opty) return false;
3706
3707 const ObjCObjectType *ty = opty->getObjectType();
3708
3709 QualType redef;
3710 if (ty->isObjCId()) {
3711 redef = S.Context.ObjCIdRedefinitionType;
3712 } else if (ty->isObjCClass()) {
3713 redef = S.Context.ObjCClassRedefinitionType;
3714 } else {
3715 return false;
3716 }
3717
3718 // Do the substitution as long as the redefinition type isn't just a
3719 // possibly-qualified pointer to builtin-id or builtin-Class again.
3720 opty = redef->getAs<ObjCObjectPointerType>();
3721 if (opty && !opty->getObjectType()->getInterface() != 0)
3722 return false;
3723
3724 S.ImpCastExprToType(base, redef, CK_BitCast);
3725 return true;
3726}
3727
John McCall10eae182009-11-30 22:42:35 +00003728/// Look up the given member of the given non-type-dependent
3729/// expression. This can return in one of two ways:
3730/// * If it returns a sentinel null-but-valid result, the caller will
3731/// assume that lookup was performed and the results written into
3732/// the provided structure. It will take over from there.
3733/// * Otherwise, the returned expression will be produced in place of
3734/// an ordinary member expression.
3735///
3736/// The ObjCImpDecl bit is a gross hack that will need to be properly
3737/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003738ExprResult
John McCall10eae182009-11-30 22:42:35 +00003739Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003740 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003741 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003742 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003743 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003744
Steve Naroffeaaae462007-12-16 21:42:28 +00003745 // Perform default conversions.
3746 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003747 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003748
Steve Naroff185616f2007-07-26 03:11:44 +00003749 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003750 assert(!BaseType->isDependentType());
3751
3752 DeclarationName MemberName = R.getLookupName();
3753 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003754
John McCall68fc88ec2010-12-15 16:46:44 +00003755 // For later type-checking purposes, turn arrow accesses into dot
3756 // accesses. The only access type we support that doesn't follow
3757 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3758 // and those never use arrows, so this is unaffected.
3759 if (IsArrow) {
3760 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3761 BaseType = Ptr->getPointeeType();
3762 else if (const ObjCObjectPointerType *Ptr
3763 = BaseType->getAs<ObjCObjectPointerType>())
3764 BaseType = Ptr->getPointeeType();
3765 else if (BaseType->isRecordType()) {
3766 // Recover from arrow accesses to records, e.g.:
3767 // struct MyRecord foo;
3768 // foo->bar
3769 // This is actually well-formed in C++ if MyRecord has an
3770 // overloaded operator->, but that should have been dealt with
3771 // by now.
3772 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3773 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3774 << FixItHint::CreateReplacement(OpLoc, ".");
3775 IsArrow = false;
3776 } else {
3777 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3778 << BaseType << BaseExpr->getSourceRange();
3779 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003780 }
3781 }
3782
John McCall68fc88ec2010-12-15 16:46:44 +00003783 // Handle field access to simple records.
3784 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3785 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3786 RTy, OpLoc, SS, HasTemplateArgs))
3787 return ExprError();
3788
3789 // Returning valid-but-null is how we indicate to the caller that
3790 // the lookup result was filled in.
3791 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003792 }
John McCall10eae182009-11-30 22:42:35 +00003793
John McCall68fc88ec2010-12-15 16:46:44 +00003794 // Handle ivar access to Objective-C objects.
3795 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003796 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003797
3798 // There are three cases for the base type:
3799 // - builtin id (qualified or unqualified)
3800 // - builtin Class (qualified or unqualified)
3801 // - an interface
3802 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3803 if (!IDecl) {
3804 // There's an implicit 'isa' ivar on all objects.
3805 // But we only actually find it this way on objects of type 'id',
3806 // apparently.
3807 if (OTy->isObjCId() && Member->isStr("isa"))
3808 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3809 Context.getObjCClassType()));
3810
3811 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3812 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3813 ObjCImpDecl, HasTemplateArgs);
3814 goto fail;
3815 }
3816
3817 ObjCInterfaceDecl *ClassDeclared;
3818 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3819
3820 if (!IV) {
3821 // Attempt to correct for typos in ivar names.
3822 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3823 LookupMemberName);
3824 if (CorrectTypo(Res, 0, 0, IDecl, false,
3825 IsArrow ? CTC_ObjCIvarLookup
3826 : CTC_ObjCPropertyLookup) &&
3827 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3828 Diag(R.getNameLoc(),
3829 diag::err_typecheck_member_reference_ivar_suggest)
3830 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3831 << FixItHint::CreateReplacement(R.getNameLoc(),
3832 IV->getNameAsString());
3833 Diag(IV->getLocation(), diag::note_previous_decl)
3834 << IV->getDeclName();
3835 } else {
3836 Res.clear();
3837 Res.setLookupName(Member);
3838
3839 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3840 << IDecl->getDeclName() << MemberName
3841 << BaseExpr->getSourceRange();
3842 return ExprError();
3843 }
3844 }
3845
3846 // If the decl being referenced had an error, return an error for this
3847 // sub-expr without emitting another error, in order to avoid cascading
3848 // error cases.
3849 if (IV->isInvalidDecl())
3850 return ExprError();
3851
3852 // Check whether we can reference this field.
3853 if (DiagnoseUseOfDecl(IV, MemberLoc))
3854 return ExprError();
3855 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3856 IV->getAccessControl() != ObjCIvarDecl::Package) {
3857 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3858 if (ObjCMethodDecl *MD = getCurMethodDecl())
3859 ClassOfMethodDecl = MD->getClassInterface();
3860 else if (ObjCImpDecl && getCurFunctionDecl()) {
3861 // Case of a c-function declared inside an objc implementation.
3862 // FIXME: For a c-style function nested inside an objc implementation
3863 // class, there is no implementation context available, so we pass
3864 // down the context as argument to this routine. Ideally, this context
3865 // need be passed down in the AST node and somehow calculated from the
3866 // AST for a function decl.
3867 if (ObjCImplementationDecl *IMPD =
3868 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3869 ClassOfMethodDecl = IMPD->getClassInterface();
3870 else if (ObjCCategoryImplDecl* CatImplClass =
3871 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3872 ClassOfMethodDecl = CatImplClass->getClassInterface();
3873 }
3874
3875 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3876 if (ClassDeclared != IDecl ||
3877 ClassOfMethodDecl != ClassDeclared)
3878 Diag(MemberLoc, diag::error_private_ivar_access)
3879 << IV->getDeclName();
3880 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3881 // @protected
3882 Diag(MemberLoc, diag::error_protected_ivar_access)
3883 << IV->getDeclName();
3884 }
3885
3886 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3887 MemberLoc, BaseExpr,
3888 IsArrow));
3889 }
3890
3891 // Objective-C property access.
3892 const ObjCObjectPointerType *OPT;
3893 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3894 // This actually uses the base as an r-value.
3895 DefaultLvalueConversion(BaseExpr);
3896 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3897
3898 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3899
3900 const ObjCObjectType *OT = OPT->getObjectType();
3901
3902 // id, with and without qualifiers.
3903 if (OT->isObjCId()) {
3904 // Check protocols on qualified interfaces.
3905 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3906 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3907 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3908 // Check the use of this declaration
3909 if (DiagnoseUseOfDecl(PD, MemberLoc))
3910 return ExprError();
3911
3912 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3913 VK_LValue,
3914 OK_ObjCProperty,
3915 MemberLoc,
3916 BaseExpr));
3917 }
3918
3919 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3920 // Check the use of this method.
3921 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3922 return ExprError();
3923 Selector SetterSel =
3924 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3925 PP.getSelectorTable(), Member);
3926 ObjCMethodDecl *SMD = 0;
3927 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3928 SetterSel, Context))
3929 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3930 QualType PType = OMD->getSendResultType();
3931
3932 ExprValueKind VK = VK_LValue;
3933 if (!getLangOptions().CPlusPlus &&
3934 IsCForbiddenLValueType(Context, PType))
3935 VK = VK_RValue;
3936 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3937
3938 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3939 VK, OK,
3940 MemberLoc, BaseExpr));
3941 }
3942 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003943 // Use of id.member can only be for a property reference. Do not
3944 // use the 'id' redefinition in this case.
3945 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003946 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3947 ObjCImpDecl, HasTemplateArgs);
3948
3949 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3950 << MemberName << BaseType);
3951 }
3952
3953 // 'Class', unqualified only.
3954 if (OT->isObjCClass()) {
3955 // Only works in a method declaration (??!).
3956 ObjCMethodDecl *MD = getCurMethodDecl();
3957 if (!MD) {
3958 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3959 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3960 ObjCImpDecl, HasTemplateArgs);
3961
3962 goto fail;
3963 }
3964
3965 // Also must look for a getter name which uses property syntax.
3966 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003967 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3968 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003969 if ((Getter = IFace->lookupClassMethod(Sel))) {
3970 // Check the use of this method.
3971 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3972 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003973 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003974 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003975 // If we found a getter then this may be a valid dot-reference, we
3976 // will look for the matching setter, in case it is needed.
3977 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003978 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3979 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003980 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3981 if (!Setter) {
3982 // If this reference is in an @implementation, also check for 'private'
3983 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003984 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003985 }
3986 // Look through local category implementations associated with the class.
3987 if (!Setter)
3988 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003989
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003990 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3991 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003992
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003993 if (Getter || Setter) {
3994 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003995
John McCall4bc41ae2010-11-18 19:01:18 +00003996 ExprValueKind VK = VK_LValue;
3997 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003998 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003999 if (!getLangOptions().CPlusPlus &&
4000 IsCForbiddenLValueType(Context, PType))
4001 VK = VK_RValue;
4002 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004003 // Get the expression type from Setter's incoming parameter.
4004 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004005 }
4006 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4007
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004008 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004009 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4010 PType, VK, OK,
4011 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004012 }
John McCall68fc88ec2010-12-15 16:46:44 +00004013
4014 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4015 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4016 ObjCImpDecl, HasTemplateArgs);
4017
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004018 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004019 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004020 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004021
John McCall68fc88ec2010-12-15 16:46:44 +00004022 // Normal property access.
4023 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
4024 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004025 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004026
Chris Lattnerb63a7452008-07-21 04:28:12 +00004027 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004028 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004029 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004030 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00004031 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004032 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4033 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004034 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004035 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004036
4037 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
4038 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004039 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004040
John McCall68fc88ec2010-12-15 16:46:44 +00004041 // Adjust builtin-sel to the appropriate redefinition type if that's
4042 // not just a pointer to builtin-sel again.
4043 if (IsArrow &&
4044 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4045 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4046 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
4047 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4048 ObjCImpDecl, HasTemplateArgs);
4049 }
4050
4051 // Failure cases.
4052 fail:
4053
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004054 // Recover from dot accesses to pointers, e.g.:
4055 // type *foo;
4056 // foo.bar
4057 // This is actually well-formed in two cases:
4058 // - 'type' is an Objective C type
4059 // - 'bar' is a pseudo-destructor name which happens to refer to
4060 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004061 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004062 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4063 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004064 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004065 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4066 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004067
4068 // Recurse as an -> access.
4069 IsArrow = true;
4070 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4071 ObjCImpDecl, HasTemplateArgs);
4072 }
John McCall68fc88ec2010-12-15 16:46:44 +00004073 }
4074
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004075 // If the user is trying to apply -> or . to a function name, it's probably
4076 // because they forgot parentheses to call that function.
4077 bool TryCall = false;
4078 bool Overloaded = false;
4079 UnresolvedSet<8> AllOverloads;
4080 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4081 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4082 TryCall = true;
4083 Overloaded = true;
4084 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4085 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4086 AllOverloads.addDecl(Fun);
4087 TryCall = true;
4088 }
4089 }
John McCall68fc88ec2010-12-15 16:46:44 +00004090
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004091 if (TryCall) {
4092 // Plunder the overload set for something that would make the member
4093 // expression valid.
4094 UnresolvedSet<4> ViableOverloads;
4095 bool HasViableZeroArgOverload = false;
4096 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4097 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004098 // Our overload set may include TemplateDecls, which we'll ignore for the
4099 // purposes of determining whether we can issue a '()' fixit.
4100 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4101 QualType ResultTy = OverloadDecl->getResultType();
4102 if ((!IsArrow && ResultTy->isRecordType()) ||
4103 (IsArrow && ResultTy->isPointerType() &&
4104 ResultTy->getPointeeType()->isRecordType())) {
4105 ViableOverloads.addDecl(*it);
4106 if (OverloadDecl->getMinRequiredArguments() == 0) {
4107 HasViableZeroArgOverload = true;
4108 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004109 }
John McCall68fc88ec2010-12-15 16:46:44 +00004110 }
4111 }
4112
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004113 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4114 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004115 << (AllOverloads.size() > 1) << 0
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004116 << BaseExpr->getSourceRange();
4117 int ViableOverloadCount = ViableOverloads.size();
4118 int I;
4119 for (I = 0; I < ViableOverloadCount; ++I) {
4120 // FIXME: Magic number for max shown overloads stolen from
4121 // OverloadCandidateSet::NoteCandidates.
4122 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4123 break;
4124 }
4125 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4126 diag::note_member_ref_possible_intended_overload);
4127 }
4128 if (I != ViableOverloadCount) {
4129 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4130 << int(ViableOverloadCount - I);
4131 }
4132 return ExprError();
4133 }
4134 } else {
4135 // We don't have an expression that's convenient to get a Decl from, but we
4136 // can at least check if the type is "function of 0 arguments which returns
4137 // an acceptable type".
4138 const FunctionType *Fun = NULL;
4139 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4140 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4141 TryCall = true;
4142 }
4143 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4144 TryCall = true;
4145 }
John McCall68fc88ec2010-12-15 16:46:44 +00004146
4147 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004148 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4149 if (FPT->getNumArgs() == 0) {
4150 QualType ResultTy = Fun->getResultType();
4151 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4152 (IsArrow && ResultTy->isPointerType() &&
4153 ResultTy->getPointeeType()->isRecordType());
4154 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004155 }
John McCall68fc88ec2010-12-15 16:46:44 +00004156 }
4157 }
4158
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004159 if (TryCall) {
4160 // At this point, we know BaseExpr looks like it's potentially callable with
4161 // 0 arguments, and that it returns something of a reasonable type, so we
4162 // can emit a fixit and carry on pretending that BaseExpr was actually a
4163 // CallExpr.
4164 SourceLocation ParenInsertionLoc =
4165 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4166 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4167 << int(Overloaded) << 1
4168 << BaseExpr->getSourceRange()
4169 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4170 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4171 MultiExprArg(*this, 0, 0),
4172 ParenInsertionLoc);
4173 if (NewBase.isInvalid())
4174 return ExprError();
4175 BaseExpr = NewBase.takeAs<Expr>();
4176 DefaultFunctionArrayConversion(BaseExpr);
4177 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4178 ObjCImpDecl, HasTemplateArgs);
4179 }
4180
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004181 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4182 << BaseType << BaseExpr->getSourceRange();
4183
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004184 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004185}
4186
John McCall10eae182009-11-30 22:42:35 +00004187/// The main callback when the parser finds something like
4188/// expression . [nested-name-specifier] identifier
4189/// expression -> [nested-name-specifier] identifier
4190/// where 'identifier' encompasses a fairly broad spectrum of
4191/// possibilities, including destructor and operator references.
4192///
4193/// \param OpKind either tok::arrow or tok::period
4194/// \param HasTrailingLParen whether the next token is '(', which
4195/// is used to diagnose mis-uses of special members that can
4196/// only be called
4197/// \param ObjCImpDecl the current ObjC @implementation decl;
4198/// this is an ugly hack around the fact that ObjC @implementations
4199/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004200ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004201 SourceLocation OpLoc,
4202 tok::TokenKind OpKind,
4203 CXXScopeSpec &SS,
4204 UnqualifiedId &Id,
4205 Decl *ObjCImpDecl,
4206 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004207 if (SS.isSet() && SS.isInvalid())
4208 return ExprError();
4209
Francois Pichet64225792011-01-18 05:04:39 +00004210 // Warn about the explicit constructor calls Microsoft extension.
4211 if (getLangOptions().Microsoft &&
4212 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4213 Diag(Id.getSourceRange().getBegin(),
4214 diag::ext_ms_explicit_constructor_call);
4215
John McCall10eae182009-11-30 22:42:35 +00004216 TemplateArgumentListInfo TemplateArgsBuffer;
4217
4218 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004219 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004220 const TemplateArgumentListInfo *TemplateArgs;
4221 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004222 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004223
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004224 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004225 bool IsArrow = (OpKind == tok::arrow);
4226
4227 NamedDecl *FirstQualifierInScope
4228 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4229 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4230
4231 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004232 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004233 if (Result.isInvalid()) return ExprError();
4234 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004235
Douglas Gregor41f90302010-04-12 20:54:26 +00004236 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4237 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004238 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004239 IsArrow, OpLoc,
4240 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004241 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004242 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004243 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004244 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4245 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004246
John McCalle9cccd82010-06-16 08:42:20 +00004247 if (Result.isInvalid()) {
4248 Owned(Base);
4249 return ExprError();
4250 }
John McCall10eae182009-11-30 22:42:35 +00004251
John McCalle9cccd82010-06-16 08:42:20 +00004252 if (Result.get()) {
4253 // The only way a reference to a destructor can be used is to
4254 // immediately call it, which falls into this case. If the
4255 // next token is not a '(', produce a diagnostic and build the
4256 // call now.
4257 if (!HasTrailingLParen &&
4258 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004259 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004260
John McCalle9cccd82010-06-16 08:42:20 +00004261 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004262 }
4263
John McCallb268a282010-08-23 23:25:46 +00004264 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004265 OpLoc, IsArrow, SS, FirstQualifierInScope,
4266 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004267 }
4268
4269 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004270}
4271
John McCalldadc5752010-08-24 06:29:42 +00004272ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004273 FunctionDecl *FD,
4274 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004275 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004276 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004277 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004278 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004279 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004280 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004281 return ExprError();
4282 }
4283
4284 if (Param->hasUninstantiatedDefaultArg()) {
4285 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004286
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004287 // Instantiate the expression.
4288 MultiLevelTemplateArgumentList ArgList
4289 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004290
Nico Weber44887f62010-11-29 18:19:25 +00004291 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004292 = ArgList.getInnermost();
4293 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4294 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004295
Nico Weber44887f62010-11-29 18:19:25 +00004296 ExprResult Result;
4297 {
4298 // C++ [dcl.fct.default]p5:
4299 // The names in the [default argument] expression are bound, and
4300 // the semantic constraints are checked, at the point where the
4301 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004302 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004303 Result = SubstExpr(UninstExpr, ArgList);
4304 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004305 if (Result.isInvalid())
4306 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004307
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004308 // Check the expression as an initializer for the parameter.
4309 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004310 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004311 InitializationKind Kind
4312 = InitializationKind::CreateCopy(Param->getLocation(),
4313 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4314 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004315
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004316 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4317 Result = InitSeq.Perform(*this, Entity, Kind,
4318 MultiExprArg(*this, &ResultE, 1));
4319 if (Result.isInvalid())
4320 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004321
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004322 // Build the default argument expression.
4323 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4324 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004325 }
4326
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004327 // If the default expression creates temporaries, we need to
4328 // push them to the current stack of expression temporaries so they'll
4329 // be properly destroyed.
4330 // FIXME: We should really be rebuilding the default argument with new
4331 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004332 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4333 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4334 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4335 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4336 ExprTemporaries.push_back(Temporary);
4337 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004338
4339 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004340 // Just mark all of the declarations in this potentially-evaluated expression
4341 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004342 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004343 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004344}
4345
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004346/// ConvertArgumentsForCall - Converts the arguments specified in
4347/// Args/NumArgs to the parameter types of the function FDecl with
4348/// function prototype Proto. Call is the call expression itself, and
4349/// Fn is the function expression. For a C++ member function, this
4350/// routine does not attempt to convert the object argument. Returns
4351/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004352bool
4353Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004354 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004355 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004356 Expr **Args, unsigned NumArgs,
4357 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004358 // Bail out early if calling a builtin with custom typechecking.
4359 // We don't need to do this in the
4360 if (FDecl)
4361 if (unsigned ID = FDecl->getBuiltinID())
4362 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4363 return false;
4364
Mike Stump4e1f26a2009-02-19 03:04:26 +00004365 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004366 // assignment, to the types of the corresponding parameter, ...
4367 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004368 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004369
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004370 // If too few arguments are available (and we don't have default
4371 // arguments for the remaining parameters), don't make the call.
4372 if (NumArgs < NumArgsInProto) {
4373 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4374 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004375 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004376 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004377 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004378 }
4379
4380 // If too many are passed and not variadic, error on the extras and drop
4381 // them.
4382 if (NumArgs > NumArgsInProto) {
4383 if (!Proto->isVariadic()) {
4384 Diag(Args[NumArgsInProto]->getLocStart(),
4385 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004386 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004387 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004388 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4389 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004390
4391 // Emit the location of the prototype.
4392 if (FDecl && !FDecl->getBuiltinID())
4393 Diag(FDecl->getLocStart(),
4394 diag::note_typecheck_call_too_many_args)
4395 << FDecl;
4396
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004397 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004398 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004399 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004400 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004401 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004402 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004403 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004404 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4405 if (Fn->getType()->isBlockPointerType())
4406 CallType = VariadicBlock; // Block
4407 else if (isa<MemberExpr>(Fn))
4408 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004409 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004410 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004411 if (Invalid)
4412 return true;
4413 unsigned TotalNumArgs = AllArgs.size();
4414 for (unsigned i = 0; i < TotalNumArgs; ++i)
4415 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004416
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004417 return false;
4418}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004419
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004420bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4421 FunctionDecl *FDecl,
4422 const FunctionProtoType *Proto,
4423 unsigned FirstProtoArg,
4424 Expr **Args, unsigned NumArgs,
4425 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004426 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004427 unsigned NumArgsInProto = Proto->getNumArgs();
4428 unsigned NumArgsToCheck = NumArgs;
4429 bool Invalid = false;
4430 if (NumArgs != NumArgsInProto)
4431 // Use default arguments for missing arguments
4432 NumArgsToCheck = NumArgsInProto;
4433 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004434 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004435 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004436 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004437
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004438 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004439 if (ArgIx < NumArgs) {
4440 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004441
Eli Friedman3164fb12009-03-22 22:00:50 +00004442 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4443 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004444 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004445 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004446 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004447
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004448 // Pass the argument
4449 ParmVarDecl *Param = 0;
4450 if (FDecl && i < FDecl->getNumParams())
4451 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004452
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004453 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004454 Param? InitializedEntity::InitializeParameter(Context, Param)
4455 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004456 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004457 SourceLocation(),
4458 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004459 if (ArgE.isInvalid())
4460 return true;
4461
4462 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004463 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004464 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004465
John McCalldadc5752010-08-24 06:29:42 +00004466 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004467 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004468 if (ArgExpr.isInvalid())
4469 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004470
Anders Carlsson355933d2009-08-25 03:49:14 +00004471 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004472 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004473 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004474 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004475
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004476 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004477 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004478 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004479 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004480 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004481 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004482 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004483 }
4484 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004485 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004486}
4487
Steve Naroff83895f72007-09-16 03:34:24 +00004488/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004489/// This provides the location of the left/right parens and a list of comma
4490/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004491ExprResult
John McCallb268a282010-08-23 23:25:46 +00004492Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004493 MultiExprArg args, SourceLocation RParenLoc,
4494 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004495 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004496
4497 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004498 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004499 if (Result.isInvalid()) return ExprError();
4500 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004501
John McCallb268a282010-08-23 23:25:46 +00004502 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004503
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004504 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004505 // If this is a pseudo-destructor expression, build the call immediately.
4506 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4507 if (NumArgs > 0) {
4508 // Pseudo-destructor calls should not have any arguments.
4509 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004510 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004511 SourceRange(Args[0]->getLocStart(),
4512 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004513
Douglas Gregorad8a3362009-09-04 17:36:40 +00004514 NumArgs = 0;
4515 }
Mike Stump11289f42009-09-09 15:08:12 +00004516
Douglas Gregorad8a3362009-09-04 17:36:40 +00004517 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004518 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004519 }
Mike Stump11289f42009-09-09 15:08:12 +00004520
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004521 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004522 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004523 // FIXME: Will need to cache the results of name lookup (including ADL) in
4524 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004525 bool Dependent = false;
4526 if (Fn->isTypeDependent())
4527 Dependent = true;
4528 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4529 Dependent = true;
4530
Peter Collingbourne41f85462011-02-09 21:07:24 +00004531 if (Dependent) {
4532 if (ExecConfig) {
4533 return Owned(new (Context) CUDAKernelCallExpr(
4534 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4535 Context.DependentTy, VK_RValue, RParenLoc));
4536 } else {
4537 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4538 Context.DependentTy, VK_RValue,
4539 RParenLoc));
4540 }
4541 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004542
4543 // Determine whether this is a call to an object (C++ [over.call.object]).
4544 if (Fn->getType()->isRecordType())
4545 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004546 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004547
John McCall10eae182009-11-30 22:42:35 +00004548 Expr *NakedFn = Fn->IgnoreParens();
4549
4550 // Determine whether this is a call to an unresolved member function.
4551 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4552 // If lookup was unresolved but not dependent (i.e. didn't find
4553 // an unresolved using declaration), it has to be an overloaded
4554 // function set, which means it must contain either multiple
4555 // declarations (all methods or method templates) or a single
4556 // method template.
4557 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004558 isa<FunctionTemplateDecl>(
4559 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004560 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004561
John McCall2d74de92009-12-01 22:10:20 +00004562 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004563 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004564 }
4565
Douglas Gregore254f902009-02-04 00:32:51 +00004566 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004567 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004568 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004569 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004570 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004571 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004572 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004573
Anders Carlsson61914b52009-10-03 17:40:22 +00004574 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004575 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004576 if (BO->getOpcode() == BO_PtrMemD ||
4577 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004578 if (const FunctionProtoType *FPT
4579 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004580 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004581 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004582
Douglas Gregor125fa402011-02-04 12:57:49 +00004583 // Check that the object type isn't more qualified than the
4584 // member function we're calling.
4585 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4586 Qualifiers ObjectQuals
4587 = BO->getOpcode() == BO_PtrMemD
4588 ? BO->getLHS()->getType().getQualifiers()
4589 : BO->getLHS()->getType()->getAs<PointerType>()
4590 ->getPointeeType().getQualifiers();
4591
4592 Qualifiers Difference = ObjectQuals - FuncQuals;
4593 Difference.removeObjCGCAttr();
4594 Difference.removeAddressSpace();
4595 if (Difference) {
4596 std::string QualsString = Difference.getAsString();
4597 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4598 << BO->getType().getUnqualifiedType()
4599 << QualsString
4600 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4601 }
4602
John McCallb268a282010-08-23 23:25:46 +00004603 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004604 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004605 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004606 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004607
4608 if (CheckCallReturnType(FPT->getResultType(),
4609 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004610 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004611 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004612
John McCallb268a282010-08-23 23:25:46 +00004613 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004614 RParenLoc))
4615 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004616
John McCallb268a282010-08-23 23:25:46 +00004617 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004618 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004619 }
4620 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004621 }
4622
Douglas Gregore254f902009-02-04 00:32:51 +00004623 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004624 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004625 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004626
Eli Friedmane14b1992009-12-26 03:35:45 +00004627 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004628 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4629 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4630 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004631 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004632 }
4633
John McCall57500772009-12-16 12:17:52 +00004634 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004635 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4636 if (UnOp->getOpcode() == UO_AddrOf)
4637 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4638
John McCall57500772009-12-16 12:17:52 +00004639 if (isa<DeclRefExpr>(NakedFn))
4640 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4641
Peter Collingbourne41f85462011-02-09 21:07:24 +00004642 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4643 ExecConfig);
4644}
4645
4646ExprResult
4647Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4648 MultiExprArg execConfig, SourceLocation GGGLoc) {
4649 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4650 if (!ConfigDecl)
4651 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4652 << "cudaConfigureCall");
4653 QualType ConfigQTy = ConfigDecl->getType();
4654
4655 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4656 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4657
4658 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004659}
4660
John McCall31996342011-04-07 08:22:57 +00004661/// Given a function expression of unknown-any type, rebuild it to
4662/// have a type appropriate for being called with the given arguments,
4663/// yielding a value of unknown-any type.
4664static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn,
4665 Expr **args, unsigned numArgs) {
4666 // Build a simple function type exactly matching the arguments.
4667 llvm::SmallVector<QualType, 8> argTypes;
4668 argTypes.reserve(numArgs);
4669 for (unsigned i = 0; i != numArgs; ++i) {
4670 // Require all the sub-expression to not be placeholders.
4671 ExprResult result = S.CheckPlaceholderExpr(args[i], SourceLocation());
4672 if (result.isInvalid()) return ExprError();
4673 args[i] = result.take();
4674
4675 // Do l2r conversions on all the arguments.
4676 S.DefaultLvalueConversion(args[i]);
4677
4678 argTypes.push_back(args[i]->getType());
4679 }
4680
4681 // Resolve the symbol to a function type that returns an unknown-any
4682 // type. In the fully resolved expression, this cast will surround
4683 // the DeclRefExpr.
4684 FunctionProtoType::ExtProtoInfo extInfo;
4685 QualType fnType = S.Context.getFunctionType(S.Context.UnknownAnyTy,
4686 argTypes.data(), numArgs,
4687 extInfo);
4688 fn = ImplicitCastExpr::Create(S.Context, fnType,
4689 CK_ResolveUnknownAnyType,
4690 fn, /*path*/ 0,
4691 (S.getLangOptions().CPlusPlus ? VK_LValue : VK_RValue));
4692
4693 // Decay that to a pointer.
4694 fnType = S.Context.getPointerType(fnType);
4695 fn = ImplicitCastExpr::Create(S.Context, fnType,
4696 CK_FunctionToPointerDecay,
4697 fn, /*path*/ 0, VK_RValue);
4698
4699 return S.Owned(fn);
4700}
4701
John McCall57500772009-12-16 12:17:52 +00004702/// BuildResolvedCallExpr - Build a call to a resolved expression,
4703/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004704/// unary-convert to an expression of function-pointer or
4705/// block-pointer type.
4706///
4707/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004708ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004709Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4710 SourceLocation LParenLoc,
4711 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004712 SourceLocation RParenLoc,
4713 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004714 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4715
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004716 // Promote the function operand.
4717 UsualUnaryConversions(Fn);
4718
Chris Lattner08464942007-12-28 05:29:59 +00004719 // Make the call expr early, before semantic checks. This guarantees cleanup
4720 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004721 CallExpr *TheCall;
4722 if (Config) {
4723 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4724 cast<CallExpr>(Config),
4725 Args, NumArgs,
4726 Context.BoolTy,
4727 VK_RValue,
4728 RParenLoc);
4729 } else {
4730 TheCall = new (Context) CallExpr(Context, Fn,
4731 Args, NumArgs,
4732 Context.BoolTy,
4733 VK_RValue,
4734 RParenLoc);
4735 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004736
John McCallbebede42011-02-26 05:39:39 +00004737 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4738
4739 // Bail out early if calling a builtin with custom typechecking.
4740 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4741 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4742
John McCall31996342011-04-07 08:22:57 +00004743 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004744 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004745 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004746 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4747 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004748 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004749 if (FuncT == 0)
4750 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4751 << Fn->getType() << Fn->getSourceRange());
4752 } else if (const BlockPointerType *BPT =
4753 Fn->getType()->getAs<BlockPointerType>()) {
4754 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4755 } else {
John McCall31996342011-04-07 08:22:57 +00004756 // Handle calls to expressions of unknown-any type.
4757 if (Fn->getType() == Context.UnknownAnyTy) {
4758 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn, Args, NumArgs);
4759 if (rewrite.isInvalid()) return ExprError();
4760 Fn = rewrite.take();
4761 NDecl = FDecl = 0;
4762 goto retry;
4763 }
4764
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004765 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4766 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004767 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004768
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004769 if (getLangOptions().CUDA) {
4770 if (Config) {
4771 // CUDA: Kernel calls must be to global functions
4772 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4773 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4774 << FDecl->getName() << Fn->getSourceRange());
4775
4776 // CUDA: Kernel function must have 'void' return type
4777 if (!FuncT->getResultType()->isVoidType())
4778 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4779 << Fn->getType() << Fn->getSourceRange());
4780 }
4781 }
4782
Eli Friedman3164fb12009-03-22 22:00:50 +00004783 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004784 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004785 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004786 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004787 return ExprError();
4788
Chris Lattner08464942007-12-28 05:29:59 +00004789 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004790 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004791 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004792
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004793 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004794 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004795 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004796 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004797 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004798 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004799
Douglas Gregord8e97de2009-04-02 15:37:10 +00004800 if (FDecl) {
4801 // Check if we have too few/too many template arguments, based
4802 // on our knowledge of the function definition.
4803 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004804 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004805 const FunctionProtoType *Proto
4806 = Def->getType()->getAs<FunctionProtoType>();
4807 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004808 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4809 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004810 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004811
4812 // If the function we're calling isn't a function prototype, but we have
4813 // a function prototype from a prior declaratiom, use that prototype.
4814 if (!FDecl->hasPrototype())
4815 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004816 }
4817
Steve Naroff0b661582007-08-28 23:30:39 +00004818 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004819 for (unsigned i = 0; i != NumArgs; i++) {
4820 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004821
4822 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004823 InitializedEntity Entity
4824 = InitializedEntity::InitializeParameter(Context,
4825 Proto->getArgType(i));
4826 ExprResult ArgE = PerformCopyInitialization(Entity,
4827 SourceLocation(),
4828 Owned(Arg));
4829 if (ArgE.isInvalid())
4830 return true;
4831
4832 Arg = ArgE.takeAs<Expr>();
4833
4834 } else {
4835 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004836 }
4837
Douglas Gregor83025412010-10-26 05:45:40 +00004838 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4839 Arg->getType(),
4840 PDiag(diag::err_call_incomplete_argument)
4841 << Arg->getSourceRange()))
4842 return ExprError();
4843
Chris Lattner08464942007-12-28 05:29:59 +00004844 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004845 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004846 }
Chris Lattner08464942007-12-28 05:29:59 +00004847
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004848 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4849 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004850 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4851 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004852
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004853 // Check for sentinels
4854 if (NDecl)
4855 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004856
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004857 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004858 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004859 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004860 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004861
John McCallbebede42011-02-26 05:39:39 +00004862 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004863 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004864 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004865 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004866 return ExprError();
4867 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004868
John McCallb268a282010-08-23 23:25:46 +00004869 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004870}
4871
John McCalldadc5752010-08-24 06:29:42 +00004872ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004873Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004874 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004875 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004876 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004877 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004878
4879 TypeSourceInfo *TInfo;
4880 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4881 if (!TInfo)
4882 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4883
John McCallb268a282010-08-23 23:25:46 +00004884 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004885}
4886
John McCalldadc5752010-08-24 06:29:42 +00004887ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004888Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004889 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004890 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004891
Eli Friedman37a186d2008-05-20 05:22:08 +00004892 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004893 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4894 PDiag(diag::err_illegal_decl_array_incomplete_type)
4895 << SourceRange(LParenLoc,
4896 literalExpr->getSourceRange().getEnd())))
4897 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004898 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004899 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4900 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004901 } else if (!literalType->isDependentType() &&
4902 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004903 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004904 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004905 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004906 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004907
Douglas Gregor85dabae2009-12-16 01:38:02 +00004908 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004909 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004910 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004911 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004912 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004913 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004914 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004915 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004916 &literalType);
4917 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004918 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004919 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004920
Chris Lattner79413952008-12-04 23:50:19 +00004921 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004922 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004923 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004924 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004925 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004926
John McCall7decc9e2010-11-18 06:31:45 +00004927 // In C, compound literals are l-values for some reason.
4928 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4929
John McCall5d7aa7f2010-01-19 22:33:45 +00004930 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004931 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004932}
4933
John McCalldadc5752010-08-24 06:29:42 +00004934ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004935Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004936 SourceLocation RBraceLoc) {
4937 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004938 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004939
Steve Naroff30d242c2007-09-15 18:49:24 +00004940 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004941 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004942
Ted Kremenekac034612010-04-13 23:39:13 +00004943 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4944 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004945 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004946 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004947}
4948
John McCalld7646252010-11-14 08:17:51 +00004949/// Prepares for a scalar cast, performing all the necessary stages
4950/// except the final cast and returning the kind required.
4951static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4952 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4953 // Also, callers should have filtered out the invalid cases with
4954 // pointers. Everything else should be possible.
4955
Abramo Bagnaraba854972011-01-04 09:50:03 +00004956 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004957 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004958 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004959
John McCall8cb679e2010-11-15 09:13:47 +00004960 switch (SrcTy->getScalarTypeKind()) {
4961 case Type::STK_MemberPointer:
4962 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004963
John McCall8cb679e2010-11-15 09:13:47 +00004964 case Type::STK_Pointer:
4965 switch (DestTy->getScalarTypeKind()) {
4966 case Type::STK_Pointer:
4967 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004968 CK_AnyPointerToObjCPointerCast :
4969 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004970 case Type::STK_Bool:
4971 return CK_PointerToBoolean;
4972 case Type::STK_Integral:
4973 return CK_PointerToIntegral;
4974 case Type::STK_Floating:
4975 case Type::STK_FloatingComplex:
4976 case Type::STK_IntegralComplex:
4977 case Type::STK_MemberPointer:
4978 llvm_unreachable("illegal cast from pointer");
4979 }
4980 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004981
John McCall8cb679e2010-11-15 09:13:47 +00004982 case Type::STK_Bool: // casting from bool is like casting from an integer
4983 case Type::STK_Integral:
4984 switch (DestTy->getScalarTypeKind()) {
4985 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004986 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004987 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004988 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004989 case Type::STK_Bool:
4990 return CK_IntegralToBoolean;
4991 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004992 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004993 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004994 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004995 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004996 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004997 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004998 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004999 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005000 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00005001 CK_IntegralToFloating);
5002 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005003 case Type::STK_MemberPointer:
5004 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005005 }
5006 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005007
John McCall8cb679e2010-11-15 09:13:47 +00005008 case Type::STK_Floating:
5009 switch (DestTy->getScalarTypeKind()) {
5010 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005011 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005012 case Type::STK_Bool:
5013 return CK_FloatingToBoolean;
5014 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005015 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005016 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005017 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00005018 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005019 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005020 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005021 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00005022 CK_FloatingToIntegral);
5023 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005024 case Type::STK_Pointer:
5025 llvm_unreachable("valid float->pointer cast?");
5026 case Type::STK_MemberPointer:
5027 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005028 }
5029 break;
5030
John McCall8cb679e2010-11-15 09:13:47 +00005031 case Type::STK_FloatingComplex:
5032 switch (DestTy->getScalarTypeKind()) {
5033 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005034 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005035 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005036 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005037 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005038 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005039 if (S.Context.hasSameType(ET, DestTy))
5040 return CK_FloatingComplexToReal;
5041 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
5042 return CK_FloatingCast;
5043 }
John McCall8cb679e2010-11-15 09:13:47 +00005044 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005045 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005046 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005047 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00005048 CK_FloatingComplexToReal);
5049 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005050 case Type::STK_Pointer:
5051 llvm_unreachable("valid complex float->pointer cast?");
5052 case Type::STK_MemberPointer:
5053 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005054 }
5055 break;
5056
John McCall8cb679e2010-11-15 09:13:47 +00005057 case Type::STK_IntegralComplex:
5058 switch (DestTy->getScalarTypeKind()) {
5059 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005060 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005061 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005062 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005063 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005064 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005065 if (S.Context.hasSameType(ET, DestTy))
5066 return CK_IntegralComplexToReal;
5067 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
5068 return CK_IntegralCast;
5069 }
John McCall8cb679e2010-11-15 09:13:47 +00005070 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005071 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005072 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00005073 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00005074 CK_IntegralComplexToReal);
5075 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005076 case Type::STK_Pointer:
5077 llvm_unreachable("valid complex int->pointer cast?");
5078 case Type::STK_MemberPointer:
5079 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005080 }
5081 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005082 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005083
John McCalld7646252010-11-14 08:17:51 +00005084 llvm_unreachable("Unhandled scalar cast");
5085 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005086}
5087
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005088/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00005089bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5090 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
5091 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005092 if (castExpr->getType() == Context.UnknownAnyTy)
5093 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5094
Sebastian Redl9f831db2009-07-25 15:41:38 +00005095 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005096 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5097 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005098 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005099 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005100
John McCall7decc9e2010-11-18 06:31:45 +00005101 // We only support r-value casts in C.
5102 VK = VK_RValue;
5103
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005104 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5105 // type needs to be scalar.
5106 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005107 // We don't necessarily do lvalue-to-rvalue conversions on this.
5108 IgnoredValueConversions(castExpr);
5109
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005110 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005111 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00005112 return false;
5113 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005114
John McCall34376a62010-12-04 03:47:34 +00005115 DefaultFunctionArrayLvalueConversion(castExpr);
5116
Eli Friedmane98194d2010-07-17 20:43:49 +00005117 if (RequireCompleteType(TyR.getBegin(), castType,
5118 diag::err_typecheck_cast_to_incomplete))
5119 return true;
5120
Anders Carlssonef918ac2009-10-16 02:35:04 +00005121 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005122 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005123 (castType->isStructureType() || castType->isUnionType())) {
5124 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005125 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005126 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5127 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005128 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005129 return false;
5130 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005131
Anders Carlsson525b76b2009-10-16 02:48:28 +00005132 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005133 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005134 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005135 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005136 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005137 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005138 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005139 castExpr->getType()) &&
5140 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005141 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5142 << castExpr->getSourceRange();
5143 break;
5144 }
5145 }
5146 if (Field == FieldEnd)
5147 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5148 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005149 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005150 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005151 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005152
Anders Carlsson525b76b2009-10-16 02:48:28 +00005153 // Reject any other conversions to non-scalar types.
5154 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5155 << castType << castExpr->getSourceRange();
5156 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005157
John McCalld7646252010-11-14 08:17:51 +00005158 // The type we're casting to is known to be a scalar or vector.
5159
5160 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005161 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005162 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005163 return Diag(castExpr->getLocStart(),
5164 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005165 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005166 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005167
5168 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005169 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005170
Anton Yartsev28ccef72011-03-27 09:32:40 +00005171 if (castType->isVectorType()) {
5172 if (castType->getAs<VectorType>()->getVectorKind() ==
5173 VectorType::AltiVecVector &&
5174 (castExpr->getType()->isIntegerType() ||
5175 castExpr->getType()->isFloatingType())) {
5176 Kind = CK_VectorSplat;
5177 return false;
5178 } else
5179 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5180 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005181 if (castExpr->getType()->isVectorType())
5182 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5183
John McCalld7646252010-11-14 08:17:51 +00005184 // The source and target types are both scalars, i.e.
5185 // - arithmetic types (fundamental, enum, and complex)
5186 // - all kinds of pointers
5187 // Note that member pointers were filtered out with C++, above.
5188
Anders Carlsson43d70f82009-10-16 05:23:41 +00005189 if (isa<ObjCSelectorExpr>(castExpr))
5190 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005191
John McCalld7646252010-11-14 08:17:51 +00005192 // If either type is a pointer, the other type has to be either an
5193 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005194 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005195 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005196 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005197 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005198 return Diag(castExpr->getLocStart(),
5199 diag::err_cast_pointer_from_non_pointer_int)
5200 << castExprType << castExpr->getSourceRange();
5201 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005202 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005203 return Diag(castExpr->getLocStart(),
5204 diag::err_cast_pointer_to_non_pointer_int)
5205 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005206 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005207
John McCalld7646252010-11-14 08:17:51 +00005208 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005209
John McCalld7646252010-11-14 08:17:51 +00005210 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005211 CheckCastAlign(castExpr, castType, TyR);
5212
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005213 return false;
5214}
5215
Anders Carlsson525b76b2009-10-16 02:48:28 +00005216bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005217 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005218 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005219
Anders Carlssonde71adf2007-11-27 05:51:55 +00005220 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005221 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005222 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005223 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005224 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005225 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005226 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005227 } else
5228 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005229 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005230 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005231
John McCalle3027922010-08-25 11:45:40 +00005232 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005233 return false;
5234}
5235
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005236bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005237 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005238 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005239
Anders Carlsson43d70f82009-10-16 05:23:41 +00005240 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005241
Nate Begemanc8961a42009-06-27 22:05:55 +00005242 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5243 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005244 if (SrcTy->isVectorType()) {
5245 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5246 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5247 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005248 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005249 return false;
5250 }
5251
Nate Begemanbd956c42009-06-28 02:36:38 +00005252 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005253 // conversion will take place first from scalar to elt type, and then
5254 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005255 if (SrcTy->isPointerType())
5256 return Diag(R.getBegin(),
5257 diag::err_invalid_conversion_between_vector_and_scalar)
5258 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005259
5260 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5261 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005262 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005263
John McCalle3027922010-08-25 11:45:40 +00005264 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005265 return false;
5266}
5267
John McCalldadc5752010-08-24 06:29:42 +00005268ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005269Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005270 SourceLocation RParenLoc, Expr *castExpr) {
5271 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005272 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005273
John McCall97513962010-01-15 18:39:57 +00005274 TypeSourceInfo *castTInfo;
5275 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5276 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005277 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005278
Nate Begeman5ec4b312009-08-10 23:49:36 +00005279 // If the Expr being casted is a ParenListExpr, handle it specially.
5280 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005281 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005282 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005283
John McCallb268a282010-08-23 23:25:46 +00005284 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005285}
5286
John McCalldadc5752010-08-24 06:29:42 +00005287ExprResult
John McCallebe54742010-01-15 18:56:44 +00005288Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005289 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005290 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005291 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005292 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005293 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005294 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005295 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005296
John McCallcf142162010-08-07 06:22:56 +00005297 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005298 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005299 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005300 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005301}
5302
Nate Begeman5ec4b312009-08-10 23:49:36 +00005303/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5304/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005305ExprResult
John McCallb268a282010-08-23 23:25:46 +00005306Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005307 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5308 if (!E)
5309 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005310
John McCalldadc5752010-08-24 06:29:42 +00005311 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005312
Nate Begeman5ec4b312009-08-10 23:49:36 +00005313 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005314 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5315 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005316
John McCallb268a282010-08-23 23:25:46 +00005317 if (Result.isInvalid()) return ExprError();
5318
5319 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005320}
5321
John McCalldadc5752010-08-24 06:29:42 +00005322ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005323Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005324 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005325 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005326 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005327 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005328 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005329
Anton Yartsev28ccef72011-03-27 09:32:40 +00005330 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005331 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005332 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5333 if (PE->getNumExprs() == 0) {
5334 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5335 return ExprError();
5336 }
John Thompson781ad172010-06-30 22:55:51 +00005337 if (PE->getNumExprs() == 1) {
5338 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005339 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005340 }
5341 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005342 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005343 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005344
Anton Yartsev28ccef72011-03-27 09:32:40 +00005345 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005346 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005347 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005348 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005349 // '(...)' form of vector initialization in AltiVec: the number of
5350 // initializers must be one or must match the size of the vector.
5351 // If a single value is specified in the initializer then it will be
5352 // replicated to all the components of the vector
5353 if (Ty->getAs<VectorType>()->getVectorKind() ==
5354 VectorType::AltiVecVector) {
5355 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5356 // The number of initializers must be one or must match the size of the
5357 // vector. If a single value is specified in the initializer then it will
5358 // be replicated to all the components of the vector
5359 if (PE->getNumExprs() == 1) {
5360 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5361 Expr *Literal = PE->getExpr(0);
5362 ImpCastExprToType(Literal, ElemTy,
5363 PrepareScalarCast(*this, Literal, ElemTy));
5364 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal);
5365 }
5366 else if (PE->getNumExprs() < numElems) {
5367 Diag(PE->getExprLoc(),
5368 diag::err_incorrect_number_of_vector_initializers);
5369 return ExprError();
5370 }
5371 else
5372 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5373 initExprs.push_back(PE->getExpr(i));
5374 }
5375 else
5376 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5377 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005378
5379 // FIXME: This means that pretty-printing the final AST will produce curly
5380 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005381 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5382 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005383 initExprs.size(), RParenLoc);
5384 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005385 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005386 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005387 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005388 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005389 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005390 if (Result.isInvalid()) return ExprError();
5391 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005392 }
5393}
5394
John McCalldadc5752010-08-24 06:29:42 +00005395ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005396 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005397 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005398 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005399 unsigned nexprs = Val.size();
5400 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005401 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5402 Expr *expr;
5403 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5404 expr = new (Context) ParenExpr(L, R, exprs[0]);
5405 else
5406 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005407 return Owned(expr);
5408}
5409
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005410/// \brief Emit a specialized diagnostic when one expression is a null pointer
5411/// constant and the other is not a pointer.
5412bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5413 SourceLocation QuestionLoc) {
5414 Expr *NullExpr = LHS;
5415 Expr *NonPointerExpr = RHS;
5416 Expr::NullPointerConstantKind NullKind =
5417 NullExpr->isNullPointerConstant(Context,
5418 Expr::NPC_ValueDependentIsNotNull);
5419
5420 if (NullKind == Expr::NPCK_NotNull) {
5421 NullExpr = RHS;
5422 NonPointerExpr = LHS;
5423 NullKind =
5424 NullExpr->isNullPointerConstant(Context,
5425 Expr::NPC_ValueDependentIsNotNull);
5426 }
5427
5428 if (NullKind == Expr::NPCK_NotNull)
5429 return false;
5430
5431 if (NullKind == Expr::NPCK_ZeroInteger) {
5432 // In this case, check to make sure that we got here from a "NULL"
5433 // string in the source code.
5434 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005435 SourceLocation loc = NullExpr->getExprLoc();
5436 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005437 return false;
5438 }
5439
5440 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5441 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5442 << NonPointerExpr->getType() << DiagType
5443 << NonPointerExpr->getSourceRange();
5444 return true;
5445}
5446
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005447/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5448/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005449/// C99 6.5.15
5450QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005451 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005452 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005453
5454 // If either LHS or RHS are overloaded functions, try to resolve them.
John McCall31996342011-04-07 08:22:57 +00005455 ExprResult lhsResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5456 if (!lhsResult.isUsable()) return QualType();
5457 LHS = lhsResult.take();
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005458
John McCall31996342011-04-07 08:22:57 +00005459 ExprResult rhsResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5460 if (!rhsResult.isUsable()) return QualType();
5461 RHS = rhsResult.take();
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005462
Sebastian Redl1a99f442009-04-16 17:51:27 +00005463 // C++ is sufficiently different to merit its own checker.
5464 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005465 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005466
5467 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005468 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005469
Chris Lattner432cff52009-02-18 04:28:32 +00005470 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005471 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005472 UsualUnaryConversions(RHS);
5473 QualType CondTy = Cond->getType();
5474 QualType LHSTy = LHS->getType();
5475 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005476
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005477 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005478 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005479 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5480 // Throw an error if its not either.
5481 if (getLangOptions().OpenCL) {
5482 if (!CondTy->isVectorType()) {
5483 Diag(Cond->getLocStart(),
5484 diag::err_typecheck_cond_expect_scalar_or_vector)
5485 << CondTy;
5486 return QualType();
5487 }
5488 }
5489 else {
5490 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5491 << CondTy;
5492 return QualType();
5493 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005494 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495
Chris Lattnere2949f42008-01-06 22:42:25 +00005496 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005497 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5498 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005499
Nate Begemanabb5a732010-09-20 22:41:17 +00005500 // OpenCL: If the condition is a vector, and both operands are scalar,
5501 // attempt to implicity convert them to the vector type to act like the
5502 // built in select.
5503 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5504 // Both operands should be of scalar type.
5505 if (!LHSTy->isScalarType()) {
5506 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5507 << CondTy;
5508 return QualType();
5509 }
5510 if (!RHSTy->isScalarType()) {
5511 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5512 << CondTy;
5513 return QualType();
5514 }
5515 // Implicity convert these scalars to the type of the condition.
5516 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5517 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5518 }
5519
Chris Lattnere2949f42008-01-06 22:42:25 +00005520 // If both operands have arithmetic type, do the usual arithmetic conversions
5521 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005522 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5523 UsualArithmeticConversions(LHS, RHS);
5524 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005525 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005526
Chris Lattnere2949f42008-01-06 22:42:25 +00005527 // If both operands are the same structure or union type, the result is that
5528 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005529 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5530 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005531 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005532 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005533 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005534 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005535 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005536 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005537
Chris Lattnere2949f42008-01-06 22:42:25 +00005538 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005539 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005540 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5541 if (!LHSTy->isVoidType())
5542 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5543 << RHS->getSourceRange();
5544 if (!RHSTy->isVoidType())
5545 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5546 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005547 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5548 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005549 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005550 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005551 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5552 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005553 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005554 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005555 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005556 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005557 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005558 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005559 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005560 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005561 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005562 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005563 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005564
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005565 // All objective-c pointer type analysis is done here.
5566 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5567 QuestionLoc);
5568 if (!compositeType.isNull())
5569 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005570
5571
Steve Naroff05efa972009-07-01 14:36:47 +00005572 // Handle block pointer types.
5573 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5574 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5575 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5576 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005577 ImpCastExprToType(LHS, destType, CK_BitCast);
5578 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005579 return destType;
5580 }
5581 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005582 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005583 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005584 }
Steve Naroff05efa972009-07-01 14:36:47 +00005585 // We have 2 block pointer types.
5586 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5587 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005588 return LHSTy;
5589 }
Steve Naroff05efa972009-07-01 14:36:47 +00005590 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005591 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5592 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005593
Steve Naroff05efa972009-07-01 14:36:47 +00005594 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5595 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005596 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005597 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005598 // In this situation, we assume void* type. No especially good
5599 // reason, but this is what gcc does, and we do have to pick
5600 // to get a consistent AST.
5601 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005602 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5603 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005604 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005605 }
Steve Naroff05efa972009-07-01 14:36:47 +00005606 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005607 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5608 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005609 return LHSTy;
5610 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005611
Steve Naroff05efa972009-07-01 14:36:47 +00005612 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5613 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5614 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005615 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5616 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005617
5618 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5619 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5620 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005621 QualType destPointee
5622 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005623 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005624 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005625 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005626 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005627 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005628 return destType;
5629 }
5630 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005631 QualType destPointee
5632 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005633 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005634 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005635 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005636 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005637 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005638 return destType;
5639 }
5640
5641 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5642 // Two identical pointer types are always compatible.
5643 return LHSTy;
5644 }
5645 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5646 rhptee.getUnqualifiedType())) {
5647 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5648 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5649 // In this situation, we assume void* type. No especially good
5650 // reason, but this is what gcc does, and we do have to pick
5651 // to get a consistent AST.
5652 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005653 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5654 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005655 return incompatTy;
5656 }
5657 // The pointer types are compatible.
5658 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5659 // differently qualified versions of compatible types, the result type is
5660 // a pointer to an appropriately qualified version of the *composite*
5661 // type.
5662 // FIXME: Need to calculate the composite type.
5663 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005664 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5665 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005666 return LHSTy;
5667 }
Mike Stump11289f42009-09-09 15:08:12 +00005668
John McCalle84af4e2010-11-13 01:35:44 +00005669 // GCC compatibility: soften pointer/integer mismatch. Note that
5670 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005671 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5672 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5673 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005674 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005675 return RHSTy;
5676 }
5677 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5678 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5679 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005680 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005681 return LHSTy;
5682 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005683
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005684 // Emit a better diagnostic if one of the expressions is a null pointer
5685 // constant and the other is not a pointer type. In this case, the user most
5686 // likely forgot to take the address of the other expression.
5687 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5688 return QualType();
5689
Chris Lattnere2949f42008-01-06 22:42:25 +00005690 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005691 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5692 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005693 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005694}
5695
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005696/// FindCompositeObjCPointerType - Helper method to find composite type of
5697/// two objective-c pointer types of the two input expressions.
5698QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5699 SourceLocation QuestionLoc) {
5700 QualType LHSTy = LHS->getType();
5701 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005702
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005703 // Handle things like Class and struct objc_class*. Here we case the result
5704 // to the pseudo-builtin, because that will be implicitly cast back to the
5705 // redefinition type if an attempt is made to access its fields.
5706 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005707 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005708 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005709 return LHSTy;
5710 }
5711 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005712 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005713 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005714 return RHSTy;
5715 }
5716 // And the same for struct objc_object* / id
5717 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005718 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005719 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005720 return LHSTy;
5721 }
5722 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005723 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005724 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005725 return RHSTy;
5726 }
5727 // And the same for struct objc_selector* / SEL
5728 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005729 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005730 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005731 return LHSTy;
5732 }
5733 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005734 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005735 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005736 return RHSTy;
5737 }
5738 // Check constraints for Objective-C object pointers types.
5739 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005740
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005741 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5742 // Two identical object pointer types are always compatible.
5743 return LHSTy;
5744 }
5745 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5746 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5747 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005748
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005749 // If both operands are interfaces and either operand can be
5750 // assigned to the other, use that type as the composite
5751 // type. This allows
5752 // xxx ? (A*) a : (B*) b
5753 // where B is a subclass of A.
5754 //
5755 // Additionally, as for assignment, if either type is 'id'
5756 // allow silent coercion. Finally, if the types are
5757 // incompatible then make sure to use 'id' as the composite
5758 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005759
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005760 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5761 // It could return the composite type.
5762 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5763 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5764 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5765 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5766 } else if ((LHSTy->isObjCQualifiedIdType() ||
5767 RHSTy->isObjCQualifiedIdType()) &&
5768 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5769 // Need to handle "id<xx>" explicitly.
5770 // GCC allows qualified id and any Objective-C type to devolve to
5771 // id. Currently localizing to here until clear this should be
5772 // part of ObjCQualifiedIdTypesAreCompatible.
5773 compositeType = Context.getObjCIdType();
5774 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5775 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005776 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005777 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5778 ;
5779 else {
5780 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5781 << LHSTy << RHSTy
5782 << LHS->getSourceRange() << RHS->getSourceRange();
5783 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005784 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5785 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005786 return incompatTy;
5787 }
5788 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005789 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5790 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005791 return compositeType;
5792 }
5793 // Check Objective-C object pointer types and 'void *'
5794 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5795 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5796 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5797 QualType destPointee
5798 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5799 QualType destType = Context.getPointerType(destPointee);
5800 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005801 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005802 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005803 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005804 return destType;
5805 }
5806 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5807 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5808 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5809 QualType destPointee
5810 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5811 QualType destType = Context.getPointerType(destPointee);
5812 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005813 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005814 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005815 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005816 return destType;
5817 }
5818 return QualType();
5819}
5820
Steve Naroff83895f72007-09-16 03:34:24 +00005821/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005822/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005823ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005824 SourceLocation ColonLoc,
5825 Expr *CondExpr, Expr *LHSExpr,
5826 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005827 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5828 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005829 OpaqueValueExpr *opaqueValue = 0;
5830 Expr *commonExpr = 0;
5831 if (LHSExpr == 0) {
5832 commonExpr = CondExpr;
5833
5834 // We usually want to apply unary conversions *before* saving, except
5835 // in the special case of a C++ l-value conditional.
5836 if (!(getLangOptions().CPlusPlus
5837 && !commonExpr->isTypeDependent()
5838 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5839 && commonExpr->isGLValue()
5840 && commonExpr->isOrdinaryOrBitFieldObject()
5841 && RHSExpr->isOrdinaryOrBitFieldObject()
5842 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5843 UsualUnaryConversions(commonExpr);
5844 }
5845
5846 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5847 commonExpr->getType(),
5848 commonExpr->getValueKind(),
5849 commonExpr->getObjectKind());
5850 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005851 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005852
John McCall7decc9e2010-11-18 06:31:45 +00005853 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005854 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005855 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005856 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005857 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005858 return ExprError();
5859
John McCallc07a0c72011-02-17 10:25:35 +00005860 if (!commonExpr)
5861 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5862 LHSExpr, ColonLoc,
5863 RHSExpr, result, VK, OK));
5864
5865 return Owned(new (Context)
5866 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5867 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005868}
5869
John McCallaba90822011-01-31 23:13:11 +00005870// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005871// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005872// routine is it effectively iqnores the qualifiers on the top level pointee.
5873// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5874// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005875static Sema::AssignConvertType
5876checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5877 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5878 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005879
Steve Naroff1f4d7272007-05-11 04:00:31 +00005880 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005881 const Type *lhptee, *rhptee;
5882 Qualifiers lhq, rhq;
5883 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5884 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005885
John McCallaba90822011-01-31 23:13:11 +00005886 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005887
5888 // C99 6.5.16.1p1: This following citation is common to constraints
5889 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5890 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005891 Qualifiers lq;
5892
5893 if (!lhq.compatiblyIncludes(rhq)) {
5894 // Treat address-space mismatches as fatal. TODO: address subspaces
5895 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5896 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5897
John McCall78535952011-03-26 02:56:45 +00005898 // It's okay to add or remove GC qualifiers when converting to
5899 // and from void*.
5900 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
5901 && (lhptee->isVoidType() || rhptee->isVoidType()))
5902 ; // keep old
5903
John McCall4fff8f62011-02-01 00:10:29 +00005904 // For GCC compatibility, other qualifier mismatches are treated
5905 // as still compatible in C.
5906 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5907 }
Steve Naroff3f597292007-05-11 22:18:03 +00005908
Mike Stump4e1f26a2009-02-19 03:04:26 +00005909 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5910 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005911 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005912 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005913 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005914 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005915
Chris Lattner0a788432008-01-03 22:56:36 +00005916 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005917 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005918 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005919 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Chris Lattner0a788432008-01-03 22:56:36 +00005921 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005922 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005923 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005924
5925 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005926 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005927 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005928 }
John McCall4fff8f62011-02-01 00:10:29 +00005929
Mike Stump4e1f26a2009-02-19 03:04:26 +00005930 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005931 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005932 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5933 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005934 // Check if the pointee types are compatible ignoring the sign.
5935 // We explicitly check for char so that we catch "char" vs
5936 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005937 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005938 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005939 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005940 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005941
Chris Lattnerec3a1562009-10-17 20:33:28 +00005942 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005943 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005944 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005945 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005946
John McCall4fff8f62011-02-01 00:10:29 +00005947 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005948 // Types are compatible ignoring the sign. Qualifier incompatibility
5949 // takes priority over sign incompatibility because the sign
5950 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005951 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005952 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005953
John McCallaba90822011-01-31 23:13:11 +00005954 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005955 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005956
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005957 // If we are a multi-level pointer, it's possible that our issue is simply
5958 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5959 // the eventual target type is the same and the pointers have the same
5960 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005961 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005962 do {
John McCall4fff8f62011-02-01 00:10:29 +00005963 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5964 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005965 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005966
John McCall4fff8f62011-02-01 00:10:29 +00005967 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005968 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005969 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005970
Eli Friedman80160bd2009-03-22 23:59:44 +00005971 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005972 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005973 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005974 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005975}
5976
John McCallaba90822011-01-31 23:13:11 +00005977/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005978/// block pointer types are compatible or whether a block and normal pointer
5979/// are compatible. It is more restrict than comparing two function pointer
5980// types.
John McCallaba90822011-01-31 23:13:11 +00005981static Sema::AssignConvertType
5982checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5983 QualType rhsType) {
5984 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5985 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5986
Steve Naroff081c7422008-09-04 15:10:53 +00005987 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005988
Steve Naroff081c7422008-09-04 15:10:53 +00005989 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005990 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5991 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992
John McCallaba90822011-01-31 23:13:11 +00005993 // In C++, the types have to match exactly.
5994 if (S.getLangOptions().CPlusPlus)
5995 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005996
John McCallaba90822011-01-31 23:13:11 +00005997 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005998
Steve Naroff081c7422008-09-04 15:10:53 +00005999 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006000 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6001 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
John McCallaba90822011-01-31 23:13:11 +00006003 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6004 return Sema::IncompatibleBlockPointer;
6005
Steve Naroff081c7422008-09-04 15:10:53 +00006006 return ConvTy;
6007}
6008
John McCallaba90822011-01-31 23:13:11 +00006009/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006010/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006011static Sema::AssignConvertType
6012checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6013 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6014 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6015
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006016 if (lhsType->isObjCBuiltinType()) {
6017 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006018 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6019 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006020 return Sema::IncompatiblePointer;
6021 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006022 }
6023 if (rhsType->isObjCBuiltinType()) {
6024 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006025 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6026 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006027 return Sema::IncompatiblePointer;
6028 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006029 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006030 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006031 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006032 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006033 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006034
John McCallaba90822011-01-31 23:13:11 +00006035 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6036 return Sema::CompatiblePointerDiscardsQualifiers;
6037
6038 if (S.Context.typesAreCompatible(lhsType, rhsType))
6039 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006040 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006041 return Sema::IncompatibleObjCQualifiedId;
6042 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006043}
6044
John McCall29600e12010-11-16 02:32:08 +00006045Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006046Sema::CheckAssignmentConstraints(SourceLocation Loc,
6047 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006048 // Fake up an opaque expression. We don't actually care about what
6049 // cast operations are required, so if CheckAssignmentConstraints
6050 // adds casts to this they'll be wasted, but fortunately that doesn't
6051 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006052 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00006053 Expr *rhsPtr = &rhs;
6054 CastKind K = CK_Invalid;
6055
6056 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6057}
6058
Mike Stump4e1f26a2009-02-19 03:04:26 +00006059/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6060/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006061/// pointers. Here are some objectionable examples that GCC considers warnings:
6062///
6063/// int a, *pint;
6064/// short *pshort;
6065/// struct foo *pfoo;
6066///
6067/// pint = pshort; // warning: assignment from incompatible pointer type
6068/// a = pint; // warning: assignment makes integer from pointer without a cast
6069/// pint = a; // warning: assignment makes pointer from integer without a cast
6070/// pint = pfoo; // warning: assignment from incompatible pointer type
6071///
6072/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006073/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006074///
John McCall8cb679e2010-11-15 09:13:47 +00006075/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006076Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00006077Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006078 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00006079 QualType rhsType = rhs->getType();
6080
Chris Lattnera52c2f22008-01-04 23:18:45 +00006081 // Get canonical types. We're not formatting these types, just comparing
6082 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006083 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6084 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006085
John McCalle5255932011-01-31 22:28:28 +00006086 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006087 if (lhsType == rhsType) {
6088 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006089 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006090 }
6091
Douglas Gregor6b754842008-10-28 00:22:11 +00006092 // If the left-hand side is a reference type, then we are in a
6093 // (rare!) case where we've allowed the use of references in C,
6094 // e.g., as a parameter type in a built-in function. In this case,
6095 // just make sure that the type referenced is compatible with the
6096 // right-hand side type. The caller is responsible for adjusting
6097 // lhsType so that the resulting expression does not have reference
6098 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006099 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006100 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6101 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006102 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006103 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006104 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006105 }
John McCalle5255932011-01-31 22:28:28 +00006106
Nate Begemanbd956c42009-06-28 02:36:38 +00006107 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6108 // to the same ExtVector type.
6109 if (lhsType->isExtVectorType()) {
6110 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006111 return Incompatible;
6112 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006113 // CK_VectorSplat does T -> vector T, so first cast to the
6114 // element type.
6115 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6116 if (elType != rhsType) {
6117 Kind = PrepareScalarCast(*this, rhs, elType);
6118 ImpCastExprToType(rhs, elType, Kind);
6119 }
6120 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006121 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006122 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006123 }
Mike Stump11289f42009-09-09 15:08:12 +00006124
John McCalle5255932011-01-31 22:28:28 +00006125 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006126 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006127 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006128 // Allow assignments of an AltiVec vector type to an equivalent GCC
6129 // vector type and vice versa
6130 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6131 Kind = CK_BitCast;
6132 return Compatible;
6133 }
6134
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006135 // If we are allowing lax vector conversions, and LHS and RHS are both
6136 // vectors, the total size only needs to be the same. This is a bitcast;
6137 // no bits are changed but the result type is different.
6138 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006139 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006140 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006141 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006142 }
Chris Lattner881a2122008-01-04 23:32:24 +00006143 }
6144 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006145 }
Eli Friedman3360d892008-05-30 18:07:22 +00006146
John McCalle5255932011-01-31 22:28:28 +00006147 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006148 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006149 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006150 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006151 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006152 }
Eli Friedman3360d892008-05-30 18:07:22 +00006153
John McCalle5255932011-01-31 22:28:28 +00006154 // Conversions to normal pointers.
6155 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6156 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006157 if (isa<PointerType>(rhsType)) {
6158 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006159 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006161
John McCalle5255932011-01-31 22:28:28 +00006162 // int -> T*
6163 if (rhsType->isIntegerType()) {
6164 Kind = CK_IntegralToPointer; // FIXME: null?
6165 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006166 }
John McCalle5255932011-01-31 22:28:28 +00006167
6168 // C pointers are not compatible with ObjC object pointers,
6169 // with two exceptions:
6170 if (isa<ObjCObjectPointerType>(rhsType)) {
6171 // - conversions to void*
6172 if (lhsPointer->getPointeeType()->isVoidType()) {
6173 Kind = CK_AnyPointerToObjCPointerCast;
6174 return Compatible;
6175 }
6176
6177 // - conversions from 'Class' to the redefinition type
6178 if (rhsType->isObjCClassType() &&
6179 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006180 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006181 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006182 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006183
John McCalle5255932011-01-31 22:28:28 +00006184 Kind = CK_BitCast;
6185 return IncompatiblePointer;
6186 }
6187
6188 // U^ -> void*
6189 if (rhsType->getAs<BlockPointerType>()) {
6190 if (lhsPointer->getPointeeType()->isVoidType()) {
6191 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006192 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006193 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006194 }
John McCalle5255932011-01-31 22:28:28 +00006195
Steve Naroff081c7422008-09-04 15:10:53 +00006196 return Incompatible;
6197 }
6198
John McCalle5255932011-01-31 22:28:28 +00006199 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006200 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006201 // U^ -> T^
6202 if (rhsType->isBlockPointerType()) {
6203 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006204 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006205 }
6206
6207 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006208 if (rhsType->isIntegerType()) {
6209 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006210 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006211 }
6212
John McCalle5255932011-01-31 22:28:28 +00006213 // id -> T^
6214 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6215 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006216 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006217 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006218
John McCalle5255932011-01-31 22:28:28 +00006219 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006220 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006221 if (RHSPT->getPointeeType()->isVoidType()) {
6222 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006223 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006224 }
John McCall8cb679e2010-11-15 09:13:47 +00006225
Chris Lattnera52c2f22008-01-04 23:18:45 +00006226 return Incompatible;
6227 }
6228
John McCalle5255932011-01-31 22:28:28 +00006229 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006230 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006231 // A* -> B*
6232 if (rhsType->isObjCObjectPointerType()) {
6233 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006234 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006235 }
6236
6237 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006238 if (rhsType->isIntegerType()) {
6239 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006240 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006241 }
6242
John McCalle5255932011-01-31 22:28:28 +00006243 // In general, C pointers are not compatible with ObjC object pointers,
6244 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006245 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006246 // - conversions from 'void*'
6247 if (rhsType->isVoidPointerType()) {
6248 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006249 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006250 }
6251
6252 // - conversions to 'Class' from its redefinition type
6253 if (lhsType->isObjCClassType() &&
6254 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6255 Kind = CK_BitCast;
6256 return Compatible;
6257 }
6258
6259 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006260 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006261 }
John McCalle5255932011-01-31 22:28:28 +00006262
6263 // T^ -> A*
6264 if (rhsType->isBlockPointerType()) {
6265 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006266 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006267 }
6268
Steve Naroff7cae42b2009-07-10 23:34:53 +00006269 return Incompatible;
6270 }
John McCalle5255932011-01-31 22:28:28 +00006271
6272 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006273 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006274 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006275 if (lhsType == Context.BoolTy) {
6276 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006277 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006278 }
Eli Friedman3360d892008-05-30 18:07:22 +00006279
John McCalle5255932011-01-31 22:28:28 +00006280 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006281 if (lhsType->isIntegerType()) {
6282 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006283 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006284 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006285
Chris Lattnera52c2f22008-01-04 23:18:45 +00006286 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006287 }
John McCalle5255932011-01-31 22:28:28 +00006288
6289 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006290 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006291 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006292 if (lhsType == Context.BoolTy) {
6293 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006294 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006295 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006296
John McCalle5255932011-01-31 22:28:28 +00006297 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006298 if (lhsType->isIntegerType()) {
6299 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006300 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006301 }
6302
Steve Naroff7cae42b2009-07-10 23:34:53 +00006303 return Incompatible;
6304 }
Eli Friedman3360d892008-05-30 18:07:22 +00006305
John McCalle5255932011-01-31 22:28:28 +00006306 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006307 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006308 if (Context.typesAreCompatible(lhsType, rhsType)) {
6309 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006310 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006311 }
Bill Wendling216423b2007-05-30 06:30:29 +00006312 }
John McCalle5255932011-01-31 22:28:28 +00006313
Steve Naroff98cf3e92007-06-06 18:38:38 +00006314 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006315}
6316
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006317/// \brief Constructs a transparent union from an expression that is
6318/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006319static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006320 QualType UnionType, FieldDecl *Field) {
6321 // Build an initializer list that designates the appropriate member
6322 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006323 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006324 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006325 SourceLocation());
6326 Initializer->setType(UnionType);
6327 Initializer->setInitializedFieldInUnion(Field);
6328
6329 // Build a compound literal constructing a value of the transparent
6330 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006331 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006332 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006333 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006334}
6335
6336Sema::AssignConvertType
6337Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6338 QualType FromType = rExpr->getType();
6339
Mike Stump11289f42009-09-09 15:08:12 +00006340 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006341 // transparent_union GCC extension.
6342 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006343 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006344 return Incompatible;
6345
6346 // The field to initialize within the transparent union.
6347 RecordDecl *UD = UT->getDecl();
6348 FieldDecl *InitField = 0;
6349 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006350 for (RecordDecl::field_iterator it = UD->field_begin(),
6351 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006352 it != itend; ++it) {
6353 if (it->getType()->isPointerType()) {
6354 // If the transparent union contains a pointer type, we allow:
6355 // 1) void pointer
6356 // 2) null pointer constant
6357 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006358 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006359 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006360 InitField = *it;
6361 break;
6362 }
Mike Stump11289f42009-09-09 15:08:12 +00006363
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006364 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006365 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006366 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006367 InitField = *it;
6368 break;
6369 }
6370 }
6371
John McCall29600e12010-11-16 02:32:08 +00006372 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006373 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006374 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006375 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006376 ImpCastExprToType(rhs, it->getType(), Kind);
6377 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006378 InitField = *it;
6379 break;
6380 }
6381 }
6382
6383 if (!InitField)
6384 return Incompatible;
6385
6386 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6387 return Compatible;
6388}
6389
Chris Lattner9bad62c2008-01-04 18:04:52 +00006390Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006391Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006392 if (getLangOptions().CPlusPlus) {
6393 if (!lhsType->isRecordType()) {
6394 // C++ 5.17p3: If the left operand is not of class type, the
6395 // expression is implicitly converted (C++ 4) to the
6396 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006397 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006398 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006399 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006400 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006401 }
6402
6403 // FIXME: Currently, we fall through and treat C++ classes like C
6404 // structures.
John McCall34376a62010-12-04 03:47:34 +00006405 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006406
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006407 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6408 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006409 if ((lhsType->isPointerType() ||
6410 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006411 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006412 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006413 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006414 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006415 return Compatible;
6416 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006417
Chris Lattnere6dcd502007-10-16 02:55:40 +00006418 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006419 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006420 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006421 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006422 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006423 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006424 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006425 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006426
John McCall8cb679e2010-11-15 09:13:47 +00006427 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006428 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006429 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006430
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006431 // C99 6.5.16.1p2: The value of the right operand is converted to the
6432 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006433 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6434 // so that we can use references in built-in functions even in C.
6435 // The getNonReferenceType() call makes sure that the resulting expression
6436 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006437 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006438 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006439 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006440}
6441
Chris Lattner326f7572008-11-18 01:30:42 +00006442QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006443 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006444 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006445 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006446 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006447}
6448
Chris Lattnerfaa54172010-01-12 21:23:57 +00006449QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006450 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006451 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006452 QualType lhsType =
6453 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6454 QualType rhsType =
6455 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006456
Nate Begeman191a6b12008-07-14 18:02:46 +00006457 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006458 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006459 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006460
Nate Begeman191a6b12008-07-14 18:02:46 +00006461 // Handle the case of a vector & extvector type of the same size and element
6462 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006463 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006464 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006465 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006466 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006467 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006468 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006469 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006470 return lhsType;
6471 }
6472
John McCalle3027922010-08-25 11:45:40 +00006473 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006474 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006475 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6476 // If we are allowing lax vector conversions, and LHS and RHS are both
6477 // vectors, the total size only needs to be the same. This is a
6478 // bitcast; no bits are changed but the result type is different.
6479 ImpCastExprToType(rex, lhsType, CK_BitCast);
6480 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006481 }
Eric Christophera613f562010-08-26 00:42:16 +00006482 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006483 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006484 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006485
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006486 // Handle the case of equivalent AltiVec and GCC vector types
6487 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6488 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006489 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006490 return rhsType;
6491 }
6492
Nate Begemanbd956c42009-06-28 02:36:38 +00006493 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6494 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6495 bool swapped = false;
6496 if (rhsType->isExtVectorType()) {
6497 swapped = true;
6498 std::swap(rex, lex);
6499 std::swap(rhsType, lhsType);
6500 }
Mike Stump11289f42009-09-09 15:08:12 +00006501
Nate Begeman886448d2009-06-28 19:12:57 +00006502 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006503 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006504 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006505 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006506 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6507 if (order > 0)
6508 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6509 if (order >= 0) {
6510 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006511 if (swapped) std::swap(rex, lex);
6512 return lhsType;
6513 }
6514 }
6515 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6516 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006517 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6518 if (order > 0)
6519 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6520 if (order >= 0) {
6521 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006522 if (swapped) std::swap(rex, lex);
6523 return lhsType;
6524 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006525 }
6526 }
Mike Stump11289f42009-09-09 15:08:12 +00006527
Nate Begeman886448d2009-06-28 19:12:57 +00006528 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006529 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006530 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006531 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006532 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006533}
6534
Chris Lattnerfaa54172010-01-12 21:23:57 +00006535QualType Sema::CheckMultiplyDivideOperands(
6536 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006537 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006538 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006539
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006540 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006541
Chris Lattnerfaa54172010-01-12 21:23:57 +00006542 if (!lex->getType()->isArithmeticType() ||
6543 !rex->getType()->isArithmeticType())
6544 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006545
Chris Lattnerfaa54172010-01-12 21:23:57 +00006546 // Check for division by zero.
6547 if (isDiv &&
6548 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006549 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6550 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006551
Chris Lattnerfaa54172010-01-12 21:23:57 +00006552 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006553}
6554
Chris Lattnerfaa54172010-01-12 21:23:57 +00006555QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006556 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006557 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006558 if (lex->getType()->hasIntegerRepresentation() &&
6559 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006560 return CheckVectorOperands(Loc, lex, rex);
6561 return InvalidOperands(Loc, lex, rex);
6562 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006563
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006564 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006565
Chris Lattnerfaa54172010-01-12 21:23:57 +00006566 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6567 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006568
Chris Lattnerfaa54172010-01-12 21:23:57 +00006569 // Check for remainder by zero.
6570 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006571 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6572 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006573
Chris Lattnerfaa54172010-01-12 21:23:57 +00006574 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006575}
6576
Chris Lattnerfaa54172010-01-12 21:23:57 +00006577QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006578 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006579 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6580 QualType compType = CheckVectorOperands(Loc, lex, rex);
6581 if (CompLHSTy) *CompLHSTy = compType;
6582 return compType;
6583 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006584
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006585 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006586
Steve Naroffe4718892007-04-27 18:30:00 +00006587 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006588 if (lex->getType()->isArithmeticType() &&
6589 rex->getType()->isArithmeticType()) {
6590 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006591 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006592 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006593
Eli Friedman8e122982008-05-18 18:08:51 +00006594 // Put any potential pointer into PExp
6595 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006596 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006597 std::swap(PExp, IExp);
6598
Steve Naroff6b712a72009-07-14 18:25:06 +00006599 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006600
Eli Friedman8e122982008-05-18 18:08:51 +00006601 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006602 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006603
Chris Lattner12bdebb2009-04-24 23:50:08 +00006604 // Check for arithmetic on pointers to incomplete types.
6605 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006606 if (getLangOptions().CPlusPlus) {
6607 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006608 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006609 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006610 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006611
6612 // GNU extension: arithmetic on pointer to void
6613 Diag(Loc, diag::ext_gnu_void_ptr)
6614 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006615 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006616 if (getLangOptions().CPlusPlus) {
6617 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6618 << lex->getType() << lex->getSourceRange();
6619 return QualType();
6620 }
6621
6622 // GNU extension: arithmetic on pointer to function
6623 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6624 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006625 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006626 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006627 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006628 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006629 PExp->getType()->isObjCObjectPointerType()) &&
6630 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006631 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6632 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006633 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006634 return QualType();
6635 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006636 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006637 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006638 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6639 << PointeeTy << PExp->getSourceRange();
6640 return QualType();
6641 }
Mike Stump11289f42009-09-09 15:08:12 +00006642
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006643 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006644 QualType LHSTy = Context.isPromotableBitField(lex);
6645 if (LHSTy.isNull()) {
6646 LHSTy = lex->getType();
6647 if (LHSTy->isPromotableIntegerType())
6648 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006649 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006650 *CompLHSTy = LHSTy;
6651 }
Eli Friedman8e122982008-05-18 18:08:51 +00006652 return PExp->getType();
6653 }
6654 }
6655
Chris Lattner326f7572008-11-18 01:30:42 +00006656 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006657}
6658
Chris Lattner2a3569b2008-04-07 05:30:13 +00006659// C99 6.5.6
6660QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006661 SourceLocation Loc, QualType* CompLHSTy) {
6662 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6663 QualType compType = CheckVectorOperands(Loc, lex, rex);
6664 if (CompLHSTy) *CompLHSTy = compType;
6665 return compType;
6666 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006667
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006668 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006669
Chris Lattner4d62f422007-12-09 21:53:25 +00006670 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006671
Chris Lattner4d62f422007-12-09 21:53:25 +00006672 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006673 if (lex->getType()->isArithmeticType()
6674 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006675 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006676 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006677 }
Mike Stump11289f42009-09-09 15:08:12 +00006678
Chris Lattner4d62f422007-12-09 21:53:25 +00006679 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006680 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006681 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682
Douglas Gregorac1fb652009-03-24 19:52:54 +00006683 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006684
Douglas Gregorac1fb652009-03-24 19:52:54 +00006685 bool ComplainAboutVoid = false;
6686 Expr *ComplainAboutFunc = 0;
6687 if (lpointee->isVoidType()) {
6688 if (getLangOptions().CPlusPlus) {
6689 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6690 << lex->getSourceRange() << rex->getSourceRange();
6691 return QualType();
6692 }
6693
6694 // GNU C extension: arithmetic on pointer to void
6695 ComplainAboutVoid = true;
6696 } else if (lpointee->isFunctionType()) {
6697 if (getLangOptions().CPlusPlus) {
6698 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006699 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006700 return QualType();
6701 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006702
6703 // GNU C extension: arithmetic on pointer to function
6704 ComplainAboutFunc = lex;
6705 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006706 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006707 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006708 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006709 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006710 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006711
Chris Lattner12bdebb2009-04-24 23:50:08 +00006712 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006713 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006714 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6715 << lpointee << lex->getSourceRange();
6716 return QualType();
6717 }
Mike Stump11289f42009-09-09 15:08:12 +00006718
Chris Lattner4d62f422007-12-09 21:53:25 +00006719 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006720 if (rex->getType()->isIntegerType()) {
6721 if (ComplainAboutVoid)
6722 Diag(Loc, diag::ext_gnu_void_ptr)
6723 << lex->getSourceRange() << rex->getSourceRange();
6724 if (ComplainAboutFunc)
6725 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006726 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006727 << ComplainAboutFunc->getSourceRange();
6728
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006729 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006730 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006731 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006732
Chris Lattner4d62f422007-12-09 21:53:25 +00006733 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006734 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006735 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006736
Douglas Gregorac1fb652009-03-24 19:52:54 +00006737 // RHS must be a completely-type object type.
6738 // Handle the GNU void* extension.
6739 if (rpointee->isVoidType()) {
6740 if (getLangOptions().CPlusPlus) {
6741 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6742 << lex->getSourceRange() << rex->getSourceRange();
6743 return QualType();
6744 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006745
Douglas Gregorac1fb652009-03-24 19:52:54 +00006746 ComplainAboutVoid = true;
6747 } else if (rpointee->isFunctionType()) {
6748 if (getLangOptions().CPlusPlus) {
6749 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006750 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006751 return QualType();
6752 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006753
6754 // GNU extension: arithmetic on pointer to function
6755 if (!ComplainAboutFunc)
6756 ComplainAboutFunc = rex;
6757 } else if (!rpointee->isDependentType() &&
6758 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006759 PDiag(diag::err_typecheck_sub_ptr_object)
6760 << rex->getSourceRange()
6761 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006762 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006763
Eli Friedman168fe152009-05-16 13:54:38 +00006764 if (getLangOptions().CPlusPlus) {
6765 // Pointee types must be the same: C++ [expr.add]
6766 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6767 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6768 << lex->getType() << rex->getType()
6769 << lex->getSourceRange() << rex->getSourceRange();
6770 return QualType();
6771 }
6772 } else {
6773 // Pointee types must be compatible C99 6.5.6p3
6774 if (!Context.typesAreCompatible(
6775 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6776 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6777 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6778 << lex->getType() << rex->getType()
6779 << lex->getSourceRange() << rex->getSourceRange();
6780 return QualType();
6781 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006782 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006783
Douglas Gregorac1fb652009-03-24 19:52:54 +00006784 if (ComplainAboutVoid)
6785 Diag(Loc, diag::ext_gnu_void_ptr)
6786 << lex->getSourceRange() << rex->getSourceRange();
6787 if (ComplainAboutFunc)
6788 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006789 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006790 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006791
6792 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006793 return Context.getPointerDiffType();
6794 }
6795 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006796
Chris Lattner326f7572008-11-18 01:30:42 +00006797 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006798}
6799
Douglas Gregor0bf31402010-10-08 23:50:27 +00006800static bool isScopedEnumerationType(QualType T) {
6801 if (const EnumType *ET = dyn_cast<EnumType>(T))
6802 return ET->getDecl()->isScoped();
6803 return false;
6804}
6805
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006806static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6807 SourceLocation Loc, unsigned Opc,
6808 QualType LHSTy) {
6809 llvm::APSInt Right;
6810 // Check right/shifter operand
6811 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6812 return;
6813
6814 if (Right.isNegative()) {
Ted Kremenek63657fe2011-03-01 18:09:31 +00006815 S.DiagRuntimeBehavior(Loc, rex,
6816 S.PDiag(diag::warn_shift_negative)
6817 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006818 return;
6819 }
6820 llvm::APInt LeftBits(Right.getBitWidth(),
6821 S.Context.getTypeSize(lex->getType()));
6822 if (Right.uge(LeftBits)) {
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006823 S.DiagRuntimeBehavior(Loc, rex,
6824 S.PDiag(diag::warn_shift_gt_typewidth)
6825 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006826 return;
6827 }
6828 if (Opc != BO_Shl)
6829 return;
6830
6831 // When left shifting an ICE which is signed, we can check for overflow which
6832 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6833 // integers have defined behavior modulo one more than the maximum value
6834 // representable in the result type, so never warn for those.
6835 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006836 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006837 LHSTy->hasUnsignedIntegerRepresentation())
6838 return;
6839 llvm::APInt ResultBits =
6840 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6841 if (LeftBits.uge(ResultBits))
6842 return;
6843 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6844 Result = Result.shl(Right);
6845
6846 // If we are only missing a sign bit, this is less likely to result in actual
6847 // bugs -- if the result is cast back to an unsigned type, it will have the
6848 // expected value. Thus we place this behind a different warning that can be
6849 // turned off separately if needed.
6850 if (LeftBits == ResultBits - 1) {
6851 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6852 << Result.toString(10) << LHSTy
6853 << lex->getSourceRange() << rex->getSourceRange();
6854 return;
6855 }
6856
6857 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6858 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6859 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6860}
6861
Chris Lattner2a3569b2008-04-07 05:30:13 +00006862// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006863QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006864 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006865 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006866 if (!lex->getType()->hasIntegerRepresentation() ||
6867 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006868 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006869
Douglas Gregor0bf31402010-10-08 23:50:27 +00006870 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6871 // hasIntegerRepresentation() above instead of this.
6872 if (isScopedEnumerationType(lex->getType()) ||
6873 isScopedEnumerationType(rex->getType())) {
6874 return InvalidOperands(Loc, lex, rex);
6875 }
6876
Nate Begemane46ee9a2009-10-25 02:26:48 +00006877 // Vector shifts promote their scalar inputs to vector type.
6878 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6879 return CheckVectorOperands(Loc, lex, rex);
6880
Chris Lattner5c11c412007-12-12 05:47:28 +00006881 // Shifts don't perform usual arithmetic conversions, they just do integer
6882 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006883
John McCall57cdd882010-12-16 19:28:59 +00006884 // For the LHS, do usual unary conversions, but then reset them away
6885 // if this is a compound assignment.
6886 Expr *old_lex = lex;
6887 UsualUnaryConversions(lex);
6888 QualType LHSTy = lex->getType();
6889 if (isCompAssign) lex = old_lex;
6890
6891 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006892 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006893
Ryan Flynnf53fab82009-08-07 16:20:20 +00006894 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006895 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006896
Chris Lattner5c11c412007-12-12 05:47:28 +00006897 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006898 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006899}
6900
Chandler Carruth17773fc2010-07-10 12:30:03 +00006901static bool IsWithinTemplateSpecialization(Decl *D) {
6902 if (DeclContext *DC = D->getDeclContext()) {
6903 if (isa<ClassTemplateSpecializationDecl>(DC))
6904 return true;
6905 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6906 return FD->isFunctionTemplateSpecialization();
6907 }
6908 return false;
6909}
6910
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006911// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006912QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006913 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006914 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006915
Chris Lattner9a152e22009-12-05 05:40:13 +00006916 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006917 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006918 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006919
Steve Naroff31090012007-07-16 21:54:35 +00006920 QualType lType = lex->getType();
6921 QualType rType = rex->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006922
Chandler Carruth712563b2011-02-17 08:37:06 +00006923 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6924 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6925 QualType LHSStrippedType = LHSStripped->getType();
6926 QualType RHSStrippedType = RHSStripped->getType();
6927
Douglas Gregor1beec452011-03-12 01:48:56 +00006928
6929
Chandler Carruth712563b2011-02-17 08:37:06 +00006930 // Two different enums will raise a warning when compared.
6931 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6932 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6933 if (LHSEnumType->getDecl()->getIdentifier() &&
6934 RHSEnumType->getDecl()->getIdentifier() &&
6935 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6936 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6937 << LHSStrippedType << RHSStrippedType
6938 << lex->getSourceRange() << rex->getSourceRange();
6939 }
6940 }
6941 }
6942
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006943 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006944 !(lType->isBlockPointerType() && isRelational) &&
6945 !lex->getLocStart().isMacroID() &&
6946 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006947 // For non-floating point types, check for self-comparisons of the form
6948 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6949 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006950 //
6951 // NOTE: Don't warn about comparison expressions resulting from macro
6952 // expansion. Also don't warn about comparisons which are only self
6953 // comparisons within a template specialization. The warnings should catch
6954 // obvious cases in the definition of the template anyways. The idea is to
6955 // warn when the typed comparison operator will always evaluate to the same
6956 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006957 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006958 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006959 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006960 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006961 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006962 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006963 << (Opc == BO_EQ
6964 || Opc == BO_LE
6965 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006966 } else if (lType->isArrayType() && rType->isArrayType() &&
6967 !DRL->getDecl()->getType()->isReferenceType() &&
6968 !DRR->getDecl()->getType()->isReferenceType()) {
6969 // what is it always going to eval to?
6970 char always_evals_to;
6971 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006972 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006973 always_evals_to = 0; // false
6974 break;
John McCalle3027922010-08-25 11:45:40 +00006975 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006976 always_evals_to = 1; // true
6977 break;
6978 default:
6979 // best we can say is 'a constant'
6980 always_evals_to = 2; // e.g. array1 <= array2
6981 break;
6982 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006983 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006984 << 1 // array
6985 << always_evals_to);
6986 }
6987 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006988 }
Mike Stump11289f42009-09-09 15:08:12 +00006989
Chris Lattner222b8bd2009-03-08 19:39:53 +00006990 if (isa<CastExpr>(LHSStripped))
6991 LHSStripped = LHSStripped->IgnoreParenCasts();
6992 if (isa<CastExpr>(RHSStripped))
6993 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006994
Chris Lattner222b8bd2009-03-08 19:39:53 +00006995 // Warn about comparisons against a string constant (unless the other
6996 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006997 Expr *literalString = 0;
6998 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006999 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007000 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007001 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007002 literalString = lex;
7003 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007004 } else if ((isa<StringLiteral>(RHSStripped) ||
7005 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007006 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007007 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007008 literalString = rex;
7009 literalStringStripped = RHSStripped;
7010 }
7011
7012 if (literalString) {
7013 std::string resultComparison;
7014 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007015 case BO_LT: resultComparison = ") < 0"; break;
7016 case BO_GT: resultComparison = ") > 0"; break;
7017 case BO_LE: resultComparison = ") <= 0"; break;
7018 case BO_GE: resultComparison = ") >= 0"; break;
7019 case BO_EQ: resultComparison = ") == 0"; break;
7020 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007021 default: assert(false && "Invalid comparison operator");
7022 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007023
Ted Kremenek3427fac2011-02-23 01:52:04 +00007024 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007025 PDiag(diag::warn_stringcompare)
7026 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007027 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007028 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007029 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007030
Douglas Gregorec170db2010-06-08 19:50:34 +00007031 // C99 6.5.8p3 / C99 6.5.9p4
7032 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
7033 UsualArithmeticConversions(lex, rex);
7034 else {
7035 UsualUnaryConversions(lex);
7036 UsualUnaryConversions(rex);
7037 }
7038
7039 lType = lex->getType();
7040 rType = rex->getType();
7041
Douglas Gregorca63811b2008-11-19 03:25:36 +00007042 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007043 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007044
Chris Lattnerb620c342007-08-26 01:18:55 +00007045 if (isRelational) {
7046 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007047 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007048 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007049 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007050 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007051 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007052
Chris Lattnerb620c342007-08-26 01:18:55 +00007053 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007054 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007055 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007056
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007057 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007058 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007059 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007060 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007061
Douglas Gregorf267edd2010-06-15 21:38:40 +00007062 // All of the following pointer-related warnings are GCC extensions, except
7063 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007064 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007065 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007066 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007067 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007068 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007069
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007070 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007071 if (LCanPointeeTy == RCanPointeeTy)
7072 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007073 if (!isRelational &&
7074 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7075 // Valid unless comparison between non-null pointer and function pointer
7076 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007077 // In a SFINAE context, we treat this as a hard error to maintain
7078 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007079 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7080 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007081 Diag(Loc,
7082 isSFINAEContext()?
7083 diag::err_typecheck_comparison_of_fptr_to_void
7084 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007085 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007086
7087 if (isSFINAEContext())
7088 return QualType();
7089
John McCalle3027922010-08-25 11:45:40 +00007090 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007091 return ResultTy;
7092 }
7093 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007094
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007095 // C++ [expr.rel]p2:
7096 // [...] Pointer conversions (4.10) and qualification
7097 // conversions (4.4) are performed on pointer operands (or on
7098 // a pointer operand and a null pointer constant) to bring
7099 // them to their composite pointer type. [...]
7100 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007101 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007102 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007103 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007104 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007105 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007106 if (T.isNull()) {
7107 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
7108 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7109 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007110 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007111 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007112 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007113 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007114 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007115 }
7116
John McCalle3027922010-08-25 11:45:40 +00007117 ImpCastExprToType(lex, T, CK_BitCast);
7118 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007119 return ResultTy;
7120 }
Eli Friedman16c209612009-08-23 00:27:47 +00007121 // C99 6.5.9p2 and C99 6.5.8p2
7122 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7123 RCanPointeeTy.getUnqualifiedType())) {
7124 // Valid unless a relational comparison of function pointers
7125 if (isRelational && LCanPointeeTy->isFunctionType()) {
7126 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7127 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7128 }
7129 } else if (!isRelational &&
7130 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7131 // Valid unless comparison between non-null pointer and function pointer
7132 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7133 && !LHSIsNull && !RHSIsNull) {
7134 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7135 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7136 }
7137 } else {
7138 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007139 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007140 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007141 }
John McCall7684dde2011-03-11 04:25:25 +00007142 if (LCanPointeeTy != RCanPointeeTy) {
7143 if (LHSIsNull && !RHSIsNull)
7144 ImpCastExprToType(lex, rType, CK_BitCast);
7145 else
7146 ImpCastExprToType(rex, lType, CK_BitCast);
7147 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007148 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007149 }
Mike Stump11289f42009-09-09 15:08:12 +00007150
Sebastian Redl576fd422009-05-10 18:38:11 +00007151 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007152 // Comparison of nullptr_t with itself.
7153 if (lType->isNullPtrType() && rType->isNullPtrType())
7154 return ResultTy;
7155
Mike Stump11289f42009-09-09 15:08:12 +00007156 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007157 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007158 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007159 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007160 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007161 ImpCastExprToType(rex, lType,
7162 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007163 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007164 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007165 return ResultTy;
7166 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007167 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007168 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007169 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007170 ImpCastExprToType(lex, rType,
7171 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007172 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007173 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007174 return ResultTy;
7175 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007176
7177 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007178 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007179 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7180 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007181 // In addition, pointers to members can be compared, or a pointer to
7182 // member and a null pointer constant. Pointer to member conversions
7183 // (4.11) and qualification conversions (4.4) are performed to bring
7184 // them to a common type. If one operand is a null pointer constant,
7185 // the common type is the type of the other operand. Otherwise, the
7186 // common type is a pointer to member type similar (4.4) to the type
7187 // of one of the operands, with a cv-qualification signature (4.4)
7188 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007189 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007190 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007191 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007192 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007193 if (T.isNull()) {
7194 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007195 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007196 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007197 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007198 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007199 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007200 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007201 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007202 }
Mike Stump11289f42009-09-09 15:08:12 +00007203
John McCalle3027922010-08-25 11:45:40 +00007204 ImpCastExprToType(lex, T, CK_BitCast);
7205 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007206 return ResultTy;
7207 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007208
7209 // Handle scoped enumeration types specifically, since they don't promote
7210 // to integers.
7211 if (lex->getType()->isEnumeralType() &&
7212 Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
7213 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007214 }
Mike Stump11289f42009-09-09 15:08:12 +00007215
Steve Naroff081c7422008-09-04 15:10:53 +00007216 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007217 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007218 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7219 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007220
Steve Naroff081c7422008-09-04 15:10:53 +00007221 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007222 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007223 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007224 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007225 }
John McCalle3027922010-08-25 11:45:40 +00007226 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007227 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007228 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007229 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007230 if (!isRelational
7231 && ((lType->isBlockPointerType() && rType->isPointerType())
7232 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007233 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007234 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007235 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007236 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007237 ->getPointeeType()->isVoidType())))
7238 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7239 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007240 }
John McCall7684dde2011-03-11 04:25:25 +00007241 if (LHSIsNull && !RHSIsNull)
7242 ImpCastExprToType(lex, rType, CK_BitCast);
7243 else
7244 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007245 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007246 }
Steve Naroff081c7422008-09-04 15:10:53 +00007247
John McCall7684dde2011-03-11 04:25:25 +00007248 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7249 const PointerType *LPT = lType->getAs<PointerType>();
7250 const PointerType *RPT = rType->getAs<PointerType>();
7251 if (LPT || RPT) {
7252 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7253 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007254
Steve Naroff753567f2008-11-17 19:49:16 +00007255 if (!LPtrToVoid && !RPtrToVoid &&
7256 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007257 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007258 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007259 }
John McCall7684dde2011-03-11 04:25:25 +00007260 if (LHSIsNull && !RHSIsNull)
7261 ImpCastExprToType(lex, rType, CK_BitCast);
7262 else
7263 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007264 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007265 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007266 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007267 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007268 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7269 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007270 if (LHSIsNull && !RHSIsNull)
7271 ImpCastExprToType(lex, rType, CK_BitCast);
7272 else
7273 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007274 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007275 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007276 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007277 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7278 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007279 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007280 bool isError = false;
7281 if ((LHSIsNull && lType->isIntegerType()) ||
7282 (RHSIsNull && rType->isIntegerType())) {
7283 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007284 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007285 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007286 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007287 else if (getLangOptions().CPlusPlus) {
7288 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7289 isError = true;
7290 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007291 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007292
Chris Lattnerd99bd522009-08-23 00:03:44 +00007293 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007294 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007295 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007296 if (isError)
7297 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007298 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007299
7300 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007301 ImpCastExprToType(lex, rType,
7302 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007303 else
John McCalle84af4e2010-11-13 01:35:44 +00007304 ImpCastExprToType(rex, lType,
7305 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007306 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007307 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007308
Steve Naroff4b191572008-09-04 16:56:14 +00007309 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007310 if (!isRelational && RHSIsNull
7311 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007312 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007313 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007314 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007315 if (!isRelational && LHSIsNull
7316 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007317 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007318 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007319 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007320
Chris Lattner326f7572008-11-18 01:30:42 +00007321 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007322}
7323
Nate Begeman191a6b12008-07-14 18:02:46 +00007324/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007325/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007326/// like a scalar comparison, a vector comparison produces a vector of integer
7327/// types.
7328QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007329 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007330 bool isRelational) {
7331 // Check to make sure we're operating on vectors of the same type and width,
7332 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007333 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007334 if (vType.isNull())
7335 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007336
Nate Begeman191a6b12008-07-14 18:02:46 +00007337 QualType lType = lex->getType();
7338 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007339
Anton Yartsev530deb92011-03-27 15:36:07 +00007340 // If AltiVec, the comparison results in a numeric type, i.e.
7341 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007342 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007343 return Context.getLogicalOperationType();
7344
Nate Begeman191a6b12008-07-14 18:02:46 +00007345 // For non-floating point types, check for self-comparisons of the form
7346 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7347 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007348 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007349 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7350 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7351 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007352 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007353 PDiag(diag::warn_comparison_always)
7354 << 0 // self-
7355 << 2 // "a constant"
7356 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007357 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007358
Nate Begeman191a6b12008-07-14 18:02:46 +00007359 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007360 if (!isRelational && lType->hasFloatingRepresentation()) {
7361 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007362 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007363 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007364
Nate Begeman191a6b12008-07-14 18:02:46 +00007365 // Return the type for the comparison, which is the same as vector type for
7366 // integer vectors, or an integer type of identical size and number of
7367 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007368 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007369 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007370
John McCall9dd450b2009-09-21 23:43:11 +00007371 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007372 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007373 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007374 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007375 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007376 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7377
Mike Stump4e1f26a2009-02-19 03:04:26 +00007378 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007379 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007380 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7381}
7382
Steve Naroff218bc2b2007-05-04 21:54:46 +00007383inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007384 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007385 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7386 if (lex->getType()->hasIntegerRepresentation() &&
7387 rex->getType()->hasIntegerRepresentation())
7388 return CheckVectorOperands(Loc, lex, rex);
7389
7390 return InvalidOperands(Loc, lex, rex);
7391 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007392
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007393 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007394
Douglas Gregor0bf31402010-10-08 23:50:27 +00007395 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7396 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007397 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007398 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007399}
7400
Steve Naroff218bc2b2007-05-04 21:54:46 +00007401inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007402 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7403
7404 // Diagnose cases where the user write a logical and/or but probably meant a
7405 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7406 // is a constant.
7407 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007408 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007409 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007410 !Loc.isMacroID()) {
7411 // If the RHS can be constant folded, and if it constant folds to something
7412 // that isn't 0 or 1 (which indicate a potential logical operation that
7413 // happened to fold to true/false) then warn.
7414 Expr::EvalResult Result;
7415 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7416 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7417 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7418 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007419 << (Opc == BO_LAnd ? "&&" : "||")
7420 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007421 }
7422 }
Chris Lattner8406c512010-07-13 19:41:32 +00007423
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007424 if (!Context.getLangOptions().CPlusPlus) {
7425 UsualUnaryConversions(lex);
7426 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007427
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007428 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7429 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007430
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007431 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007433
John McCall4a2429a2010-06-04 00:29:51 +00007434 // The following is safe because we only use this method for
7435 // non-overloadable operands.
7436
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007437 // C++ [expr.log.and]p1
7438 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007439 // The operands are both contextually converted to type bool.
7440 if (PerformContextuallyConvertToBool(lex) ||
7441 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007442 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007443
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007444 // C++ [expr.log.and]p2
7445 // C++ [expr.log.or]p2
7446 // The result is a bool.
7447 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007448}
7449
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007450/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7451/// is a read-only property; return true if so. A readonly property expression
7452/// depends on various declarations and thus must be treated specially.
7453///
Mike Stump11289f42009-09-09 15:08:12 +00007454static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007455 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7456 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007457 if (PropExpr->isImplicitProperty()) return false;
7458
7459 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7460 QualType BaseType = PropExpr->isSuperReceiver() ?
7461 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007462 PropExpr->getBase()->getType();
7463
John McCallb7bd14f2010-12-02 01:19:52 +00007464 if (const ObjCObjectPointerType *OPT =
7465 BaseType->getAsObjCInterfacePointerType())
7466 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7467 if (S.isPropertyReadonly(PDecl, IFace))
7468 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007469 }
7470 return false;
7471}
7472
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007473static bool IsConstProperty(Expr *E, Sema &S) {
7474 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7475 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7476 if (PropExpr->isImplicitProperty()) return false;
7477
7478 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7479 QualType T = PDecl->getType();
7480 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007481 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007482 CanQualType CT = S.Context.getCanonicalType(T);
7483 return CT.isConstQualified();
7484 }
7485 return false;
7486}
7487
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007488static bool IsReadonlyMessage(Expr *E, Sema &S) {
7489 if (E->getStmtClass() != Expr::MemberExprClass)
7490 return false;
7491 const MemberExpr *ME = cast<MemberExpr>(E);
7492 NamedDecl *Member = ME->getMemberDecl();
7493 if (isa<FieldDecl>(Member)) {
7494 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7495 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7496 return false;
7497 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7498 }
7499 return false;
7500}
7501
Chris Lattner30bd3272008-11-18 01:22:49 +00007502/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7503/// emit an error and return true. If so, return false.
7504static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007505 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007506 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007507 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007508 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7509 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007510 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7511 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007512 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7513 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007514 if (IsLV == Expr::MLV_Valid)
7515 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007516
Chris Lattner30bd3272008-11-18 01:22:49 +00007517 unsigned Diag = 0;
7518 bool NeedType = false;
7519 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007520 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007521 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007522 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7523 NeedType = true;
7524 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007525 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007526 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7527 NeedType = true;
7528 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007529 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007530 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7531 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007532 case Expr::MLV_Valid:
7533 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007534 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007535 case Expr::MLV_MemberFunction:
7536 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007537 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7538 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007539 case Expr::MLV_IncompleteType:
7540 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007541 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007542 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007543 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007544 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007545 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7546 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007547 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007548 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7549 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007550 case Expr::MLV_ReadonlyProperty:
7551 Diag = diag::error_readonly_property_assignment;
7552 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007553 case Expr::MLV_NoSetterProperty:
7554 Diag = diag::error_nosetter_property_assignment;
7555 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007556 case Expr::MLV_InvalidMessageExpression:
7557 Diag = diag::error_readonly_message_assignment;
7558 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007559 case Expr::MLV_SubObjCPropertySetting:
7560 Diag = diag::error_no_subobject_property_setting;
7561 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007562 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007563
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007564 SourceRange Assign;
7565 if (Loc != OrigLoc)
7566 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007567 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007568 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007569 else
Mike Stump11289f42009-09-09 15:08:12 +00007570 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007571 return true;
7572}
7573
7574
7575
7576// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007577QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7578 SourceLocation Loc,
7579 QualType CompoundType) {
7580 // Verify that LHS is a modifiable lvalue, and emit error if not.
7581 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007582 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007583
7584 QualType LHSType = LHS->getType();
7585 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007586 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007587 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007588 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007589 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007590 if (LHS->getObjectKind() == OK_ObjCProperty)
7591 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007592 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007593 // Special case of NSObject attributes on c-style pointer types.
7594 if (ConvTy == IncompatiblePointer &&
7595 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007596 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007597 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007598 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007599 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007600
John McCall7decc9e2010-11-18 06:31:45 +00007601 if (ConvTy == Compatible &&
7602 getLangOptions().ObjCNonFragileABI &&
7603 LHSType->isObjCObjectType())
7604 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7605 << LHSType;
7606
Chris Lattnerea714382008-08-21 18:04:13 +00007607 // If the RHS is a unary plus or minus, check to see if they = and + are
7608 // right next to each other. If so, the user may have typo'd "x =+ 4"
7609 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007610 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007611 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7612 RHSCheck = ICE->getSubExpr();
7613 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007614 if ((UO->getOpcode() == UO_Plus ||
7615 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007616 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007617 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007618 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7619 // And there is a space or other character before the subexpr of the
7620 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007621 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7622 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007623 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007624 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007625 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007626 }
Chris Lattnerea714382008-08-21 18:04:13 +00007627 }
7628 } else {
7629 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007630 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007631 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007632
Chris Lattner326f7572008-11-18 01:30:42 +00007633 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007634 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007635 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007636
Chris Lattner39561062010-07-07 06:14:23 +00007637
7638 // Check to see if the destination operand is a dereferenced null pointer. If
7639 // so, and if not volatile-qualified, this is undefined behavior that the
7640 // optimizer will delete, so warn about it. People sometimes try to use this
7641 // to get a deterministic trap and are surprised by clang's behavior. This
7642 // only handles the pattern "*null = whatever", which is a very syntactic
7643 // check.
7644 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007645 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007646 UO->getSubExpr()->IgnoreParenCasts()->
7647 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7648 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007649 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7650 PDiag(diag::warn_indirection_through_null)
7651 << UO->getSubExpr()->getSourceRange());
7652 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7653 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007654 }
7655
Ted Kremenek64699be2011-02-16 01:57:07 +00007656 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007657 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007658
Steve Naroff98cf3e92007-06-06 18:38:38 +00007659 // C99 6.5.16p3: The type of an assignment expression is the type of the
7660 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007661 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007662 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7663 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007664 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007665 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007666 return (getLangOptions().CPlusPlus
7667 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007668}
7669
Chris Lattner326f7572008-11-18 01:30:42 +00007670// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007671static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007672 SourceLocation Loc) {
7673 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007674
John McCall4bc41ae2010-11-18 19:01:18 +00007675 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007676 if (LHSResult.isInvalid())
7677 return QualType();
7678
John McCall4bc41ae2010-11-18 19:01:18 +00007679 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007680 if (RHSResult.isInvalid())
7681 return QualType();
7682 RHS = RHSResult.take();
7683
John McCall73d36182010-10-12 07:14:40 +00007684 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7685 // operands, but not unary promotions.
7686 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007687
John McCall34376a62010-12-04 03:47:34 +00007688 // So we treat the LHS as a ignored value, and in C++ we allow the
7689 // containing site to determine what should be done with the RHS.
7690 S.IgnoredValueConversions(LHS);
7691
7692 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007693 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007694 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007695 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007696 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007697
Chris Lattner326f7572008-11-18 01:30:42 +00007698 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007699}
7700
Steve Naroff7a5af782007-07-13 16:58:59 +00007701/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7702/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007703static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7704 ExprValueKind &VK,
7705 SourceLocation OpLoc,
7706 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007707 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007708 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007709
Chris Lattner6b0cf142008-11-21 07:05:48 +00007710 QualType ResType = Op->getType();
7711 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007712
John McCall4bc41ae2010-11-18 19:01:18 +00007713 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007714 // Decrement of bool is not allowed.
7715 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007716 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007717 return QualType();
7718 }
7719 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007720 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007721 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007722 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007723 } else if (ResType->isAnyPointerType()) {
7724 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007725
Chris Lattner6b0cf142008-11-21 07:05:48 +00007726 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007727 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007728 if (S.getLangOptions().CPlusPlus) {
7729 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007730 << Op->getSourceRange();
7731 return QualType();
7732 }
7733
7734 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007735 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007736 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007737 if (S.getLangOptions().CPlusPlus) {
7738 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007739 << Op->getType() << Op->getSourceRange();
7740 return QualType();
7741 }
7742
John McCall4bc41ae2010-11-18 19:01:18 +00007743 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007744 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007745 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7746 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007747 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007748 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007749 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007750 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007751 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7752 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007753 << PointeeTy << Op->getSourceRange();
7754 return QualType();
7755 }
Eli Friedman090addd2010-01-03 00:20:48 +00007756 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007757 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007758 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007759 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007760 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007761 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007762 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007763 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7764 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007765 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7766 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007767 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007768 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007769 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007770 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007771 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007772 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007773 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007774 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007775 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007776 // In C++, a prefix increment is the same type as the operand. Otherwise
7777 // (in C or with postfix), the increment is the unqualified type of the
7778 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007779 if (isPrefix && S.getLangOptions().CPlusPlus) {
7780 VK = VK_LValue;
7781 return ResType;
7782 } else {
7783 VK = VK_RValue;
7784 return ResType.getUnqualifiedType();
7785 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007786}
7787
John McCall34376a62010-12-04 03:47:34 +00007788void Sema::ConvertPropertyForRValue(Expr *&E) {
7789 assert(E->getValueKind() == VK_LValue &&
7790 E->getObjectKind() == OK_ObjCProperty);
7791 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7792
7793 ExprValueKind VK = VK_RValue;
7794 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007795 if (const ObjCMethodDecl *GetterMethod =
7796 PRE->getImplicitPropertyGetter()) {
7797 QualType Result = GetterMethod->getResultType();
7798 VK = Expr::getValueKindForType(Result);
7799 }
7800 else {
7801 Diag(PRE->getLocation(), diag::err_getter_not_found)
7802 << PRE->getBase()->getType();
7803 }
John McCall34376a62010-12-04 03:47:34 +00007804 }
7805
7806 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7807 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007808
7809 ExprResult Result = MaybeBindToTemporary(E);
7810 if (!Result.isInvalid())
7811 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007812}
7813
7814void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7815 assert(LHS->getValueKind() == VK_LValue &&
7816 LHS->getObjectKind() == OK_ObjCProperty);
7817 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7818
7819 if (PRE->isImplicitProperty()) {
7820 // If using property-dot syntax notation for assignment, and there is a
7821 // setter, RHS expression is being passed to the setter argument. So,
7822 // type conversion (and comparison) is RHS to setter's argument type.
7823 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7824 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7825 LHSTy = (*P)->getType();
7826
7827 // Otherwise, if the getter returns an l-value, just call that.
7828 } else {
7829 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7830 ExprValueKind VK = Expr::getValueKindForType(Result);
7831 if (VK == VK_LValue) {
7832 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7833 CK_GetObjCProperty, LHS, 0, VK);
7834 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007835 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007836 }
John McCall34376a62010-12-04 03:47:34 +00007837 }
7838
7839 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007840 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007841 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007842 Expr *Arg = RHS;
7843 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7844 Owned(Arg));
7845 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007846 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007847 }
7848}
7849
7850
Anders Carlsson806700f2008-02-01 07:15:58 +00007851/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007852/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007853/// where the declaration is needed for type checking. We only need to
7854/// handle cases when the expression references a function designator
7855/// or is an lvalue. Here are some examples:
7856/// - &(x) => x
7857/// - &*****f => f for f a function designator.
7858/// - &s.xx => s
7859/// - &s.zz[1].yy -> s, if zz is an array
7860/// - *(x + 1) -> x, if x is an array
7861/// - &"123"[2] -> 0
7862/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007863static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007864 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007865 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007866 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007867 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007868 // If this is an arrow operator, the address is an offset from
7869 // the base's value, so the object the base refers to is
7870 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007871 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007872 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007873 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007874 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007875 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007876 // FIXME: This code shouldn't be necessary! We should catch the implicit
7877 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007878 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7879 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7880 if (ICE->getSubExpr()->getType()->isArrayType())
7881 return getPrimaryDecl(ICE->getSubExpr());
7882 }
7883 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007884 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007885 case Stmt::UnaryOperatorClass: {
7886 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007887
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007888 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007889 case UO_Real:
7890 case UO_Imag:
7891 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007892 return getPrimaryDecl(UO->getSubExpr());
7893 default:
7894 return 0;
7895 }
7896 }
Steve Naroff47500512007-04-19 23:00:49 +00007897 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007898 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007899 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007900 // If the result of an implicit cast is an l-value, we care about
7901 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007902 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007903 default:
7904 return 0;
7905 }
7906}
7907
7908/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007909/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007910/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007911/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007912/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007913/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007914/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007915static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7916 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007917 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007918 return S.Context.DependentTy;
7919 if (OrigOp->getType() == S.Context.OverloadTy)
7920 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007921
John McCall4bc41ae2010-11-18 19:01:18 +00007922 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007923 if (PR.isInvalid()) return QualType();
7924 OrigOp = PR.take();
7925
John McCall8d08b9b2010-08-27 09:08:28 +00007926 // Make sure to ignore parentheses in subsequent checks
7927 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007928
John McCall4bc41ae2010-11-18 19:01:18 +00007929 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007930 // Implement C99-only parts of addressof rules.
7931 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007932 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007933 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7934 // (assuming the deref expression is valid).
7935 return uOp->getSubExpr()->getType();
7936 }
7937 // Technically, there should be a check for array subscript
7938 // expressions here, but the result of one is always an lvalue anyway.
7939 }
John McCallf3a88602011-02-03 08:15:49 +00007940 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007941 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007942
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007943 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007944 bool sfinae = S.isSFINAEContext();
7945 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7946 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007947 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007948 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007949 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007950 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007951 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007952 } else if (lval == Expr::LV_MemberFunction) {
7953 // If it's an instance method, make a member pointer.
7954 // The expression must have exactly the form &A::foo.
7955
7956 // If the underlying expression isn't a decl ref, give up.
7957 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007958 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007959 << OrigOp->getSourceRange();
7960 return QualType();
7961 }
7962 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7963 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7964
7965 // The id-expression was parenthesized.
7966 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007967 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007968 << OrigOp->getSourceRange();
7969
7970 // The method was named without a qualifier.
7971 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007972 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007973 << op->getSourceRange();
7974 }
7975
John McCall4bc41ae2010-11-18 19:01:18 +00007976 return S.Context.getMemberPointerType(op->getType(),
7977 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007978 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007979 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007980 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007981 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007982 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007983 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007984 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007985 return QualType();
7986 }
John McCall086a4642010-11-24 05:12:34 +00007987 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007988 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007989 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007990 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007991 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007992 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007993 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007994 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007995 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007996 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007997 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007998 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007999 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008000 << "property expression" << op->getSourceRange();
8001 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008002 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008003 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008004 // with the register storage-class specifier.
8005 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008006 // in C++ it is not error to take address of a register
8007 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008008 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008009 !S.getLangOptions().CPlusPlus) {
8010 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008011 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008012 return QualType();
8013 }
John McCalld14a8642009-11-21 08:51:07 +00008014 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008015 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008016 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008017 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008018 // Could be a pointer to member, though, if there is an explicit
8019 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008020 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008021 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008022 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008023 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008024 S.Diag(OpLoc,
8025 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008026 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008027 return QualType();
8028 }
Mike Stump11289f42009-09-09 15:08:12 +00008029
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008030 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8031 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008032 return S.Context.getMemberPointerType(op->getType(),
8033 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008034 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008035 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008036 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008037 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008038 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008039
Eli Friedmance7f9002009-05-16 23:27:50 +00008040 if (lval == Expr::LV_IncompleteVoidType) {
8041 // Taking the address of a void variable is technically illegal, but we
8042 // allow it in cases which are otherwise valid.
8043 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008044 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008045 }
8046
Steve Naroff47500512007-04-19 23:00:49 +00008047 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008048 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008049 return S.Context.getObjCObjectPointerType(op->getType());
8050 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008051}
8052
Chris Lattner9156f1b2010-07-05 19:17:26 +00008053/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008054static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8055 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008056 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008057 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008058
John McCall4bc41ae2010-11-18 19:01:18 +00008059 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00008060 QualType OpTy = Op->getType();
8061 QualType Result;
8062
8063 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8064 // is an incomplete type or void. It would be possible to warn about
8065 // dereferencing a void pointer, but it's completely well-defined, and such a
8066 // warning is unlikely to catch any mistakes.
8067 if (const PointerType *PT = OpTy->getAs<PointerType>())
8068 Result = PT->getPointeeType();
8069 else if (const ObjCObjectPointerType *OPT =
8070 OpTy->getAs<ObjCObjectPointerType>())
8071 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008072 else {
John McCall4bc41ae2010-11-18 19:01:18 +00008073 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008074 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008075 if (PR.take() != Op)
8076 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008077 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008078
Chris Lattner9156f1b2010-07-05 19:17:26 +00008079 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008080 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008081 << OpTy << Op->getSourceRange();
8082 return QualType();
8083 }
John McCall4bc41ae2010-11-18 19:01:18 +00008084
8085 // Dereferences are usually l-values...
8086 VK = VK_LValue;
8087
8088 // ...except that certain expressions are never l-values in C.
8089 if (!S.getLangOptions().CPlusPlus &&
8090 IsCForbiddenLValueType(S.Context, Result))
8091 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008092
8093 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008094}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008095
John McCalle3027922010-08-25 11:45:40 +00008096static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008097 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008098 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008099 switch (Kind) {
8100 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008101 case tok::periodstar: Opc = BO_PtrMemD; break;
8102 case tok::arrowstar: Opc = BO_PtrMemI; break;
8103 case tok::star: Opc = BO_Mul; break;
8104 case tok::slash: Opc = BO_Div; break;
8105 case tok::percent: Opc = BO_Rem; break;
8106 case tok::plus: Opc = BO_Add; break;
8107 case tok::minus: Opc = BO_Sub; break;
8108 case tok::lessless: Opc = BO_Shl; break;
8109 case tok::greatergreater: Opc = BO_Shr; break;
8110 case tok::lessequal: Opc = BO_LE; break;
8111 case tok::less: Opc = BO_LT; break;
8112 case tok::greaterequal: Opc = BO_GE; break;
8113 case tok::greater: Opc = BO_GT; break;
8114 case tok::exclaimequal: Opc = BO_NE; break;
8115 case tok::equalequal: Opc = BO_EQ; break;
8116 case tok::amp: Opc = BO_And; break;
8117 case tok::caret: Opc = BO_Xor; break;
8118 case tok::pipe: Opc = BO_Or; break;
8119 case tok::ampamp: Opc = BO_LAnd; break;
8120 case tok::pipepipe: Opc = BO_LOr; break;
8121 case tok::equal: Opc = BO_Assign; break;
8122 case tok::starequal: Opc = BO_MulAssign; break;
8123 case tok::slashequal: Opc = BO_DivAssign; break;
8124 case tok::percentequal: Opc = BO_RemAssign; break;
8125 case tok::plusequal: Opc = BO_AddAssign; break;
8126 case tok::minusequal: Opc = BO_SubAssign; break;
8127 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8128 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8129 case tok::ampequal: Opc = BO_AndAssign; break;
8130 case tok::caretequal: Opc = BO_XorAssign; break;
8131 case tok::pipeequal: Opc = BO_OrAssign; break;
8132 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008133 }
8134 return Opc;
8135}
8136
John McCalle3027922010-08-25 11:45:40 +00008137static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008138 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008139 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008140 switch (Kind) {
8141 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008142 case tok::plusplus: Opc = UO_PreInc; break;
8143 case tok::minusminus: Opc = UO_PreDec; break;
8144 case tok::amp: Opc = UO_AddrOf; break;
8145 case tok::star: Opc = UO_Deref; break;
8146 case tok::plus: Opc = UO_Plus; break;
8147 case tok::minus: Opc = UO_Minus; break;
8148 case tok::tilde: Opc = UO_Not; break;
8149 case tok::exclaim: Opc = UO_LNot; break;
8150 case tok::kw___real: Opc = UO_Real; break;
8151 case tok::kw___imag: Opc = UO_Imag; break;
8152 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008153 }
8154 return Opc;
8155}
8156
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008157/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8158/// This warning is only emitted for builtin assignment operations. It is also
8159/// suppressed in the event of macro expansions.
8160static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8161 SourceLocation OpLoc) {
8162 if (!S.ActiveTemplateInstantiations.empty())
8163 return;
8164 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8165 return;
8166 lhs = lhs->IgnoreParenImpCasts();
8167 rhs = rhs->IgnoreParenImpCasts();
8168 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8169 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8170 if (!LeftDeclRef || !RightDeclRef ||
8171 LeftDeclRef->getLocation().isMacroID() ||
8172 RightDeclRef->getLocation().isMacroID())
8173 return;
8174 const ValueDecl *LeftDecl =
8175 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8176 const ValueDecl *RightDecl =
8177 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8178 if (LeftDecl != RightDecl)
8179 return;
8180 if (LeftDecl->getType().isVolatileQualified())
8181 return;
8182 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8183 if (RefTy->getPointeeType().isVolatileQualified())
8184 return;
8185
8186 S.Diag(OpLoc, diag::warn_self_assignment)
8187 << LeftDeclRef->getType()
8188 << lhs->getSourceRange() << rhs->getSourceRange();
8189}
8190
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008191/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8192/// operator @p Opc at location @c TokLoc. This routine only supports
8193/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008194ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008195 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00008196 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008197 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008198 // The following two variables are used for compound assignment operators
8199 QualType CompLHSTy; // Type of LHS after promotions for computation
8200 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008201 ExprValueKind VK = VK_RValue;
8202 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008203
Douglas Gregor1beec452011-03-12 01:48:56 +00008204 // Check if a 'foo<int>' involved in a binary op, identifies a single
8205 // function unambiguously (i.e. an lvalue ala 13.4)
8206 // But since an assignment can trigger target based overload, exclude it in
8207 // our blind search. i.e:
8208 // template<class T> void f(); template<class T, class U> void f(U);
8209 // f<int> == 0; // resolve f<int> blindly
8210 // void (*p)(int); p = f<int>; // resolve f<int> using target
8211 if (Opc != BO_Assign) {
John McCall31996342011-04-07 08:22:57 +00008212 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs, OpLoc);
8213 if (!resolvedLHS.isUsable()) return ExprError();
8214 lhs = resolvedLHS.take();
8215
8216 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs, OpLoc);
8217 if (!resolvedRHS.isUsable()) return ExprError();
8218 rhs = resolvedRHS.take();
Douglas Gregor1beec452011-03-12 01:48:56 +00008219 }
8220
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008221 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008222 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008223 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008224 if (getLangOptions().CPlusPlus &&
8225 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00008226 VK = lhs->getValueKind();
8227 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008228 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008229 if (!ResultTy.isNull())
8230 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008231 break;
John McCalle3027922010-08-25 11:45:40 +00008232 case BO_PtrMemD:
8233 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008234 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008235 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008236 break;
John McCalle3027922010-08-25 11:45:40 +00008237 case BO_Mul:
8238 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008239 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008240 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008241 break;
John McCalle3027922010-08-25 11:45:40 +00008242 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008243 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8244 break;
John McCalle3027922010-08-25 11:45:40 +00008245 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008246 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8247 break;
John McCalle3027922010-08-25 11:45:40 +00008248 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008249 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8250 break;
John McCalle3027922010-08-25 11:45:40 +00008251 case BO_Shl:
8252 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008253 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008254 break;
John McCalle3027922010-08-25 11:45:40 +00008255 case BO_LE:
8256 case BO_LT:
8257 case BO_GE:
8258 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008259 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008260 break;
John McCalle3027922010-08-25 11:45:40 +00008261 case BO_EQ:
8262 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008263 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008264 break;
John McCalle3027922010-08-25 11:45:40 +00008265 case BO_And:
8266 case BO_Xor:
8267 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008268 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8269 break;
John McCalle3027922010-08-25 11:45:40 +00008270 case BO_LAnd:
8271 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008272 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008273 break;
John McCalle3027922010-08-25 11:45:40 +00008274 case BO_MulAssign:
8275 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008276 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008277 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008278 CompLHSTy = CompResultTy;
8279 if (!CompResultTy.isNull())
8280 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008281 break;
John McCalle3027922010-08-25 11:45:40 +00008282 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008283 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8284 CompLHSTy = CompResultTy;
8285 if (!CompResultTy.isNull())
8286 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008287 break;
John McCalle3027922010-08-25 11:45:40 +00008288 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008289 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8290 if (!CompResultTy.isNull())
8291 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008292 break;
John McCalle3027922010-08-25 11:45:40 +00008293 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008294 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8295 if (!CompResultTy.isNull())
8296 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008297 break;
John McCalle3027922010-08-25 11:45:40 +00008298 case BO_ShlAssign:
8299 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008300 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008301 CompLHSTy = CompResultTy;
8302 if (!CompResultTy.isNull())
8303 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008304 break;
John McCalle3027922010-08-25 11:45:40 +00008305 case BO_AndAssign:
8306 case BO_XorAssign:
8307 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008308 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8309 CompLHSTy = CompResultTy;
8310 if (!CompResultTy.isNull())
8311 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008312 break;
John McCalle3027922010-08-25 11:45:40 +00008313 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008314 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008315 if (getLangOptions().CPlusPlus) {
8316 VK = rhs->getValueKind();
8317 OK = rhs->getObjectKind();
8318 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008319 break;
8320 }
8321 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008322 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008323 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008324 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8325 VK, OK, OpLoc));
8326
John McCall34376a62010-12-04 03:47:34 +00008327 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008328 VK = VK_LValue;
8329 OK = lhs->getObjectKind();
8330 }
8331 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8332 VK, OK, CompLHSTy,
8333 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008334}
8335
Sebastian Redl44615072009-10-27 12:10:02 +00008336/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8337/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008338static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8339 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008340 const PartialDiagnostic &FirstNote,
8341 SourceRange FirstParenRange,
8342 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008343 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008344 Self.Diag(Loc, PD);
8345
8346 if (!FirstNote.getDiagID())
8347 return;
8348
8349 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8350 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8351 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008352 return;
8353 }
8354
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008355 Self.Diag(Loc, FirstNote)
8356 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008357 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008358
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008359 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008360 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008361
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008362 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8363 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8364 // We can't display the parentheses, so just dig the
8365 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008366 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008367 return;
8368 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008369
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008370 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008371 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8372 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008373}
8374
Sebastian Redl44615072009-10-27 12:10:02 +00008375/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8376/// operators are mixed in a way that suggests that the programmer forgot that
8377/// comparison operators have higher precedence. The most typical example of
8378/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008379static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008380 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008381 typedef BinaryOperator BinOp;
8382 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8383 rhsopc = static_cast<BinOp::Opcode>(-1);
8384 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008385 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008386 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008387 rhsopc = BO->getOpcode();
8388
8389 // Subs are not binary operators.
8390 if (lhsopc == -1 && rhsopc == -1)
8391 return;
8392
8393 // Bitwise operations are sometimes used as eager logical ops.
8394 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008395 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8396 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008397 return;
8398
Sebastian Redl44615072009-10-27 12:10:02 +00008399 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008400 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008401 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008402 << SourceRange(lhs->getLocStart(), OpLoc)
8403 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008404 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008405 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008406 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8407 Self.PDiag(diag::note_precedence_bitwise_silence)
8408 << BinOp::getOpcodeStr(lhsopc),
8409 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008410 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008411 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008412 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008413 << SourceRange(OpLoc, rhs->getLocEnd())
8414 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008415 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008416 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008417 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8418 Self.PDiag(diag::note_precedence_bitwise_silence)
8419 << BinOp::getOpcodeStr(rhsopc),
8420 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008421}
8422
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008423/// \brief It accepts a '&&' expr that is inside a '||' one.
8424/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8425/// in parentheses.
8426static void
8427EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8428 Expr *E) {
8429 assert(isa<BinaryOperator>(E) &&
8430 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8431 SuggestParentheses(Self, OpLoc,
8432 Self.PDiag(diag::warn_logical_and_in_logical_or)
8433 << E->getSourceRange(),
8434 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8435 E->getSourceRange(),
8436 Self.PDiag(0), SourceRange());
8437}
8438
8439/// \brief Returns true if the given expression can be evaluated as a constant
8440/// 'true'.
8441static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8442 bool Res;
8443 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8444}
8445
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008446/// \brief Returns true if the given expression can be evaluated as a constant
8447/// 'false'.
8448static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8449 bool Res;
8450 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8451}
8452
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008453/// \brief Look for '&&' in the left hand of a '||' expr.
8454static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008455 Expr *OrLHS, Expr *OrRHS) {
8456 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008457 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008458 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8459 if (EvaluatesAsFalse(S, OrRHS))
8460 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008461 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8462 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8463 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8464 } else if (Bop->getOpcode() == BO_LOr) {
8465 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8466 // If it's "a || b && 1 || c" we didn't warn earlier for
8467 // "a || b && 1", but warn now.
8468 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8469 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8470 }
8471 }
8472 }
8473}
8474
8475/// \brief Look for '&&' in the right hand of a '||' expr.
8476static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008477 Expr *OrLHS, Expr *OrRHS) {
8478 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008479 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008480 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8481 if (EvaluatesAsFalse(S, OrLHS))
8482 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008483 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8484 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8485 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008486 }
8487 }
8488}
8489
Sebastian Redl43028242009-10-26 15:24:15 +00008490/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008491/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008492static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008493 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008494 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008495 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008496 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8497
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008498 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8499 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008500 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008501 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8502 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008503 }
Sebastian Redl43028242009-10-26 15:24:15 +00008504}
8505
Steve Naroff218bc2b2007-05-04 21:54:46 +00008506// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008507ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008508 tok::TokenKind Kind,
8509 Expr *lhs, Expr *rhs) {
8510 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008511 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8512 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008513
Sebastian Redl43028242009-10-26 15:24:15 +00008514 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8515 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8516
Douglas Gregor5287f092009-11-05 00:51:44 +00008517 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8518}
8519
John McCalldadc5752010-08-24 06:29:42 +00008520ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008521 BinaryOperatorKind Opc,
8522 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008523 if (getLangOptions().CPlusPlus) {
8524 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008525
John McCall622114c2010-12-06 05:26:58 +00008526 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8527 UseBuiltinOperator = false;
8528 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8529 UseBuiltinOperator = true;
8530 } else {
8531 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8532 !rhs->getType()->isOverloadableType();
8533 }
8534
8535 if (!UseBuiltinOperator) {
8536 // Find all of the overloaded operators visible from this
8537 // point. We perform both an operator-name lookup from the local
8538 // scope and an argument-dependent lookup based on the types of
8539 // the arguments.
8540 UnresolvedSet<16> Functions;
8541 OverloadedOperatorKind OverOp
8542 = BinaryOperator::getOverloadedOperator(Opc);
8543 if (S && OverOp != OO_None)
8544 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8545 Functions);
8546
8547 // Build the (potentially-overloaded, potentially-dependent)
8548 // binary operation.
8549 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8550 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008551 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008552
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008553 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008554 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008555}
8556
John McCalldadc5752010-08-24 06:29:42 +00008557ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008558 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008559 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008560 ExprValueKind VK = VK_RValue;
8561 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008562 QualType resultType;
8563 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008564 case UO_PreInc:
8565 case UO_PreDec:
8566 case UO_PostInc:
8567 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008568 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008569 Opc == UO_PreInc ||
8570 Opc == UO_PostInc,
8571 Opc == UO_PreInc ||
8572 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008573 break;
John McCalle3027922010-08-25 11:45:40 +00008574 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008575 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008576 break;
John McCall31996342011-04-07 08:22:57 +00008577 case UO_Deref: {
8578 ExprResult resolved = CheckPlaceholderExpr(Input, OpLoc);
8579 if (!resolved.isUsable()) return ExprError();
8580 Input = resolved.take();
Douglas Gregorb92a1562010-02-03 00:27:59 +00008581 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008582 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008583 break;
John McCall31996342011-04-07 08:22:57 +00008584 }
John McCalle3027922010-08-25 11:45:40 +00008585 case UO_Plus:
8586 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008587 UsualUnaryConversions(Input);
8588 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008589 if (resultType->isDependentType())
8590 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008591 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8592 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008593 break;
8594 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8595 resultType->isEnumeralType())
8596 break;
8597 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008598 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008599 resultType->isPointerType())
8600 break;
John McCall36226622010-10-12 02:09:17 +00008601 else if (resultType->isPlaceholderType()) {
8602 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8603 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008604 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008605 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008606
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008607 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8608 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008609 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008610 UsualUnaryConversions(Input);
8611 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008612 if (resultType->isDependentType())
8613 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008614 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8615 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8616 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008617 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008618 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008619 else if (resultType->hasIntegerRepresentation())
8620 break;
8621 else if (resultType->isPlaceholderType()) {
8622 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8623 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008624 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008625 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008626 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8627 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008628 }
Steve Naroff35d85152007-05-07 00:24:15 +00008629 break;
John McCalle3027922010-08-25 11:45:40 +00008630 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008631 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008632 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008633 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008634 if (resultType->isDependentType())
8635 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008636 if (resultType->isScalarType()) {
8637 // C99 6.5.3.3p1: ok, fallthrough;
8638 if (Context.getLangOptions().CPlusPlus) {
8639 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8640 // operand contextually converted to bool.
8641 ImpCastExprToType(Input, Context.BoolTy,
8642 ScalarTypeToBooleanCastKind(resultType));
8643 }
John McCall36226622010-10-12 02:09:17 +00008644 } else if (resultType->isPlaceholderType()) {
8645 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8646 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008647 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008648 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008649 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8650 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008651 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008652
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008653 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008654 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008655 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008656 break;
John McCalle3027922010-08-25 11:45:40 +00008657 case UO_Real:
8658 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008659 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008660 // _Real and _Imag map ordinary l-values into ordinary l-values.
8661 if (Input->getValueKind() != VK_RValue &&
8662 Input->getObjectKind() == OK_Ordinary)
8663 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008664 break;
John McCalle3027922010-08-25 11:45:40 +00008665 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008666 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008667 VK = Input->getValueKind();
8668 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008669 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008670 }
8671 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008672 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008673
John McCall7decc9e2010-11-18 06:31:45 +00008674 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8675 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008676}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008677
John McCalldadc5752010-08-24 06:29:42 +00008678ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008679 UnaryOperatorKind Opc,
8680 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008681 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008682 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008683 // Find all of the overloaded operators visible from this
8684 // point. We perform both an operator-name lookup from the local
8685 // scope and an argument-dependent lookup based on the types of
8686 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008687 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008688 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008689 if (S && OverOp != OO_None)
8690 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8691 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008692
John McCallb268a282010-08-23 23:25:46 +00008693 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008694 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008695
John McCallb268a282010-08-23 23:25:46 +00008696 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008697}
8698
Douglas Gregor5287f092009-11-05 00:51:44 +00008699// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008700ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008701 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008702 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008703}
8704
Steve Naroff66356bd2007-09-16 14:56:35 +00008705/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008706ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008707 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008708 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008709 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008710 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008711 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008712}
8713
John McCalldadc5752010-08-24 06:29:42 +00008714ExprResult
John McCallb268a282010-08-23 23:25:46 +00008715Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008716 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008717 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8718 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8719
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008720 bool isFileScope
8721 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008722 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008723 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008724
Chris Lattner366727f2007-07-24 16:58:17 +00008725 // FIXME: there are a variety of strange constraints to enforce here, for
8726 // example, it is not possible to goto into a stmt expression apparently.
8727 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008728
Chris Lattner366727f2007-07-24 16:58:17 +00008729 // If there are sub stmts in the compound stmt, take the type of the last one
8730 // as the type of the stmtexpr.
8731 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008732 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008733 if (!Compound->body_empty()) {
8734 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008735 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008736 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008737 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8738 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008739 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008740 }
8741 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008742 // Do function/array conversion on the last expression, but not
8743 // lvalue-to-rvalue. However, initialize an unqualified type.
8744 DefaultFunctionArrayConversion(LastExpr);
8745 Ty = LastExpr->getType().getUnqualifiedType();
8746
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008747 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8748 ExprResult Res = PerformCopyInitialization(
8749 InitializedEntity::InitializeResult(LPLoc,
8750 Ty,
8751 false),
8752 SourceLocation(),
8753 Owned(LastExpr));
8754 if (Res.isInvalid())
8755 return ExprError();
8756 if ((LastExpr = Res.takeAs<Expr>())) {
8757 if (!LastLabelStmt)
8758 Compound->setLastStmt(LastExpr);
8759 else
8760 LastLabelStmt->setSubStmt(LastExpr);
8761 StmtExprMayBindToTemp = true;
8762 }
8763 }
8764 }
Chris Lattner944d3062008-07-26 19:51:01 +00008765 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008766
Eli Friedmanba961a92009-03-23 00:24:07 +00008767 // FIXME: Check that expression type is complete/non-abstract; statement
8768 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008769 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8770 if (StmtExprMayBindToTemp)
8771 return MaybeBindToTemporary(ResStmtExpr);
8772 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008773}
Steve Naroff78864672007-08-01 22:05:33 +00008774
John McCalldadc5752010-08-24 06:29:42 +00008775ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008776 TypeSourceInfo *TInfo,
8777 OffsetOfComponent *CompPtr,
8778 unsigned NumComponents,
8779 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008780 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008781 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008782 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008783
Chris Lattnerf17bd422007-08-30 17:45:32 +00008784 // We must have at least one component that refers to the type, and the first
8785 // one is known to be a field designator. Verify that the ArgTy represents
8786 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008787 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008788 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8789 << ArgTy << TypeRange);
8790
8791 // Type must be complete per C99 7.17p3 because a declaring a variable
8792 // with an incomplete type would be ill-formed.
8793 if (!Dependent
8794 && RequireCompleteType(BuiltinLoc, ArgTy,
8795 PDiag(diag::err_offsetof_incomplete_type)
8796 << TypeRange))
8797 return ExprError();
8798
Chris Lattner78502cf2007-08-31 21:49:13 +00008799 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8800 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008801 // FIXME: This diagnostic isn't actually visible because the location is in
8802 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008803 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008804 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8805 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008806
8807 bool DidWarnAboutNonPOD = false;
8808 QualType CurrentType = ArgTy;
8809 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8810 llvm::SmallVector<OffsetOfNode, 4> Comps;
8811 llvm::SmallVector<Expr*, 4> Exprs;
8812 for (unsigned i = 0; i != NumComponents; ++i) {
8813 const OffsetOfComponent &OC = CompPtr[i];
8814 if (OC.isBrackets) {
8815 // Offset of an array sub-field. TODO: Should we allow vector elements?
8816 if (!CurrentType->isDependentType()) {
8817 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8818 if(!AT)
8819 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8820 << CurrentType);
8821 CurrentType = AT->getElementType();
8822 } else
8823 CurrentType = Context.DependentTy;
8824
8825 // The expression must be an integral expression.
8826 // FIXME: An integral constant expression?
8827 Expr *Idx = static_cast<Expr*>(OC.U.E);
8828 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8829 !Idx->getType()->isIntegerType())
8830 return ExprError(Diag(Idx->getLocStart(),
8831 diag::err_typecheck_subscript_not_integer)
8832 << Idx->getSourceRange());
8833
8834 // Record this array index.
8835 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8836 Exprs.push_back(Idx);
8837 continue;
8838 }
8839
8840 // Offset of a field.
8841 if (CurrentType->isDependentType()) {
8842 // We have the offset of a field, but we can't look into the dependent
8843 // type. Just record the identifier of the field.
8844 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8845 CurrentType = Context.DependentTy;
8846 continue;
8847 }
8848
8849 // We need to have a complete type to look into.
8850 if (RequireCompleteType(OC.LocStart, CurrentType,
8851 diag::err_offsetof_incomplete_type))
8852 return ExprError();
8853
8854 // Look for the designated field.
8855 const RecordType *RC = CurrentType->getAs<RecordType>();
8856 if (!RC)
8857 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8858 << CurrentType);
8859 RecordDecl *RD = RC->getDecl();
8860
8861 // C++ [lib.support.types]p5:
8862 // The macro offsetof accepts a restricted set of type arguments in this
8863 // International Standard. type shall be a POD structure or a POD union
8864 // (clause 9).
8865 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8866 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008867 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008868 PDiag(diag::warn_offsetof_non_pod_type)
8869 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8870 << CurrentType))
8871 DidWarnAboutNonPOD = true;
8872 }
8873
8874 // Look for the field.
8875 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8876 LookupQualifiedName(R, RD);
8877 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008878 IndirectFieldDecl *IndirectMemberDecl = 0;
8879 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008880 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008881 MemberDecl = IndirectMemberDecl->getAnonField();
8882 }
8883
Douglas Gregor882211c2010-04-28 22:16:22 +00008884 if (!MemberDecl)
8885 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8886 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8887 OC.LocEnd));
8888
Douglas Gregor10982ea2010-04-28 22:36:06 +00008889 // C99 7.17p3:
8890 // (If the specified member is a bit-field, the behavior is undefined.)
8891 //
8892 // We diagnose this as an error.
8893 if (MemberDecl->getBitWidth()) {
8894 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8895 << MemberDecl->getDeclName()
8896 << SourceRange(BuiltinLoc, RParenLoc);
8897 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8898 return ExprError();
8899 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008900
8901 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008902 if (IndirectMemberDecl)
8903 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008904
Douglas Gregord1702062010-04-29 00:18:15 +00008905 // If the member was found in a base class, introduce OffsetOfNodes for
8906 // the base class indirections.
8907 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8908 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008909 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008910 CXXBasePath &Path = Paths.front();
8911 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8912 B != BEnd; ++B)
8913 Comps.push_back(OffsetOfNode(B->Base));
8914 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008915
Francois Pichet783dd6e2010-11-21 06:08:52 +00008916 if (IndirectMemberDecl) {
8917 for (IndirectFieldDecl::chain_iterator FI =
8918 IndirectMemberDecl->chain_begin(),
8919 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8920 assert(isa<FieldDecl>(*FI));
8921 Comps.push_back(OffsetOfNode(OC.LocStart,
8922 cast<FieldDecl>(*FI), OC.LocEnd));
8923 }
8924 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008925 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008926
Douglas Gregor882211c2010-04-28 22:16:22 +00008927 CurrentType = MemberDecl->getType().getNonReferenceType();
8928 }
8929
8930 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8931 TInfo, Comps.data(), Comps.size(),
8932 Exprs.data(), Exprs.size(), RParenLoc));
8933}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008934
John McCalldadc5752010-08-24 06:29:42 +00008935ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008936 SourceLocation BuiltinLoc,
8937 SourceLocation TypeLoc,
8938 ParsedType argty,
8939 OffsetOfComponent *CompPtr,
8940 unsigned NumComponents,
8941 SourceLocation RPLoc) {
8942
Douglas Gregor882211c2010-04-28 22:16:22 +00008943 TypeSourceInfo *ArgTInfo;
8944 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8945 if (ArgTy.isNull())
8946 return ExprError();
8947
Eli Friedman06dcfd92010-08-05 10:15:45 +00008948 if (!ArgTInfo)
8949 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8950
8951 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8952 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008953}
8954
8955
John McCalldadc5752010-08-24 06:29:42 +00008956ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008957 Expr *CondExpr,
8958 Expr *LHSExpr, Expr *RHSExpr,
8959 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008960 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8961
John McCall7decc9e2010-11-18 06:31:45 +00008962 ExprValueKind VK = VK_RValue;
8963 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008964 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008965 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008966 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008967 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008968 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008969 } else {
8970 // The conditional expression is required to be a constant expression.
8971 llvm::APSInt condEval(32);
8972 SourceLocation ExpLoc;
8973 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008974 return ExprError(Diag(ExpLoc,
8975 diag::err_typecheck_choose_expr_requires_constant)
8976 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008977
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008978 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008979 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8980
8981 resType = ActiveExpr->getType();
8982 ValueDependent = ActiveExpr->isValueDependent();
8983 VK = ActiveExpr->getValueKind();
8984 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008985 }
8986
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008987 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008988 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008989 resType->isDependentType(),
8990 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008991}
8992
Steve Naroffc540d662008-09-03 18:15:37 +00008993//===----------------------------------------------------------------------===//
8994// Clang Extensions.
8995//===----------------------------------------------------------------------===//
8996
8997/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008998void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008999 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9000 PushBlockScope(BlockScope, Block);
9001 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009002 if (BlockScope)
9003 PushDeclContext(BlockScope, Block);
9004 else
9005 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009006}
9007
Mike Stump82f071f2009-02-04 22:31:32 +00009008void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009009 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009010 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009011 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009012
John McCall8cb7bdf2010-06-04 23:28:52 +00009013 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009014 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009015
John McCall3882ace2011-01-05 12:14:39 +00009016 // GetTypeForDeclarator always produces a function type for a block
9017 // literal signature. Furthermore, it is always a FunctionProtoType
9018 // unless the function was written with a typedef.
9019 assert(T->isFunctionType() &&
9020 "GetTypeForDeclarator made a non-function block signature");
9021
9022 // Look for an explicit signature in that function type.
9023 FunctionProtoTypeLoc ExplicitSignature;
9024
9025 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9026 if (isa<FunctionProtoTypeLoc>(tmp)) {
9027 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9028
9029 // Check whether that explicit signature was synthesized by
9030 // GetTypeForDeclarator. If so, don't save that as part of the
9031 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009032 if (ExplicitSignature.getLocalRangeBegin() ==
9033 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009034 // This would be much cheaper if we stored TypeLocs instead of
9035 // TypeSourceInfos.
9036 TypeLoc Result = ExplicitSignature.getResultLoc();
9037 unsigned Size = Result.getFullDataSize();
9038 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9039 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9040
9041 ExplicitSignature = FunctionProtoTypeLoc();
9042 }
John McCalla3ccba02010-06-04 11:21:44 +00009043 }
Mike Stump11289f42009-09-09 15:08:12 +00009044
John McCall3882ace2011-01-05 12:14:39 +00009045 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9046 CurBlock->FunctionType = T;
9047
9048 const FunctionType *Fn = T->getAs<FunctionType>();
9049 QualType RetTy = Fn->getResultType();
9050 bool isVariadic =
9051 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9052
John McCall8e346702010-06-04 19:02:56 +00009053 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009054
John McCalla3ccba02010-06-04 11:21:44 +00009055 // Don't allow returning a objc interface by value.
9056 if (RetTy->isObjCObjectType()) {
9057 Diag(ParamInfo.getSourceRange().getBegin(),
9058 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9059 return;
9060 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009061
John McCalla3ccba02010-06-04 11:21:44 +00009062 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009063 // return type. TODO: what should we do with declarators like:
9064 // ^ * { ... }
9065 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009066 if (RetTy != Context.DependentTy)
9067 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009068
John McCalla3ccba02010-06-04 11:21:44 +00009069 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009070 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009071 if (ExplicitSignature) {
9072 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9073 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009074 if (Param->getIdentifier() == 0 &&
9075 !Param->isImplicit() &&
9076 !Param->isInvalidDecl() &&
9077 !getLangOptions().CPlusPlus)
9078 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009079 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009080 }
John McCalla3ccba02010-06-04 11:21:44 +00009081
9082 // Fake up parameter variables if we have a typedef, like
9083 // ^ fntype { ... }
9084 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9085 for (FunctionProtoType::arg_type_iterator
9086 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9087 ParmVarDecl *Param =
9088 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9089 ParamInfo.getSourceRange().getBegin(),
9090 *I);
John McCall8e346702010-06-04 19:02:56 +00009091 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009092 }
Steve Naroffc540d662008-09-03 18:15:37 +00009093 }
John McCalla3ccba02010-06-04 11:21:44 +00009094
John McCall8e346702010-06-04 19:02:56 +00009095 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009096 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009097 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009098 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9099 CurBlock->TheDecl->param_end(),
9100 /*CheckParameterNames=*/false);
9101 }
9102
John McCalla3ccba02010-06-04 11:21:44 +00009103 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009104 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009105
John McCall8e346702010-06-04 19:02:56 +00009106 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009107 Diag(ParamInfo.getAttributes()->getLoc(),
9108 diag::warn_attribute_sentinel_not_variadic) << 1;
9109 // FIXME: remove the attribute.
9110 }
9111
9112 // Put the parameter variables in scope. We can bail out immediately
9113 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009114 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009115 return;
9116
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009117 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009118 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9119 (*AI)->setOwningFunction(CurBlock->TheDecl);
9120
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009121 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009122 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009123 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009124
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009125 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009126 }
John McCallf7b2fb52010-01-22 00:28:27 +00009127 }
Steve Naroffc540d662008-09-03 18:15:37 +00009128}
9129
9130/// ActOnBlockError - If there is an error parsing a block, this callback
9131/// is invoked to pop the information about the block from the action impl.
9132void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009133 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009134 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009135 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009136}
9137
9138/// ActOnBlockStmtExpr - This is called when the body of a block statement
9139/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009140ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009141 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009142 // If blocks are disabled, emit an error.
9143 if (!LangOpts.Blocks)
9144 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009145
Douglas Gregor9a28e842010-03-01 23:15:13 +00009146 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009147
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009148 PopDeclContext();
9149
Steve Naroffc540d662008-09-03 18:15:37 +00009150 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009151 if (!BSI->ReturnType.isNull())
9152 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009153
Mike Stump3bf1ab42009-07-28 22:04:01 +00009154 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009155 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009156
John McCallc63de662011-02-02 13:00:07 +00009157 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009158 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9159 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009160
John McCall8e346702010-06-04 19:02:56 +00009161 // If the user wrote a function type in some form, try to use that.
9162 if (!BSI->FunctionType.isNull()) {
9163 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9164
9165 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9166 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9167
9168 // Turn protoless block types into nullary block types.
9169 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009170 FunctionProtoType::ExtProtoInfo EPI;
9171 EPI.ExtInfo = Ext;
9172 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009173
9174 // Otherwise, if we don't need to change anything about the function type,
9175 // preserve its sugar structure.
9176 } else if (FTy->getResultType() == RetTy &&
9177 (!NoReturn || FTy->getNoReturnAttr())) {
9178 BlockTy = BSI->FunctionType;
9179
9180 // Otherwise, make the minimal modifications to the function type.
9181 } else {
9182 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9184 EPI.TypeQuals = 0; // FIXME: silently?
9185 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009186 BlockTy = Context.getFunctionType(RetTy,
9187 FPT->arg_type_begin(),
9188 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009189 EPI);
John McCall8e346702010-06-04 19:02:56 +00009190 }
9191
9192 // If we don't have a function type, just build one from nothing.
9193 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009194 FunctionProtoType::ExtProtoInfo EPI;
9195 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
9196 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009197 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009198
John McCall8e346702010-06-04 19:02:56 +00009199 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9200 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009201 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009202
Chris Lattner45542ea2009-04-19 05:28:12 +00009203 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009204 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009205 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009206
Chris Lattner60f84492011-02-17 23:58:47 +00009207 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009208
John McCallc63de662011-02-02 13:00:07 +00009209 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009210
Ted Kremenek1767a272011-02-23 01:51:48 +00009211 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9212 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009213 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009214}
9215
John McCalldadc5752010-08-24 06:29:42 +00009216ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009217 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009218 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009219 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009220 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009221 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009222}
9223
John McCalldadc5752010-08-24 06:29:42 +00009224ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009225 Expr *E, TypeSourceInfo *TInfo,
9226 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009227 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009228
Eli Friedman121ba0c2008-08-09 23:32:40 +00009229 // Get the va_list type
9230 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009231 if (VaListType->isArrayType()) {
9232 // Deal with implicit array decay; for example, on x86-64,
9233 // va_list is an array, but it's supposed to decay to
9234 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009235 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009236 // Make sure the input expression also decays appropriately.
9237 UsualUnaryConversions(E);
9238 } else {
9239 // Otherwise, the va_list argument must be an l-value because
9240 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009241 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009242 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009243 return ExprError();
9244 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009245
Douglas Gregorad3150c2009-05-19 23:10:31 +00009246 if (!E->isTypeDependent() &&
9247 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009248 return ExprError(Diag(E->getLocStart(),
9249 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009250 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009251 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009252
Eli Friedmanba961a92009-03-23 00:24:07 +00009253 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009254 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009255
Abramo Bagnara27db2392010-08-10 10:06:15 +00009256 QualType T = TInfo->getType().getNonLValueExprType(Context);
9257 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009258}
9259
John McCalldadc5752010-08-24 06:29:42 +00009260ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009261 // The type of __null will be int or long, depending on the size of
9262 // pointers on the target.
9263 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009264 unsigned pw = Context.Target.getPointerWidth(0);
9265 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009266 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009267 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009268 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009269 else if (pw == Context.Target.getLongLongWidth())
9270 Ty = Context.LongLongTy;
9271 else {
9272 assert(!"I don't know size of pointer!");
9273 Ty = Context.IntTy;
9274 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009275
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009276 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009277}
9278
Alexis Huntc46382e2010-04-28 23:02:27 +00009279static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009280 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009281 if (!SemaRef.getLangOptions().ObjC1)
9282 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009283
Anders Carlssonace5d072009-11-10 04:46:30 +00009284 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9285 if (!PT)
9286 return;
9287
9288 // Check if the destination is of type 'id'.
9289 if (!PT->isObjCIdType()) {
9290 // Check if the destination is the 'NSString' interface.
9291 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9292 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9293 return;
9294 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009295
Anders Carlssonace5d072009-11-10 04:46:30 +00009296 // Strip off any parens and casts.
9297 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9298 if (!SL || SL->isWide())
9299 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009300
Douglas Gregora771f462010-03-31 17:46:05 +00009301 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009302}
9303
Chris Lattner9bad62c2008-01-04 18:04:52 +00009304bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9305 SourceLocation Loc,
9306 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009307 Expr *SrcExpr, AssignmentAction Action,
9308 bool *Complained) {
9309 if (Complained)
9310 *Complained = false;
9311
Chris Lattner9bad62c2008-01-04 18:04:52 +00009312 // Decode the result (notice that AST's are still created for extensions).
9313 bool isInvalid = false;
9314 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009315 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009316
Chris Lattner9bad62c2008-01-04 18:04:52 +00009317 switch (ConvTy) {
9318 default: assert(0 && "Unknown conversion type");
9319 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009320 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009321 DiagKind = diag::ext_typecheck_convert_pointer_int;
9322 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009323 case IntToPointer:
9324 DiagKind = diag::ext_typecheck_convert_int_pointer;
9325 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009326 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009327 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009328 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9329 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009330 case IncompatiblePointerSign:
9331 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9332 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009333 case FunctionVoidPointer:
9334 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9335 break;
John McCall4fff8f62011-02-01 00:10:29 +00009336 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009337 // Perform array-to-pointer decay if necessary.
9338 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9339
John McCall4fff8f62011-02-01 00:10:29 +00009340 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9341 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9342 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9343 DiagKind = diag::err_typecheck_incompatible_address_space;
9344 break;
9345 }
9346
9347 llvm_unreachable("unknown error case for discarding qualifiers!");
9348 // fallthrough
9349 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009350 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009351 // If the qualifiers lost were because we were applying the
9352 // (deprecated) C++ conversion from a string literal to a char*
9353 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9354 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009355 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009356 // bit of refactoring (so that the second argument is an
9357 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009358 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009359 // C++ semantics.
9360 if (getLangOptions().CPlusPlus &&
9361 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9362 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009363 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9364 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009365 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009366 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009367 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009368 case IntToBlockPointer:
9369 DiagKind = diag::err_int_to_block_pointer;
9370 break;
9371 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009372 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009373 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009374 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009375 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009376 // it can give a more specific diagnostic.
9377 DiagKind = diag::warn_incompatible_qualified_id;
9378 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009379 case IncompatibleVectors:
9380 DiagKind = diag::warn_incompatible_vectors;
9381 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009382 case Incompatible:
9383 DiagKind = diag::err_typecheck_convert_incompatible;
9384 isInvalid = true;
9385 break;
9386 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009387
Douglas Gregorc68e1402010-04-09 00:35:39 +00009388 QualType FirstType, SecondType;
9389 switch (Action) {
9390 case AA_Assigning:
9391 case AA_Initializing:
9392 // The destination type comes first.
9393 FirstType = DstType;
9394 SecondType = SrcType;
9395 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009396
Douglas Gregorc68e1402010-04-09 00:35:39 +00009397 case AA_Returning:
9398 case AA_Passing:
9399 case AA_Converting:
9400 case AA_Sending:
9401 case AA_Casting:
9402 // The source type comes first.
9403 FirstType = SrcType;
9404 SecondType = DstType;
9405 break;
9406 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009407
Douglas Gregorc68e1402010-04-09 00:35:39 +00009408 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009409 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009410 if (Complained)
9411 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009412 return isInvalid;
9413}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009414
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009415bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009416 llvm::APSInt ICEResult;
9417 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9418 if (Result)
9419 *Result = ICEResult;
9420 return false;
9421 }
9422
Anders Carlssone54e8a12008-11-30 19:50:32 +00009423 Expr::EvalResult EvalResult;
9424
Mike Stump4e1f26a2009-02-19 03:04:26 +00009425 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009426 EvalResult.HasSideEffects) {
9427 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9428
9429 if (EvalResult.Diag) {
9430 // We only show the note if it's not the usual "invalid subexpression"
9431 // or if it's actually in a subexpression.
9432 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9433 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9434 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9435 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009436
Anders Carlssone54e8a12008-11-30 19:50:32 +00009437 return true;
9438 }
9439
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009440 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9441 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009442
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009443 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009444 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9445 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009446 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009447
Anders Carlssone54e8a12008-11-30 19:50:32 +00009448 if (Result)
9449 *Result = EvalResult.Val.getInt();
9450 return false;
9451}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009452
Douglas Gregorff790f12009-11-26 00:44:06 +00009453void
Mike Stump11289f42009-09-09 15:08:12 +00009454Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009455 ExprEvalContexts.push_back(
9456 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009457}
9458
Mike Stump11289f42009-09-09 15:08:12 +00009459void
Douglas Gregorff790f12009-11-26 00:44:06 +00009460Sema::PopExpressionEvaluationContext() {
9461 // Pop the current expression evaluation context off the stack.
9462 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9463 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009464
Douglas Gregorfab31f42009-12-12 07:57:52 +00009465 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9466 if (Rec.PotentiallyReferenced) {
9467 // Mark any remaining declarations in the current position of the stack
9468 // as "referenced". If they were not meant to be referenced, semantic
9469 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009470 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009471 I = Rec.PotentiallyReferenced->begin(),
9472 IEnd = Rec.PotentiallyReferenced->end();
9473 I != IEnd; ++I)
9474 MarkDeclarationReferenced(I->first, I->second);
9475 }
9476
9477 if (Rec.PotentiallyDiagnosed) {
9478 // Emit any pending diagnostics.
9479 for (PotentiallyEmittedDiagnostics::iterator
9480 I = Rec.PotentiallyDiagnosed->begin(),
9481 IEnd = Rec.PotentiallyDiagnosed->end();
9482 I != IEnd; ++I)
9483 Diag(I->first, I->second);
9484 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009485 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009486
9487 // When are coming out of an unevaluated context, clear out any
9488 // temporaries that we may have created as part of the evaluation of
9489 // the expression in that context: they aren't relevant because they
9490 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009491 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009492 ExprTemporaries.size() > Rec.NumTemporaries)
9493 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9494 ExprTemporaries.end());
9495
9496 // Destroy the popped expression evaluation record.
9497 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009498}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009499
9500/// \brief Note that the given declaration was referenced in the source code.
9501///
9502/// This routine should be invoke whenever a given declaration is referenced
9503/// in the source code, and where that reference occurred. If this declaration
9504/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9505/// C99 6.9p3), then the declaration will be marked as used.
9506///
9507/// \param Loc the location where the declaration was referenced.
9508///
9509/// \param D the declaration that has been referenced by the source code.
9510void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9511 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009512
Douglas Gregorebada0772010-06-17 23:14:26 +00009513 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009514 return;
Mike Stump11289f42009-09-09 15:08:12 +00009515
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009516 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9517 // template or not. The reason for this is that unevaluated expressions
9518 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9519 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009520 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009521 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009522 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009523 return;
9524 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009525
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009526 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9527 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009528
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009529 // Do not mark anything as "used" within a dependent context; wait for
9530 // an instantiation.
9531 if (CurContext->isDependentContext())
9532 return;
Mike Stump11289f42009-09-09 15:08:12 +00009533
Douglas Gregorff790f12009-11-26 00:44:06 +00009534 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009535 case Unevaluated:
9536 // We are in an expression that is not potentially evaluated; do nothing.
9537 return;
Mike Stump11289f42009-09-09 15:08:12 +00009538
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009539 case PotentiallyEvaluated:
9540 // We are in a potentially-evaluated expression, so this declaration is
9541 // "used"; handle this below.
9542 break;
Mike Stump11289f42009-09-09 15:08:12 +00009543
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009544 case PotentiallyPotentiallyEvaluated:
9545 // We are in an expression that may be potentially evaluated; queue this
9546 // declaration reference until we know whether the expression is
9547 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009548 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009549 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009550
9551 case PotentiallyEvaluatedIfUsed:
9552 // Referenced declarations will only be used if the construct in the
9553 // containing expression is used.
9554 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009555 }
Mike Stump11289f42009-09-09 15:08:12 +00009556
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009557 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009559 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009560 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009561 if (Constructor->getParent()->hasTrivialConstructor())
9562 return;
9563 if (!Constructor->isUsed(false))
9564 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009565 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009566 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009567 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009568 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9569 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009570
Douglas Gregor88d292c2010-05-13 16:44:06 +00009571 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009572 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009573 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009574 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009575 if (Destructor->isVirtual())
9576 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009577 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9578 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9579 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009580 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009581 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009582 } else if (MethodDecl->isVirtual())
9583 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009584 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009585 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009586 // Recursive functions should be marked when used from another function.
9587 if (CurContext == Function) return;
9588
Mike Stump11289f42009-09-09 15:08:12 +00009589 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009590 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009591 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009592 bool AlreadyInstantiated = false;
9593 if (FunctionTemplateSpecializationInfo *SpecInfo
9594 = Function->getTemplateSpecializationInfo()) {
9595 if (SpecInfo->getPointOfInstantiation().isInvalid())
9596 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009597 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009598 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009599 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009600 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009601 = Function->getMemberSpecializationInfo()) {
9602 if (MSInfo->getPointOfInstantiation().isInvalid())
9603 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009604 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009605 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009606 AlreadyInstantiated = true;
9607 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009608
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009609 if (!AlreadyInstantiated) {
9610 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9611 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9612 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9613 Loc));
9614 else
Chandler Carruth54080172010-08-25 08:44:16 +00009615 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009616 }
John McCall83779672011-02-19 02:53:41 +00009617 } else {
9618 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009619 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9620 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009621 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009622 MarkDeclarationReferenced(Loc, *i);
9623 }
John McCall83779672011-02-19 02:53:41 +00009624 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009625
John McCall83779672011-02-19 02:53:41 +00009626 // Keep track of used but undefined functions.
9627 if (!Function->isPure() && !Function->hasBody() &&
9628 Function->getLinkage() != ExternalLinkage) {
9629 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9630 if (old.isInvalid()) old = Loc;
9631 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009632
John McCall83779672011-02-19 02:53:41 +00009633 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009634 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009635 }
Mike Stump11289f42009-09-09 15:08:12 +00009636
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009637 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009638 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009639 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009640 Var->getInstantiatedFromStaticDataMember()) {
9641 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9642 assert(MSInfo && "Missing member specialization information?");
9643 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9644 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9645 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009646 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009647 }
9648 }
Mike Stump11289f42009-09-09 15:08:12 +00009649
John McCall15dd4042011-02-21 19:25:48 +00009650 // Keep track of used but undefined variables. We make a hole in
9651 // the warning for static const data members with in-line
9652 // initializers.
John McCall83779672011-02-19 02:53:41 +00009653 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009654 && Var->getLinkage() != ExternalLinkage
9655 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009656 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9657 if (old.isInvalid()) old = Loc;
9658 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009659
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009660 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009661 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009662 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009663}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009664
Douglas Gregor5597ab42010-05-07 23:12:07 +00009665namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009666 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009667 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009668 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009669 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9670 Sema &S;
9671 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009672
Douglas Gregor5597ab42010-05-07 23:12:07 +00009673 public:
9674 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009675
Douglas Gregor5597ab42010-05-07 23:12:07 +00009676 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009677
9678 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9679 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009680 };
9681}
9682
Chandler Carruthaf80f662010-06-09 08:17:30 +00009683bool MarkReferencedDecls::TraverseTemplateArgument(
9684 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009685 if (Arg.getKind() == TemplateArgument::Declaration) {
9686 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9687 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009688
9689 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009690}
9691
Chandler Carruthaf80f662010-06-09 08:17:30 +00009692bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009693 if (ClassTemplateSpecializationDecl *Spec
9694 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9695 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009696 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009697 }
9698
Chandler Carruthc65667c2010-06-10 10:31:57 +00009699 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009700}
9701
9702void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9703 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009704 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009705}
9706
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009707namespace {
9708 /// \brief Helper class that marks all of the declarations referenced by
9709 /// potentially-evaluated subexpressions as "referenced".
9710 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9711 Sema &S;
9712
9713 public:
9714 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9715
9716 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9717
9718 void VisitDeclRefExpr(DeclRefExpr *E) {
9719 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9720 }
9721
9722 void VisitMemberExpr(MemberExpr *E) {
9723 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009724 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009725 }
9726
9727 void VisitCXXNewExpr(CXXNewExpr *E) {
9728 if (E->getConstructor())
9729 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9730 if (E->getOperatorNew())
9731 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9732 if (E->getOperatorDelete())
9733 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009734 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009735 }
9736
9737 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9738 if (E->getOperatorDelete())
9739 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009740 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9741 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9742 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9743 S.MarkDeclarationReferenced(E->getLocStart(),
9744 S.LookupDestructor(Record));
9745 }
9746
Douglas Gregor32b3de52010-09-11 23:32:50 +00009747 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009748 }
9749
9750 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9751 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009752 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009753 }
9754
9755 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9756 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9757 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009758
9759 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9760 Visit(E->getExpr());
9761 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009762 };
9763}
9764
9765/// \brief Mark any declarations that appear within this expression or any
9766/// potentially-evaluated subexpressions as "referenced".
9767void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9768 EvaluatedExprMarker(*this).Visit(E);
9769}
9770
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009771/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9772/// of the program being compiled.
9773///
9774/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009775/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009776/// possibility that the code will actually be executable. Code in sizeof()
9777/// expressions, code used only during overload resolution, etc., are not
9778/// potentially evaluated. This routine will suppress such diagnostics or,
9779/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009780/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009781/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009782///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009783/// This routine should be used for all diagnostics that describe the run-time
9784/// behavior of a program, such as passing a non-POD value through an ellipsis.
9785/// Failure to do so will likely result in spurious diagnostics or failures
9786/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009787bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009788 const PartialDiagnostic &PD) {
9789 switch (ExprEvalContexts.back().Context ) {
9790 case Unevaluated:
9791 // The argument will never be evaluated, so don't complain.
9792 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009793
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009794 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009795 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009796 if (stmt && getCurFunctionOrMethodDecl()) {
9797 FunctionScopes.back()->PossiblyUnreachableDiags.
9798 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9799 }
9800 else
9801 Diag(Loc, PD);
9802
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009803 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009804
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009805 case PotentiallyPotentiallyEvaluated:
9806 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9807 break;
9808 }
9809
9810 return false;
9811}
9812
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009813bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9814 CallExpr *CE, FunctionDecl *FD) {
9815 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9816 return false;
9817
9818 PartialDiagnostic Note =
9819 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9820 << FD->getDeclName() : PDiag();
9821 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009822
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009823 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009824 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009825 PDiag(diag::err_call_function_incomplete_return)
9826 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009827 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009828 << CE->getSourceRange(),
9829 std::make_pair(NoteLoc, Note)))
9830 return true;
9831
9832 return false;
9833}
9834
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009835// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009836// will prevent this condition from triggering, which is what we want.
9837void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9838 SourceLocation Loc;
9839
John McCall0506e4a2009-11-11 02:41:58 +00009840 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009841 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009842
John McCalld5707ab2009-10-12 21:59:07 +00009843 if (isa<BinaryOperator>(E)) {
9844 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009845 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009846 return;
9847
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009848 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9849
John McCallb0e419e2009-11-12 00:06:05 +00009850 // Greylist some idioms by putting them into a warning subcategory.
9851 if (ObjCMessageExpr *ME
9852 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9853 Selector Sel = ME->getSelector();
9854
John McCallb0e419e2009-11-12 00:06:05 +00009855 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009856 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009857 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9858
9859 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009860 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009861 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9862 }
John McCall0506e4a2009-11-11 02:41:58 +00009863
John McCalld5707ab2009-10-12 21:59:07 +00009864 Loc = Op->getOperatorLoc();
9865 } else if (isa<CXXOperatorCallExpr>(E)) {
9866 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009867 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009868 return;
9869
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009870 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009871 Loc = Op->getOperatorLoc();
9872 } else {
9873 // Not an assignment.
9874 return;
9875 }
9876
John McCalld5707ab2009-10-12 21:59:07 +00009877 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009878 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009879
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009880 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009881
9882 if (IsOrAssign)
9883 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9884 << FixItHint::CreateReplacement(Loc, "!=");
9885 else
9886 Diag(Loc, diag::note_condition_assign_to_comparison)
9887 << FixItHint::CreateReplacement(Loc, "==");
9888
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009889 Diag(Loc, diag::note_condition_assign_silence)
9890 << FixItHint::CreateInsertion(Open, "(")
9891 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009892}
9893
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009894/// \brief Redundant parentheses over an equality comparison can indicate
9895/// that the user intended an assignment used as condition.
9896void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009897 // Don't warn if the parens came from a macro.
9898 SourceLocation parenLoc = parenE->getLocStart();
9899 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9900 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009901 // Don't warn for dependent expressions.
9902 if (parenE->isTypeDependent())
9903 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009904
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009905 Expr *E = parenE->IgnoreParens();
9906
9907 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009908 if (opE->getOpcode() == BO_EQ &&
9909 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9910 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009911 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009912
Ted Kremenekae022092011-02-02 02:20:30 +00009913 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9914 Diag(Loc, diag::note_equality_comparison_to_assign)
9915 << FixItHint::CreateReplacement(Loc, "=");
9916 Diag(Loc, diag::note_equality_comparison_silence)
9917 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9918 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009919 }
9920}
9921
John McCalld5707ab2009-10-12 21:59:07 +00009922bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9923 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009924 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9925 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009926
9927 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009928 if (E->isBoundMemberFunction(Context))
9929 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9930 << E->getSourceRange();
9931
John McCall34376a62010-12-04 03:47:34 +00009932 if (getLangOptions().CPlusPlus)
9933 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9934
9935 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009936
9937 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009938 if (!T->isScalarType()) // C99 6.8.4.1p1
9939 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9940 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009941 }
9942
9943 return false;
9944}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009945
John McCalldadc5752010-08-24 06:29:42 +00009946ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9947 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009948 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009949 return ExprError();
9950
Douglas Gregorb412e172010-07-25 18:17:45 +00009951 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009952 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009953
9954 return Owned(Sub);
9955}
John McCall36e7fe32010-10-12 00:20:44 +00009956
John McCall31996342011-04-07 08:22:57 +00009957namespace {
9958 struct RebuildUnknownAnyExpr
9959 : StmtVisitor<RebuildUnknownAnyExpr, Expr*> {
9960
9961 Sema &S;
9962
9963 /// The current destination type.
9964 QualType DestType;
9965
9966 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9967 : S(S), DestType(castType) {}
9968
9969 Expr *VisitStmt(Stmt *S) {
9970 llvm_unreachable("unexpected expression kind!");
9971 return 0;
9972 }
9973
9974 Expr *VisitCallExpr(CallExpr *call) {
9975 call->setCallee(Visit(call->getCallee()));
9976 return call;
9977 }
9978
9979 Expr *VisitParenExpr(ParenExpr *paren) {
9980 paren->setSubExpr(Visit(paren->getSubExpr()));
9981 return paren;
9982 }
9983
9984 Expr *VisitUnaryExtension(UnaryOperator *op) {
9985 op->setSubExpr(Visit(op->getSubExpr()));
9986 return op;
9987 }
9988
9989 Expr *VisitImplicitCastExpr(ImplicitCastExpr *ice) {
9990 // If this isn't an inner resolution, just recurse down.
9991 if (ice->getCastKind() != CK_ResolveUnknownAnyType) {
9992 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
9993 ice->setSubExpr(Visit(ice->getSubExpr()));
9994 return ice;
9995 }
9996
9997 QualType type = ice->getType();
9998 assert(type.getUnqualifiedType() == type);
9999
10000 // The only time it should be possible for this to appear
10001 // internally to an unknown-any expression is when handling a call.
10002 const FunctionProtoType *proto = type->castAs<FunctionProtoType>();
10003 DestType = S.Context.getFunctionType(DestType,
10004 proto->arg_type_begin(),
10005 proto->getNumArgs(),
10006 proto->getExtProtoInfo());
10007
10008 // Strip the resolve cast when recursively rebuilding.
10009 return Visit(ice->getSubExpr());
10010 }
10011
10012 Expr *VisitDeclRefExpr(DeclRefExpr *ref) {
10013 ExprValueKind valueKind = VK_LValue;
10014 if (!S.getLangOptions().CPlusPlus && DestType->isFunctionType())
10015 valueKind = VK_RValue;
10016
10017 return ImplicitCastExpr::Create(S.Context, DestType,
10018 CK_ResolveUnknownAnyType,
10019 ref, 0, valueKind);
10020 }
10021 };
10022}
10023
10024/// Check a cast of an unknown-any type. We intentionally only
10025/// trigger this for C-style casts.
10026bool Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10027 Expr *&castExpr, CastKind &castKind,
10028 ExprValueKind &VK, CXXCastPath &path) {
10029 VK = Expr::getValueKindForType(castType);
10030
10031 // Rewrite the casted expression from scratch.
10032 castExpr = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10033
10034 return CheckCastTypes(typeRange, castType, castExpr, castKind, VK, path);
10035}
10036
10037static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10038 Expr *orig = e;
10039 while (true) {
10040 e = e->IgnoreParenImpCasts();
10041 if (CallExpr *call = dyn_cast<CallExpr>(e))
10042 e = call->getCallee();
10043 else
10044 break;
10045 }
10046
10047 assert(isa<DeclRefExpr>(e) && "unexpected form of unknown-any expression");
10048 DeclRefExpr *ref = cast<DeclRefExpr>(e);
10049 S.Diag(ref->getLocation(), diag::err_bad_use_of_unknown_any)
10050 << ref->getDecl() << orig->getSourceRange();
10051
10052 // Never recoverable.
10053 return ExprError();
10054}
10055
John McCall36e7fe32010-10-12 00:20:44 +000010056/// Check for operands with placeholder types and complain if found.
10057/// Returns true if there was an error and no recovery was possible.
10058ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
John McCall31996342011-04-07 08:22:57 +000010059 // Placeholder types are always *exactly* the appropriate builtin type.
10060 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010061
John McCall31996342011-04-07 08:22:57 +000010062 // Overloaded expressions.
10063 if (type == Context.OverloadTy)
10064 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010065 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010066 QualType(),
10067 diag::err_ovl_unresolvable);
10068
10069 // Expressions of unknown type.
10070 if (type == Context.UnknownAnyTy)
10071 return diagnoseUnknownAnyExpr(*this, E);
10072
10073 assert(!type->isPlaceholderType());
10074 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010075}