blob: 3ced0fe66d357ffe58ce0066d9a5a7b1ab441e58 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000072 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Douglas Gregor171c45a2009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 if (FD->isDeleted()) {
88 Diag(Loc, diag::err_deleted_function_use);
89 Diag(D->getLocation(), diag::note_unavailable_here) << true;
90 return true;
91 }
Douglas Gregorde681d42009-02-24 04:26:15 +000092 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000093
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000094 // See if this declaration is unavailable or deprecated.
95 std::string Message;
96 switch (D->getAvailability(&Message)) {
97 case AR_Available:
98 case AR_NotYetIntroduced:
99 break;
100
101 case AR_Deprecated:
102 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103 break;
104
105 case AR_Unavailable:
106 if (Message.empty()) {
107 if (!UnknownObjCClass)
108 Diag(Loc, diag::err_unavailable) << D->getDeclName();
109 else
110 Diag(Loc, diag::warn_unavailable_fwdclass_message)
111 << D->getDeclName();
112 }
113 else
114 Diag(Loc, diag::err_unavailable_message)
115 << D->getDeclName() << Message;
116 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117 break;
118 }
119
Anders Carlsson73067a02010-10-22 23:37:08 +0000120 // Warn if this is used but marked unused.
121 if (D->hasAttr<UnusedAttr>())
122 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
Douglas Gregor171c45a2009-02-18 21:56:37 +0000124 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000125}
126
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131 // FIXME: C++0x implicitly-deleted special member functions could be
132 // detected here so that we could improve diagnostics to say, e.g.,
133 // "base class 'A' had a deleted copy constructor".
134 if (FD->isDeleted())
135 return std::string();
136
137 std::string Message;
138 if (FD->getAvailability(&Message))
139 return ": " + Message;
140
141 return std::string();
142}
143
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000152 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000153
154 // FIXME: In C++0x, if any of the arguments are parameter pack
155 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Mike Stump87c57ac2009-05-16 07:39:55 +0000159 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 bool warnNotEnoughArgs = false;
163 int isMethod = 0;
164 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165 // skip over named parameters.
166 ObjCMethodDecl::param_iterator P, E = MD->param_end();
167 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168 if (nullPos)
169 --nullPos;
170 else
171 ++i;
172 }
173 warnNotEnoughArgs = (P != E || i >= NumArgs);
174 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000176 // skip over named parameters.
177 ObjCMethodDecl::param_iterator P, E = FD->param_end();
178 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179 if (nullPos)
180 --nullPos;
181 else
182 ++i;
183 }
184 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000192 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193 unsigned NumArgsInProto = Proto->getNumArgs();
194 unsigned k;
195 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196 if (nullPos)
197 --nullPos;
198 else
199 ++i;
200 }
201 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202 }
203 if (Ty->isBlockPointerType())
204 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000205 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000206 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
214 }
215 int sentinel = i;
216 while (sentinelPos > 0 && i < NumArgs-1) {
217 --sentinelPos;
218 ++i;
219 }
220 if (sentinelPos > 0) {
221 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000238 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239 Expr::NPC_ValueDependentIsNull))
240 return;
241
242 // Unfortunately, __null has type 'int'.
243 if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000247}
248
Douglas Gregor87f95b02009-02-26 21:00:50 +0000249SourceRange Sema::getExprRange(ExprTy *E) const {
250 Expr *Ex = (Expr *)E;
251 return Ex? Ex->getSourceRange() : SourceRange();
252}
253
Chris Lattner513165e2008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000266 else if (Ty->isArrayType()) {
267 // In C90 mode, arrays only promote to pointers if the array expression is
268 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269 // type 'array of type' is converted to an expression that has type 'pointer
270 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
271 // that has type 'array of type' ...". The relevant change is "an lvalue"
272 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000273 //
274 // C++ 4.2p1:
275 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276 // T" can be converted to an rvalue of type "pointer to T".
277 //
John McCall086a4642010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 }
John Wiegley01296292011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000283}
284
John Wiegley01296292011-04-08 18:41:53 +0000285ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000286 // C++ [conv.lval]p1:
287 // A glvalue of a non-function, non-array type T can be
288 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000289 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000290
John McCall27584242010-12-06 20:48:59 +0000291 QualType T = E->getType();
292 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000293
John McCall27584242010-12-06 20:48:59 +0000294 // Create a load out of an ObjCProperty l-value, if necessary.
295 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000296 ExprResult Res = ConvertPropertyForRValue(E);
297 if (Res.isInvalid())
298 return Owned(E);
299 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000300 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000301 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000302 }
John McCall27584242010-12-06 20:48:59 +0000303
304 // We don't want to throw lvalue-to-rvalue casts on top of
305 // expressions of certain types in C++.
306 if (getLangOptions().CPlusPlus &&
307 (E->getType() == Context.OverloadTy ||
308 T->isDependentType() ||
309 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000310 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000311
312 // The C standard is actually really unclear on this point, and
313 // DR106 tells us what the result should be but not why. It's
314 // generally best to say that void types just doesn't undergo
315 // lvalue-to-rvalue at all. Note that expressions of unqualified
316 // 'void' type are never l-values, but qualified void can be.
317 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000318 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000319
320 // C++ [conv.lval]p1:
321 // [...] If T is a non-class type, the type of the prvalue is the
322 // cv-unqualified version of T. Otherwise, the type of the
323 // rvalue is T.
324 //
325 // C99 6.3.2.1p2:
326 // If the lvalue has qualified type, the value has the unqualified
327 // version of the type of the lvalue; otherwise, the value has the
328 // type of the lvalue.
329 if (T.hasQualifiers())
330 T = T.getUnqualifiedType();
331
Ted Kremenekdf26df72011-03-01 18:41:00 +0000332 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000333
John Wiegley01296292011-04-08 18:41:53 +0000334 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
335 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000336}
337
John Wiegley01296292011-04-08 18:41:53 +0000338ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
339 ExprResult Res = DefaultFunctionArrayConversion(E);
340 if (Res.isInvalid())
341 return ExprError();
342 Res = DefaultLvalueConversion(Res.take());
343 if (Res.isInvalid())
344 return ExprError();
345 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000346}
347
348
Chris Lattner513165e2008-07-25 21:10:04 +0000349/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000350/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000351/// sometimes surpressed. For example, the array->pointer conversion doesn't
352/// apply if the array is an argument to the sizeof or address (&) operators.
353/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000354ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000355 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000356 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
357 if (Res.isInvalid())
358 return Owned(E);
359 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000360
361 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000362 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000363
364 // Try to perform integral promotions if the object has a theoretically
365 // promotable type.
366 if (Ty->isIntegralOrUnscopedEnumerationType()) {
367 // C99 6.3.1.1p2:
368 //
369 // The following may be used in an expression wherever an int or
370 // unsigned int may be used:
371 // - an object or expression with an integer type whose integer
372 // conversion rank is less than or equal to the rank of int
373 // and unsigned int.
374 // - A bit-field of type _Bool, int, signed int, or unsigned int.
375 //
376 // If an int can represent all values of the original type, the
377 // value is converted to an int; otherwise, it is converted to an
378 // unsigned int. These are called the integer promotions. All
379 // other types are unchanged by the integer promotions.
380
381 QualType PTy = Context.isPromotableBitField(E);
382 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000383 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
384 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000385 }
386 if (Ty->isPromotableIntegerType()) {
387 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000388 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
389 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000390 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000391 }
John Wiegley01296292011-04-08 18:41:53 +0000392 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000393}
394
Chris Lattner2ce500f2008-07-25 22:25:12 +0000395/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000396/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000397/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000398ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
399 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000400 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000401
John Wiegley01296292011-04-08 18:41:53 +0000402 ExprResult Res = UsualUnaryConversions(E);
403 if (Res.isInvalid())
404 return Owned(E);
405 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000406
Chris Lattner2ce500f2008-07-25 22:25:12 +0000407 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000408 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
410
411 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000412}
413
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000414/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
415/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000416/// interfaces passed by value.
417ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000418 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000419 ExprResult ExprRes = DefaultArgumentPromotion(E);
420 if (ExprRes.isInvalid())
421 return ExprError();
422 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000424 // __builtin_va_start takes the second argument as a "varargs" argument, but
425 // it doesn't actually do anything with it. It doesn't need to be non-pod
426 // etc.
427 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000429
John Wiegley01296292011-04-08 18:41:53 +0000430 if (E->getType()->isObjCObjectType() &&
431 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000432 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000433 << E->getType() << CT))
434 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000435
John Wiegley01296292011-04-08 18:41:53 +0000436 if (!E->getType()->isPODType() &&
437 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000438 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000439 << E->getType() << CT))
440 return ExprError();
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000441
John Wiegley01296292011-04-08 18:41:53 +0000442 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000443}
444
Chris Lattner513165e2008-07-25 21:10:04 +0000445/// UsualArithmeticConversions - Performs various conversions that are common to
446/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000447/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000448/// responsible for emitting appropriate error diagnostics.
449/// FIXME: verify the conversion rules for "complex int" are consistent with
450/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000451QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000452 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000453 if (!isCompAssign) {
454 lhsExpr = UsualUnaryConversions(lhsExpr.take());
455 if (lhsExpr.isInvalid())
456 return QualType();
457 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000458
John Wiegley01296292011-04-08 18:41:53 +0000459 rhsExpr = UsualUnaryConversions(rhsExpr.take());
460 if (rhsExpr.isInvalid())
461 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000462
Mike Stump11289f42009-09-09 15:08:12 +0000463 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000464 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000465 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000466 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000467 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000468 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000469
470 // If both types are identical, no conversion is needed.
471 if (lhs == rhs)
472 return lhs;
473
474 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
475 // The caller can deal with this (e.g. pointer + int).
476 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
477 return lhs;
478
John McCalld005ac92010-11-13 08:17:45 +0000479 // Apply unary and bitfield promotions to the LHS's type.
480 QualType lhs_unpromoted = lhs;
481 if (lhs->isPromotableIntegerType())
482 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000483 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000484 if (!LHSBitfieldPromoteTy.isNull())
485 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000486 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000487 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000488
John McCalld005ac92010-11-13 08:17:45 +0000489 // If both types are identical, no conversion is needed.
490 if (lhs == rhs)
491 return lhs;
492
493 // At this point, we have two different arithmetic types.
494
495 // Handle complex types first (C99 6.3.1.8p1).
496 bool LHSComplexFloat = lhs->isComplexType();
497 bool RHSComplexFloat = rhs->isComplexType();
498 if (LHSComplexFloat || RHSComplexFloat) {
499 // if we have an integer operand, the result is the complex type.
500
John McCallc5e62b42010-11-13 09:02:35 +0000501 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
502 if (rhs->isIntegerType()) {
503 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000504 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
505 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000506 } else {
507 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000508 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000509 }
John McCalld005ac92010-11-13 08:17:45 +0000510 return lhs;
511 }
512
John McCallc5e62b42010-11-13 09:02:35 +0000513 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
514 if (!isCompAssign) {
515 // int -> float -> _Complex float
516 if (lhs->isIntegerType()) {
517 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000518 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
519 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000520 } else {
521 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000522 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000523 }
524 }
John McCalld005ac92010-11-13 08:17:45 +0000525 return rhs;
526 }
527
528 // This handles complex/complex, complex/float, or float/complex.
529 // When both operands are complex, the shorter operand is converted to the
530 // type of the longer, and that is the type of the result. This corresponds
531 // to what is done when combining two real floating-point operands.
532 // The fun begins when size promotion occur across type domains.
533 // From H&S 6.3.4: When one operand is complex and the other is a real
534 // floating-point type, the less precise type is converted, within it's
535 // real or complex domain, to the precision of the other type. For example,
536 // when combining a "long double" with a "double _Complex", the
537 // "double _Complex" is promoted to "long double _Complex".
538 int order = Context.getFloatingTypeOrder(lhs, rhs);
539
540 // If both are complex, just cast to the more precise type.
541 if (LHSComplexFloat && RHSComplexFloat) {
542 if (order > 0) {
543 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000544 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000545 return lhs;
546
547 } else if (order < 0) {
548 // _Complex float -> _Complex double
549 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000550 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000551 return rhs;
552 }
553 return lhs;
554 }
555
556 // If just the LHS is complex, the RHS needs to be converted,
557 // and the LHS might need to be promoted.
558 if (LHSComplexFloat) {
559 if (order > 0) { // LHS is wider
560 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000561 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000562 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
563 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000564 return lhs;
565 }
566
567 // RHS is at least as wide. Find its corresponding complex type.
568 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
569
570 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000571 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000572
573 // _Complex float -> _Complex double
574 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000575 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000576
577 return result;
578 }
579
580 // Just the RHS is complex, so the LHS needs to be converted
581 // and the RHS might need to be promoted.
582 assert(RHSComplexFloat);
583
584 if (order < 0) { // RHS is wider
585 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000587 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000588 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
589 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000590 }
John McCalld005ac92010-11-13 08:17:45 +0000591 return rhs;
592 }
593
594 // LHS is at least as wide. Find its corresponding complex type.
595 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
596
597 // double -> _Complex double
598 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000599 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000600
601 // _Complex float -> _Complex double
602 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000603 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000604
605 return result;
606 }
607
608 // Now handle "real" floating types (i.e. float, double, long double).
609 bool LHSFloat = lhs->isRealFloatingType();
610 bool RHSFloat = rhs->isRealFloatingType();
611 if (LHSFloat || RHSFloat) {
612 // If we have two real floating types, convert the smaller operand
613 // to the bigger result.
614 if (LHSFloat && RHSFloat) {
615 int order = Context.getFloatingTypeOrder(lhs, rhs);
616 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000618 return lhs;
619 }
620
621 assert(order < 0 && "illegal float comparison");
622 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626
627 // If we have an integer operand, the result is the real floating type.
628 if (LHSFloat) {
629 if (rhs->isIntegerType()) {
630 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000631 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000632 return lhs;
633 }
634
635 // Convert both sides to the appropriate complex float.
636 assert(rhs->isComplexIntegerType());
637 QualType result = Context.getComplexType(lhs);
638
639 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000640 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641
642 // float -> _Complex float
643 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645
646 return result;
647 }
648
649 assert(RHSFloat);
650 if (lhs->isIntegerType()) {
651 // Convert lhs to the rhs floating point type.
652 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000653 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000654 return rhs;
655 }
656
657 // Convert both sides to the appropriate complex float.
658 assert(lhs->isComplexIntegerType());
659 QualType result = Context.getComplexType(rhs);
660
661 // _Complex int -> _Complex float
662 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000663 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000664
665 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000666 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000667
668 return result;
669 }
670
671 // Handle GCC complex int extension.
672 // FIXME: if the operands are (int, _Complex long), we currently
673 // don't promote the complex. Also, signedness?
674 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
675 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
676 if (lhsComplexInt && rhsComplexInt) {
677 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
678 rhsComplexInt->getElementType());
679 assert(order && "inequal types with equal element ordering");
680 if (order > 0) {
681 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000682 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000683 return lhs;
684 }
685
686 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000687 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000688 return rhs;
689 } else if (lhsComplexInt) {
690 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000692 return lhs;
693 } else if (rhsComplexInt) {
694 // int -> _Complex int
695 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000697 return rhs;
698 }
699
700 // Finally, we have two differing integer types.
701 // The rules for this case are in C99 6.3.1.8
702 int compare = Context.getIntegerTypeOrder(lhs, rhs);
703 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
704 rhsSigned = rhs->hasSignedIntegerRepresentation();
705 if (lhsSigned == rhsSigned) {
706 // Same signedness; use the higher-ranked type
707 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000709 return lhs;
710 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000711 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000712 return rhs;
713 } else if (compare != (lhsSigned ? 1 : -1)) {
714 // The unsigned type has greater than or equal rank to the
715 // signed type, so use the unsigned type
716 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000717 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000718 return lhs;
719 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000720 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000721 return rhs;
722 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
723 // The two types are different widths; if we are here, that
724 // means the signed type is larger than the unsigned type, so
725 // use the signed type.
726 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000727 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000728 return lhs;
729 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000730 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000731 return rhs;
732 } else {
733 // The signed type is higher-ranked than the unsigned type,
734 // but isn't actually any bigger (like unsigned int and long
735 // on most 32-bit systems). Use the unsigned type corresponding
736 // to the signed type.
737 QualType result =
738 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000740 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000742 return result;
743 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000744}
745
Chris Lattner513165e2008-07-25 21:10:04 +0000746//===----------------------------------------------------------------------===//
747// Semantic Analysis for various Expression Types
748//===----------------------------------------------------------------------===//
749
750
Steve Naroff83895f72007-09-16 03:34:24 +0000751/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000752/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
753/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
754/// multiple tokens. However, the common case is that StringToks points to one
755/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000756///
John McCalldadc5752010-08-24 06:29:42 +0000757ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000758Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000759 assert(NumStringToks && "Must have at least one string!");
760
Chris Lattner8a24e582009-01-16 18:51:42 +0000761 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000762 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000763 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000764
Chris Lattner23b7eb62007-06-15 23:05:46 +0000765 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000766 for (unsigned i = 0; i != NumStringToks; ++i)
767 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000768
Chris Lattner36fc8792008-02-11 00:02:17 +0000769 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000770 if (Literal.AnyWide)
771 StrTy = Context.getWCharType();
772 else if (Literal.Pascal)
773 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000774
775 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000776 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000777 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000778
Chris Lattner36fc8792008-02-11 00:02:17 +0000779 // Get an array type for the string, according to C99 6.4.5. This includes
780 // the nul terminator character as well as the string length for pascal
781 // strings.
782 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000783 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000784 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattner5b183d82006-11-10 05:03:26 +0000786 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000787 return Owned(StringLiteral::Create(Context, Literal.GetString(),
788 Literal.GetStringLength(),
789 Literal.AnyWide, StrTy,
790 &StringTokLocs[0],
791 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000792}
793
John McCallc63de662011-02-02 13:00:07 +0000794enum CaptureResult {
795 /// No capture is required.
796 CR_NoCapture,
797
798 /// A capture is required.
799 CR_Capture,
800
John McCall351762c2011-02-07 10:33:21 +0000801 /// A by-ref capture is required.
802 CR_CaptureByRef,
803
John McCallc63de662011-02-02 13:00:07 +0000804 /// An error occurred when trying to capture the given variable.
805 CR_Error
806};
807
808/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000809///
John McCallc63de662011-02-02 13:00:07 +0000810/// \param var - the variable referenced
811/// \param DC - the context which we couldn't capture through
812static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000813diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000814 VarDecl *var, DeclContext *DC) {
815 switch (S.ExprEvalContexts.back().Context) {
816 case Sema::Unevaluated:
817 // The argument will never be evaluated, so don't complain.
818 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000819
John McCallc63de662011-02-02 13:00:07 +0000820 case Sema::PotentiallyEvaluated:
821 case Sema::PotentiallyEvaluatedIfUsed:
822 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000823
John McCallc63de662011-02-02 13:00:07 +0000824 case Sema::PotentiallyPotentiallyEvaluated:
825 // FIXME: delay these!
826 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
John McCallc63de662011-02-02 13:00:07 +0000829 // Don't diagnose about capture if we're not actually in code right
830 // now; in general, there are more appropriate places that will
831 // diagnose this.
832 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
833
John McCall92d627e2011-03-22 23:15:50 +0000834 // Certain madnesses can happen with parameter declarations, which
835 // we want to ignore.
836 if (isa<ParmVarDecl>(var)) {
837 // - If the parameter still belongs to the translation unit, then
838 // we're actually just using one parameter in the declaration of
839 // the next. This is useful in e.g. VLAs.
840 if (isa<TranslationUnitDecl>(var->getDeclContext()))
841 return CR_NoCapture;
842
843 // - This particular madness can happen in ill-formed default
844 // arguments; claim it's okay and let downstream code handle it.
845 if (S.CurContext == var->getDeclContext()->getParent())
846 return CR_NoCapture;
847 }
John McCallc63de662011-02-02 13:00:07 +0000848
849 DeclarationName functionName;
850 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
851 functionName = fn->getDeclName();
852 // FIXME: variable from enclosing block that we couldn't capture from!
853
854 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
855 << var->getIdentifier() << functionName;
856 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
857 << var->getIdentifier();
858
859 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000860}
861
John McCall351762c2011-02-07 10:33:21 +0000862/// There is a well-formed capture at a particular scope level;
863/// propagate it through all the nested blocks.
864static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
865 const BlockDecl::Capture &capture) {
866 VarDecl *var = capture.getVariable();
867
868 // Update all the inner blocks with the capture information.
869 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
870 i != e; ++i) {
871 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
872 innerBlock->Captures.push_back(
873 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
874 /*nested*/ true, capture.getCopyExpr()));
875 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
876 }
877
878 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
879}
880
881/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000882/// given value in the current context requires a variable capture.
883///
884/// This also keeps the captures set in the BlockScopeInfo records
885/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000886static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000887 ValueDecl *value) {
888 // Only variables ever require capture.
889 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000890 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000891
892 // Fast path: variables from the current context never require capture.
893 DeclContext *DC = S.CurContext;
894 if (var->getDeclContext() == DC) return CR_NoCapture;
895
896 // Only variables with local storage require capture.
897 // FIXME: What about 'const' variables in C++?
898 if (!var->hasLocalStorage()) return CR_NoCapture;
899
900 // Otherwise, we need to capture.
901
902 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000903 do {
904 // Only blocks (and eventually C++0x closures) can capture; other
905 // scopes don't work.
906 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000907 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000908
909 BlockScopeInfo *blockScope =
910 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
911 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
912
John McCall351762c2011-02-07 10:33:21 +0000913 // Check whether we've already captured it in this block. If so,
914 // we're done.
915 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
916 return propagateCapture(S, functionScopesIndex,
917 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000918
919 functionScopesIndex--;
920 DC = cast<BlockDecl>(DC)->getDeclContext();
921 } while (var->getDeclContext() != DC);
922
John McCall351762c2011-02-07 10:33:21 +0000923 // Okay, we descended all the way to the block that defines the variable.
924 // Actually try to capture it.
925 QualType type = var->getType();
926
927 // Prohibit variably-modified types.
928 if (type->isVariablyModifiedType()) {
929 S.Diag(loc, diag::err_ref_vm_type);
930 S.Diag(var->getLocation(), diag::note_declared_at);
931 return CR_Error;
932 }
933
934 // Prohibit arrays, even in __block variables, but not references to
935 // them.
936 if (type->isArrayType()) {
937 S.Diag(loc, diag::err_ref_array_type);
938 S.Diag(var->getLocation(), diag::note_declared_at);
939 return CR_Error;
940 }
941
942 S.MarkDeclarationReferenced(loc, var);
943
944 // The BlocksAttr indicates the variable is bound by-reference.
945 bool byRef = var->hasAttr<BlocksAttr>();
946
947 // Build a copy expression.
948 Expr *copyExpr = 0;
949 if (!byRef && S.getLangOptions().CPlusPlus &&
950 !type->isDependentType() && type->isStructureOrClassType()) {
951 // According to the blocks spec, the capture of a variable from
952 // the stack requires a const copy constructor. This is not true
953 // of the copy/move done to move a __block variable to the heap.
954 type.addConst();
955
956 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
957 ExprResult result =
958 S.PerformCopyInitialization(
959 InitializedEntity::InitializeBlock(var->getLocation(),
960 type, false),
961 loc, S.Owned(declRef));
962
963 // Build a full-expression copy expression if initialization
964 // succeeded and used a non-trivial constructor. Recover from
965 // errors by pretending that the copy isn't necessary.
966 if (!result.isInvalid() &&
967 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
968 result = S.MaybeCreateExprWithCleanups(result);
969 copyExpr = result.take();
970 }
971 }
972
973 // We're currently at the declarer; go back to the closure.
974 functionScopesIndex++;
975 BlockScopeInfo *blockScope =
976 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
977
978 // Build a valid capture in this scope.
979 blockScope->Captures.push_back(
980 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
981 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
982
983 // Propagate that to inner captures if necessary.
984 return propagateCapture(S, functionScopesIndex,
985 blockScope->Captures.back());
986}
987
988static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
989 const DeclarationNameInfo &NameInfo,
990 bool byRef) {
991 assert(isa<VarDecl>(vd) && "capturing non-variable");
992
993 VarDecl *var = cast<VarDecl>(vd);
994 assert(var->hasLocalStorage() && "capturing non-local");
995 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
996
997 QualType exprType = var->getType().getNonReferenceType();
998
999 BlockDeclRefExpr *BDRE;
1000 if (!byRef) {
1001 // The variable will be bound by copy; make it const within the
1002 // closure, but record that this was done in the expression.
1003 bool constAdded = !exprType.isConstQualified();
1004 exprType.addConst();
1005
1006 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1007 NameInfo.getLoc(), false,
1008 constAdded);
1009 } else {
1010 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1011 NameInfo.getLoc(), true);
1012 }
1013
1014 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001015}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001016
John McCalldadc5752010-08-24 06:29:42 +00001017ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001018Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001019 SourceLocation Loc,
1020 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001021 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001022 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001023}
1024
John McCallf4cd4f92011-02-09 01:13:10 +00001025/// BuildDeclRefExpr - Build an expression that references a
1026/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001027ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001028Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001029 const DeclarationNameInfo &NameInfo,
1030 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001031 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001032
John McCall086a4642010-11-24 05:12:34 +00001033 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001034 SS? SS->getWithLocInContext(Context)
1035 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001036 D, NameInfo, Ty, VK);
1037
1038 // Just in case we're building an illegal pointer-to-member.
1039 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1040 E->setObjectKind(OK_BitField);
1041
1042 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001043}
1044
John McCallfeb624a2010-11-23 20:48:44 +00001045static ExprResult
1046BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1047 const CXXScopeSpec &SS, FieldDecl *Field,
1048 DeclAccessPair FoundDecl,
1049 const DeclarationNameInfo &MemberNameInfo);
1050
John McCalldadc5752010-08-24 06:29:42 +00001051ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001052Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1053 SourceLocation loc,
1054 IndirectFieldDecl *indirectField,
1055 Expr *baseObjectExpr,
1056 SourceLocation opLoc) {
1057 // First, build the expression that refers to the base object.
1058
1059 bool baseObjectIsPointer = false;
1060 Qualifiers baseQuals;
1061
1062 // Case 1: the base of the indirect field is not a field.
1063 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001064 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001065 if (baseVariable) {
1066 assert(baseVariable->getType()->isRecordType());
1067
1068 // In principle we could have a member access expression that
1069 // accesses an anonymous struct/union that's a static member of
1070 // the base object's class. However, under the current standard,
1071 // static data members cannot be anonymous structs or unions.
1072 // Supporting this is as easy as building a MemberExpr here.
1073 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1074
1075 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1076
1077 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001078 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001079 if (result.isInvalid()) return ExprError();
1080
1081 baseObjectExpr = result.take();
1082 baseObjectIsPointer = false;
1083 baseQuals = baseObjectExpr->getType().getQualifiers();
1084
1085 // Case 2: the base of the indirect field is a field and the user
1086 // wrote a member expression.
1087 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001088 // The caller provided the base object expression. Determine
1089 // whether its a pointer and whether it adds any qualifiers to the
1090 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001091 QualType objectType = baseObjectExpr->getType();
1092
1093 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1094 baseObjectIsPointer = true;
1095 objectType = ptr->getPointeeType();
1096 } else {
1097 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001098 }
John McCallf3a88602011-02-03 08:15:49 +00001099 baseQuals = objectType.getQualifiers();
1100
1101 // Case 3: the base of the indirect field is a field and we should
1102 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001103 } else {
1104 // We've found a member of an anonymous struct/union that is
1105 // inside a non-anonymous struct/union, so in a well-formed
1106 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001107 CXXMethodDecl *method = tryCaptureCXXThis();
1108 if (!method) {
1109 Diag(loc, diag::err_invalid_member_use_in_static_method)
1110 << indirectField->getDeclName();
1111 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001112 }
1113
John McCallf3a88602011-02-03 08:15:49 +00001114 // Our base object expression is "this".
1115 baseObjectExpr =
1116 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1117 /*isImplicit=*/ true);
1118 baseObjectIsPointer = true;
1119 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001120 }
1121
1122 // Build the implicit member references to the field of the
1123 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001124 Expr *result = baseObjectExpr;
1125 IndirectFieldDecl::chain_iterator
1126 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001127
John McCallf3a88602011-02-03 08:15:49 +00001128 // Build the first member access in the chain with full information.
1129 if (!baseVariable) {
1130 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001131
John McCallf3a88602011-02-03 08:15:49 +00001132 // FIXME: use the real found-decl info!
1133 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001134
John McCallf3a88602011-02-03 08:15:49 +00001135 // Make a nameInfo that properly uses the anonymous name.
1136 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001137
John McCallf3a88602011-02-03 08:15:49 +00001138 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001139 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001140 memberNameInfo).take();
1141 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001142
John McCallf3a88602011-02-03 08:15:49 +00001143 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001144 }
1145
John McCallf3a88602011-02-03 08:15:49 +00001146 // In all cases, we should now skip the first declaration in the chain.
1147 ++FI;
1148
Douglas Gregore10f36d2011-02-18 02:44:58 +00001149 while (FI != FEnd) {
1150 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001151
1152 // FIXME: these are somewhat meaningless
1153 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1154 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001155
1156 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001157 (FI == FEnd? SS : EmptySS), field,
1158 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001159 .take();
1160 }
1161
1162 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001163}
1164
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001165/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001166/// possibly a list of template arguments.
1167///
1168/// If this produces template arguments, it is permitted to call
1169/// DecomposeTemplateName.
1170///
1171/// This actually loses a lot of source location information for
1172/// non-standard name kinds; we should consider preserving that in
1173/// some way.
1174static void DecomposeUnqualifiedId(Sema &SemaRef,
1175 const UnqualifiedId &Id,
1176 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001177 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001178 const TemplateArgumentListInfo *&TemplateArgs) {
1179 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1180 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1181 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1182
1183 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1184 Id.TemplateId->getTemplateArgs(),
1185 Id.TemplateId->NumArgs);
1186 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1187 TemplateArgsPtr.release();
1188
John McCall3e56fd42010-08-23 07:28:44 +00001189 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001190 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1191 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001192 TemplateArgs = &Buffer;
1193 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001194 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001195 TemplateArgs = 0;
1196 }
1197}
1198
John McCall2d74de92009-12-01 22:10:20 +00001199/// Determines if the given class is provably not derived from all of
1200/// the prospective base classes.
1201static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1202 CXXRecordDecl *Record,
1203 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001204 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001205 return false;
1206
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001207 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001208 if (!RD) return false;
1209 Record = cast<CXXRecordDecl>(RD);
1210
John McCall2d74de92009-12-01 22:10:20 +00001211 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1212 E = Record->bases_end(); I != E; ++I) {
1213 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1214 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1215 if (!BaseRT) return false;
1216
1217 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001218 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1219 return false;
1220 }
1221
1222 return true;
1223}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001224
John McCall2d74de92009-12-01 22:10:20 +00001225enum IMAKind {
1226 /// The reference is definitely not an instance member access.
1227 IMA_Static,
1228
1229 /// The reference may be an implicit instance member access.
1230 IMA_Mixed,
1231
1232 /// The reference may be to an instance member, but it is invalid if
1233 /// so, because the context is not an instance method.
1234 IMA_Mixed_StaticContext,
1235
1236 /// The reference may be to an instance member, but it is invalid if
1237 /// so, because the context is from an unrelated class.
1238 IMA_Mixed_Unrelated,
1239
1240 /// The reference is definitely an implicit instance member access.
1241 IMA_Instance,
1242
1243 /// The reference may be to an unresolved using declaration.
1244 IMA_Unresolved,
1245
1246 /// The reference may be to an unresolved using declaration and the
1247 /// context is not an instance method.
1248 IMA_Unresolved_StaticContext,
1249
John McCall2d74de92009-12-01 22:10:20 +00001250 /// All possible referrents are instance members and the current
1251 /// context is not an instance method.
1252 IMA_Error_StaticContext,
1253
1254 /// All possible referrents are instance members of an unrelated
1255 /// class.
1256 IMA_Error_Unrelated
1257};
1258
1259/// The given lookup names class member(s) and is not being used for
1260/// an address-of-member expression. Classify the type of access
1261/// according to whether it's possible that this reference names an
1262/// instance member. This is best-effort; it is okay to
1263/// conservatively answer "yes", in which case some errors will simply
1264/// not be caught until template-instantiation.
1265static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1266 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001267 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001268
John McCall87fe5d52010-05-20 01:18:31 +00001269 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001270 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001271 (!isa<CXXMethodDecl>(DC) ||
1272 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001273
1274 if (R.isUnresolvableResult())
1275 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1276
1277 // Collect all the declaring classes of instance members we find.
1278 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001279 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001280 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001282 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001283
John McCalla8ae2222010-04-06 21:38:20 +00001284 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001285 if (dyn_cast<FieldDecl>(D))
1286 hasField = true;
1287
John McCall2d74de92009-12-01 22:10:20 +00001288 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001289 Classes.insert(R->getCanonicalDecl());
1290 }
1291 else
1292 hasNonInstance = true;
1293 }
1294
1295 // If we didn't find any instance members, it can't be an implicit
1296 // member reference.
1297 if (Classes.empty())
1298 return IMA_Static;
1299
1300 // If the current context is not an instance method, it can't be
1301 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001302 if (isStaticContext) {
1303 if (hasNonInstance)
1304 return IMA_Mixed_StaticContext;
1305
1306 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1307 // C++0x [expr.prim.general]p10:
1308 // An id-expression that denotes a non-static data member or non-static
1309 // member function of a class can only be used:
1310 // (...)
1311 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1312 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1313 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1314 if (isUnevaluatedExpression)
1315 return IMA_Mixed_StaticContext;
1316 }
1317
1318 return IMA_Error_StaticContext;
1319 }
John McCall2d74de92009-12-01 22:10:20 +00001320
1321 // If we can prove that the current context is unrelated to all the
1322 // declaring classes, it can't be an implicit member reference (in
1323 // which case it's an error if any of those members are selected).
1324 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001325 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001326 Classes))
1327 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1328
1329 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1330}
1331
1332/// Diagnose a reference to a field with no object available.
1333static void DiagnoseInstanceReference(Sema &SemaRef,
1334 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001335 NamedDecl *rep,
1336 const DeclarationNameInfo &nameInfo) {
1337 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001338 SourceRange Range(Loc);
1339 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1340
John McCallf3a88602011-02-03 08:15:49 +00001341 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001342 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1343 if (MD->isStatic()) {
1344 // "invalid use of member 'x' in static member function"
1345 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001346 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001347 return;
1348 }
1349 }
1350
1351 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001352 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001353 return;
1354 }
1355
1356 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001357}
1358
John McCalld681c392009-12-16 08:11:27 +00001359/// Diagnose an empty lookup.
1360///
1361/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001362bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1363 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001364 DeclarationName Name = R.getLookupName();
1365
John McCalld681c392009-12-16 08:11:27 +00001366 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001367 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001368 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1369 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001370 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001371 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001372 diagnostic_suggest = diag::err_undeclared_use_suggest;
1373 }
John McCalld681c392009-12-16 08:11:27 +00001374
Douglas Gregor598b08f2009-12-31 05:20:13 +00001375 // If the original lookup was an unqualified lookup, fake an
1376 // unqualified lookup. This is useful when (for example) the
1377 // original lookup would not have found something because it was a
1378 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001379 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001380 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001381 if (isa<CXXRecordDecl>(DC)) {
1382 LookupQualifiedName(R, DC);
1383
1384 if (!R.empty()) {
1385 // Don't give errors about ambiguities in this lookup.
1386 R.suppressDiagnostics();
1387
1388 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1389 bool isInstance = CurMethod &&
1390 CurMethod->isInstance() &&
1391 DC == CurMethod->getParent();
1392
1393 // Give a code modification hint to insert 'this->'.
1394 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1395 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001396 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001397 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1398 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001399 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001400 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001401 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001402 Diag(R.getNameLoc(), diagnostic) << Name
1403 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1404 QualType DepThisType = DepMethod->getThisType(Context);
1405 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1406 R.getNameLoc(), DepThisType, false);
1407 TemplateArgumentListInfo TList;
1408 if (ULE->hasExplicitTemplateArgs())
1409 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001410
Douglas Gregore16af532011-02-28 18:50:33 +00001411 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001412 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001413 CXXDependentScopeMemberExpr *DepExpr =
1414 CXXDependentScopeMemberExpr::Create(
1415 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001416 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001417 R.getLookupNameInfo(), &TList);
1418 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001419 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001420 // FIXME: we should be able to handle this case too. It is correct
1421 // to add this-> here. This is a workaround for PR7947.
1422 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001423 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001424 } else {
John McCalld681c392009-12-16 08:11:27 +00001425 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001426 }
John McCalld681c392009-12-16 08:11:27 +00001427
1428 // Do we really want to note all of these?
1429 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1430 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1431
1432 // Tell the callee to try to recover.
1433 return false;
1434 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001435
1436 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001437 }
1438 }
1439
Douglas Gregor598b08f2009-12-31 05:20:13 +00001440 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001441 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001442 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 if (!R.empty()) {
1444 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1445 if (SS.isEmpty())
1446 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1447 << FixItHint::CreateReplacement(R.getNameLoc(),
1448 R.getLookupName().getAsString());
1449 else
1450 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1451 << Name << computeDeclContext(SS, false) << R.getLookupName()
1452 << SS.getRange()
1453 << FixItHint::CreateReplacement(R.getNameLoc(),
1454 R.getLookupName().getAsString());
1455 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1456 Diag(ND->getLocation(), diag::note_previous_decl)
1457 << ND->getDeclName();
1458
1459 // Tell the callee to try to recover.
1460 return false;
1461 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001462
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001463 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1464 // FIXME: If we ended up with a typo for a type name or
1465 // Objective-C class name, we're in trouble because the parser
1466 // is in the wrong place to recover. Suggest the typo
1467 // correction, but don't make it a fix-it since we're not going
1468 // to recover well anyway.
1469 if (SS.isEmpty())
1470 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1471 else
1472 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1473 << Name << computeDeclContext(SS, false) << R.getLookupName()
1474 << SS.getRange();
1475
1476 // Don't try to recover; it won't work.
1477 return true;
1478 }
1479 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001480 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001481 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001482 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001483 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001484 else
Douglas Gregor25363982010-01-01 00:15:04 +00001485 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001486 << Name << computeDeclContext(SS, false) << Corrected
1487 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001488 return true;
1489 }
Douglas Gregor25363982010-01-01 00:15:04 +00001490 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001491 }
1492
1493 // Emit a special diagnostic for failed member lookups.
1494 // FIXME: computing the declaration context might fail here (?)
1495 if (!SS.isEmpty()) {
1496 Diag(R.getNameLoc(), diag::err_no_member)
1497 << Name << computeDeclContext(SS, false)
1498 << SS.getRange();
1499 return true;
1500 }
1501
John McCalld681c392009-12-16 08:11:27 +00001502 // Give up, we can't recover.
1503 Diag(R.getNameLoc(), diagnostic) << Name;
1504 return true;
1505}
1506
Douglas Gregor05fcf842010-11-02 20:36:02 +00001507ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1508 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001509 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1510 if (!IDecl)
1511 return 0;
1512 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1513 if (!ClassImpDecl)
1514 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001515 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001516 if (!property)
1517 return 0;
1518 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001519 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1520 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001521 return 0;
1522 return property;
1523}
1524
Douglas Gregor05fcf842010-11-02 20:36:02 +00001525bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1526 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1527 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1528 if (!IDecl)
1529 return false;
1530 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1531 if (!ClassImpDecl)
1532 return false;
1533 if (ObjCPropertyImplDecl *PIDecl
1534 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1535 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1536 PIDecl->getPropertyIvarDecl())
1537 return false;
1538
1539 return true;
1540}
1541
Fariborz Jahanian18722982010-07-17 00:59:30 +00001542static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001543 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001544 IdentifierInfo *II,
1545 SourceLocation NameLoc) {
1546 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001547 bool LookForIvars;
1548 if (Lookup.empty())
1549 LookForIvars = true;
1550 else if (CurMeth->isClassMethod())
1551 LookForIvars = false;
1552 else
1553 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001554 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1555 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001556 if (!LookForIvars)
1557 return 0;
1558
Fariborz Jahanian18722982010-07-17 00:59:30 +00001559 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1560 if (!IDecl)
1561 return 0;
1562 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001563 if (!ClassImpDecl)
1564 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001565 bool DynamicImplSeen = false;
1566 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1567 if (!property)
1568 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001569 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001570 DynamicImplSeen =
1571 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001572 // property implementation has a designated ivar. No need to assume a new
1573 // one.
1574 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1575 return 0;
1576 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001577 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001578 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1579 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001580 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001581 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001582 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001583 (Expr *)0, true);
1584 ClassImpDecl->addDecl(Ivar);
1585 IDecl->makeDeclVisibleInContext(Ivar, false);
1586 property->setPropertyIvarDecl(Ivar);
1587 return Ivar;
1588 }
1589 return 0;
1590}
1591
John McCalldadc5752010-08-24 06:29:42 +00001592ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001593 CXXScopeSpec &SS,
1594 UnqualifiedId &Id,
1595 bool HasTrailingLParen,
1596 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001597 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1598 "cannot be direct & operand and have a trailing lparen");
1599
1600 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001601 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001602
John McCall10eae182009-11-30 22:42:35 +00001603 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001604
1605 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001606 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001607 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001608 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001609
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001610 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001611 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001612 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001613
John McCalle66edc12009-11-24 19:00:30 +00001614 // C++ [temp.dep.expr]p3:
1615 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001616 // -- an identifier that was declared with a dependent type,
1617 // (note: handled after lookup)
1618 // -- a template-id that is dependent,
1619 // (note: handled in BuildTemplateIdExpr)
1620 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001621 // -- a nested-name-specifier that contains a class-name that
1622 // names a dependent type.
1623 // Determine whether this is a member of an unknown specialization;
1624 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001625 bool DependentID = false;
1626 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1627 Name.getCXXNameType()->isDependentType()) {
1628 DependentID = true;
1629 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001630 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001631 if (RequireCompleteDeclContext(SS, DC))
1632 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001633 } else {
1634 DependentID = true;
1635 }
1636 }
1637
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001638 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001640 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001641
Fariborz Jahanian86151342010-07-22 23:33:21 +00001642 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001643 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001644 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001645 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001646 // Lookup the template name again to correctly establish the context in
1647 // which it was found. This is really unfortunate as we already did the
1648 // lookup to determine that it was a template name in the first place. If
1649 // this becomes a performance hit, we can work harder to preserve those
1650 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001651 bool MemberOfUnknownSpecialization;
1652 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1653 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001654
1655 if (MemberOfUnknownSpecialization ||
1656 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1657 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1658 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001659 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001660 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001661 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001662
Douglas Gregora5226932011-02-04 13:35:07 +00001663 // If the result might be in a dependent base class, this is a dependent
1664 // id-expression.
1665 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1666 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1667 TemplateArgs);
1668
John McCalle66edc12009-11-24 19:00:30 +00001669 // If this reference is in an Objective-C method, then we need to do
1670 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001671 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001672 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001673 if (E.isInvalid())
1674 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001675
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001676 if (Expr *Ex = E.takeAs<Expr>())
1677 return Owned(Ex);
1678
1679 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001680 if (getLangOptions().ObjCDefaultSynthProperties &&
1681 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001682 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1683 if (const ObjCPropertyDecl *Property =
1684 canSynthesizeProvisionalIvar(II)) {
1685 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1686 Diag(Property->getLocation(), diag::note_property_declare);
1687 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001688 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1689 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001690 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001691 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001692 // for further use, this must be set to false if in class method.
1693 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001694 }
Chris Lattner59a25942008-03-31 00:36:02 +00001695 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001696
John McCalle66edc12009-11-24 19:00:30 +00001697 if (R.isAmbiguous())
1698 return ExprError();
1699
Douglas Gregor171c45a2009-02-18 21:56:37 +00001700 // Determine whether this name might be a candidate for
1701 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001702 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001703
John McCalle66edc12009-11-24 19:00:30 +00001704 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001705 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001706 // in C90, extension in C99, forbidden in C++).
1707 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1708 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1709 if (D) R.addDecl(D);
1710 }
1711
1712 // If this name wasn't predeclared and if this is not a function
1713 // call, diagnose the problem.
1714 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001715 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001716 return ExprError();
1717
1718 assert(!R.empty() &&
1719 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001720
1721 // If we found an Objective-C instance variable, let
1722 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001723 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001724 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1725 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001726 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001727 assert(E.isInvalid() || E.get());
1728 return move(E);
1729 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001730 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
John McCalle66edc12009-11-24 19:00:30 +00001733 // This is guaranteed from this point on.
1734 assert(!R.empty() || ADL);
1735
John McCall2d74de92009-12-01 22:10:20 +00001736 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001737 // C++ [class.mfct.non-static]p3:
1738 // When an id-expression that is not part of a class member access
1739 // syntax and not used to form a pointer to member is used in the
1740 // body of a non-static member function of class X, if name lookup
1741 // resolves the name in the id-expression to a non-static non-type
1742 // member of some class C, the id-expression is transformed into a
1743 // class member access expression using (*this) as the
1744 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001745 //
1746 // But we don't actually need to do this for '&' operands if R
1747 // resolved to a function or overloaded function set, because the
1748 // expression is ill-formed if it actually works out to be a
1749 // non-static member function:
1750 //
1751 // C++ [expr.ref]p4:
1752 // Otherwise, if E1.E2 refers to a non-static member function. . .
1753 // [t]he expression can be used only as the left-hand operand of a
1754 // member function call.
1755 //
1756 // There are other safeguards against such uses, but it's important
1757 // to get this right here so that we don't end up making a
1758 // spuriously dependent expression if we're inside a dependent
1759 // instance method.
John McCall57500772009-12-16 12:17:52 +00001760 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001761 bool MightBeImplicitMember;
1762 if (!isAddressOfOperand)
1763 MightBeImplicitMember = true;
1764 else if (!SS.isEmpty())
1765 MightBeImplicitMember = false;
1766 else if (R.isOverloadedResult())
1767 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001768 else if (R.isUnresolvableResult())
1769 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001770 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001771 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1772 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001773
1774 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001775 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001776 }
1777
John McCalle66edc12009-11-24 19:00:30 +00001778 if (TemplateArgs)
1779 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001780
John McCalle66edc12009-11-24 19:00:30 +00001781 return BuildDeclarationNameExpr(SS, R, ADL);
1782}
1783
John McCall57500772009-12-16 12:17:52 +00001784/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001785ExprResult
John McCall57500772009-12-16 12:17:52 +00001786Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1787 LookupResult &R,
1788 const TemplateArgumentListInfo *TemplateArgs) {
1789 switch (ClassifyImplicitMemberAccess(*this, R)) {
1790 case IMA_Instance:
1791 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1792
John McCall57500772009-12-16 12:17:52 +00001793 case IMA_Mixed:
1794 case IMA_Mixed_Unrelated:
1795 case IMA_Unresolved:
1796 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1797
1798 case IMA_Static:
1799 case IMA_Mixed_StaticContext:
1800 case IMA_Unresolved_StaticContext:
1801 if (TemplateArgs)
1802 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1803 return BuildDeclarationNameExpr(SS, R, false);
1804
1805 case IMA_Error_StaticContext:
1806 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001807 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1808 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001809 return ExprError();
1810 }
1811
1812 llvm_unreachable("unexpected instance member access kind");
1813 return ExprError();
1814}
1815
John McCall10eae182009-11-30 22:42:35 +00001816/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1817/// declaration name, generally during template instantiation.
1818/// There's a large number of things which don't need to be done along
1819/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001820ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001821Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001822 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001823 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001824 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001825 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001826
John McCall0b66eb32010-05-01 00:40:08 +00001827 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001828 return ExprError();
1829
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001830 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001831 LookupQualifiedName(R, DC);
1832
1833 if (R.isAmbiguous())
1834 return ExprError();
1835
1836 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001837 Diag(NameInfo.getLoc(), diag::err_no_member)
1838 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001839 return ExprError();
1840 }
1841
1842 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1843}
1844
1845/// LookupInObjCMethod - The parser has read a name in, and Sema has
1846/// detected that we're currently inside an ObjC method. Perform some
1847/// additional lookup.
1848///
1849/// Ideally, most of this would be done by lookup, but there's
1850/// actually quite a lot of extra work involved.
1851///
1852/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001853ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001854Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001855 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001856 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001857 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001858
John McCalle66edc12009-11-24 19:00:30 +00001859 // There are two cases to handle here. 1) scoped lookup could have failed,
1860 // in which case we should look for an ivar. 2) scoped lookup could have
1861 // found a decl, but that decl is outside the current instance method (i.e.
1862 // a global variable). In these two cases, we do a lookup for an ivar with
1863 // this name, if the lookup sucedes, we replace it our current decl.
1864
1865 // If we're in a class method, we don't normally want to look for
1866 // ivars. But if we don't find anything else, and there's an
1867 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001868 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001869
1870 bool LookForIvars;
1871 if (Lookup.empty())
1872 LookForIvars = true;
1873 else if (IsClassMethod)
1874 LookForIvars = false;
1875 else
1876 LookForIvars = (Lookup.isSingleResult() &&
1877 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001878 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001879 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001880 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001881 ObjCInterfaceDecl *ClassDeclared;
1882 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1883 // Diagnose using an ivar in a class method.
1884 if (IsClassMethod)
1885 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1886 << IV->getDeclName());
1887
1888 // If we're referencing an invalid decl, just return this as a silent
1889 // error node. The error diagnostic was already emitted on the decl.
1890 if (IV->isInvalidDecl())
1891 return ExprError();
1892
1893 // Check if referencing a field with __attribute__((deprecated)).
1894 if (DiagnoseUseOfDecl(IV, Loc))
1895 return ExprError();
1896
1897 // Diagnose the use of an ivar outside of the declaring class.
1898 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1899 ClassDeclared != IFace)
1900 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1901
1902 // FIXME: This should use a new expr for a direct reference, don't
1903 // turn this into Self->ivar, just return a BareIVarExpr or something.
1904 IdentifierInfo &II = Context.Idents.get("self");
1905 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001906 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001907 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001908 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001909 SelfName, false, false);
1910 if (SelfExpr.isInvalid())
1911 return ExprError();
1912
John Wiegley01296292011-04-08 18:41:53 +00001913 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1914 if (SelfExpr.isInvalid())
1915 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001916
John McCalle66edc12009-11-24 19:00:30 +00001917 MarkDeclarationReferenced(Loc, IV);
1918 return Owned(new (Context)
1919 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001920 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001921 }
Chris Lattner87313662010-04-12 05:10:17 +00001922 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001923 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001924 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001925 ObjCInterfaceDecl *ClassDeclared;
1926 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1927 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1928 IFace == ClassDeclared)
1929 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1930 }
1931 }
1932
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001933 if (Lookup.empty() && II && AllowBuiltinCreation) {
1934 // FIXME. Consolidate this with similar code in LookupName.
1935 if (unsigned BuiltinID = II->getBuiltinID()) {
1936 if (!(getLangOptions().CPlusPlus &&
1937 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1938 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1939 S, Lookup.isForRedeclaration(),
1940 Lookup.getNameLoc());
1941 if (D) Lookup.addDecl(D);
1942 }
1943 }
1944 }
John McCalle66edc12009-11-24 19:00:30 +00001945 // Sentinel value saying that we didn't do anything special.
1946 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001947}
John McCalld14a8642009-11-21 08:51:07 +00001948
John McCall16df1e52010-03-30 21:47:33 +00001949/// \brief Cast a base object to a member's actual type.
1950///
1951/// Logically this happens in three phases:
1952///
1953/// * First we cast from the base type to the naming class.
1954/// The naming class is the class into which we were looking
1955/// when we found the member; it's the qualifier type if a
1956/// qualifier was provided, and otherwise it's the base type.
1957///
1958/// * Next we cast from the naming class to the declaring class.
1959/// If the member we found was brought into a class's scope by
1960/// a using declaration, this is that class; otherwise it's
1961/// the class declaring the member.
1962///
1963/// * Finally we cast from the declaring class to the "true"
1964/// declaring class of the member. This conversion does not
1965/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001966ExprResult
1967Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001969 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001970 NamedDecl *Member) {
1971 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1972 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001973 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001975 QualType DestRecordType;
1976 QualType DestType;
1977 QualType FromRecordType;
1978 QualType FromType = From->getType();
1979 bool PointerConversions = false;
1980 if (isa<FieldDecl>(Member)) {
1981 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001982
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001983 if (FromType->getAs<PointerType>()) {
1984 DestType = Context.getPointerType(DestRecordType);
1985 FromRecordType = FromType->getPointeeType();
1986 PointerConversions = true;
1987 } else {
1988 DestType = DestRecordType;
1989 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001990 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001991 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1992 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001993 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001994
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 DestType = Method->getThisType(Context);
1996 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001997
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 if (FromType->getAs<PointerType>()) {
1999 FromRecordType = FromType->getPointeeType();
2000 PointerConversions = true;
2001 } else {
2002 FromRecordType = FromType;
2003 DestType = DestRecordType;
2004 }
2005 } else {
2006 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002007 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002009
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002010 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002011 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002012
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013 // If the unqualified types are the same, no conversion is necessary.
2014 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002015 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002016
John McCall16df1e52010-03-30 21:47:33 +00002017 SourceRange FromRange = From->getSourceRange();
2018 SourceLocation FromLoc = FromRange.getBegin();
2019
John McCall2536c6d2010-08-25 10:28:54 +00002020 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002021
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002023 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002024 // class name.
2025 //
2026 // If the member was a qualified name and the qualified referred to a
2027 // specific base subobject type, we'll cast to that intermediate type
2028 // first and then to the object in which the member is declared. That allows
2029 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2030 //
2031 // class Base { public: int x; };
2032 // class Derived1 : public Base { };
2033 // class Derived2 : public Base { };
2034 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2035 //
2036 // void VeryDerived::f() {
2037 // x = 17; // error: ambiguous base subobjects
2038 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2039 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002040 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002041 QualType QType = QualType(Qualifier->getAsType(), 0);
2042 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2043 assert(QType->isRecordType() && "lookup done with non-record type");
2044
2045 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2046
2047 // In C++98, the qualifier type doesn't actually have to be a base
2048 // type of the object type, in which case we just ignore it.
2049 // Otherwise build the appropriate casts.
2050 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002051 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002052 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002053 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002054 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002055
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002056 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002057 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002058 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2059 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002060
2061 FromType = QType;
2062 FromRecordType = QRecordType;
2063
2064 // If the qualifier type was the same as the destination type,
2065 // we're done.
2066 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002067 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002068 }
2069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002070
John McCall16df1e52010-03-30 21:47:33 +00002071 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002072
John McCall16df1e52010-03-30 21:47:33 +00002073 // If we actually found the member through a using declaration, cast
2074 // down to the using declaration's type.
2075 //
2076 // Pointer equality is fine here because only one declaration of a
2077 // class ever has member declarations.
2078 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2079 assert(isa<UsingShadowDecl>(FoundDecl));
2080 QualType URecordType = Context.getTypeDeclType(
2081 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2082
2083 // We only need to do this if the naming-class to declaring-class
2084 // conversion is non-trivial.
2085 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2086 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002087 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002088 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002089 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002090 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002091
John McCall16df1e52010-03-30 21:47:33 +00002092 QualType UType = URecordType;
2093 if (PointerConversions)
2094 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002095 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2096 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002097 FromType = UType;
2098 FromRecordType = URecordType;
2099 }
2100
2101 // We don't do access control for the conversion from the
2102 // declaring class to the true declaring class.
2103 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002104 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002105
John McCallcf142162010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002107 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2108 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002109 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002110 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002111
John Wiegley01296292011-04-08 18:41:53 +00002112 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2113 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002114}
Douglas Gregor3256d042009-06-30 15:47:41 +00002115
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002116/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002117static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002118 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002119 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002120 const DeclarationNameInfo &MemberNameInfo,
2121 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002122 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002123 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002124 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002125 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002126 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002127}
2128
John McCallfeb624a2010-11-23 20:48:44 +00002129static ExprResult
2130BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2131 const CXXScopeSpec &SS, FieldDecl *Field,
2132 DeclAccessPair FoundDecl,
2133 const DeclarationNameInfo &MemberNameInfo) {
2134 // x.a is an l-value if 'a' has a reference type. Otherwise:
2135 // x.a is an l-value/x-value/pr-value if the base is (and note
2136 // that *x is always an l-value), except that if the base isn't
2137 // an ordinary object then we must have an rvalue.
2138 ExprValueKind VK = VK_LValue;
2139 ExprObjectKind OK = OK_Ordinary;
2140 if (!IsArrow) {
2141 if (BaseExpr->getObjectKind() == OK_Ordinary)
2142 VK = BaseExpr->getValueKind();
2143 else
2144 VK = VK_RValue;
2145 }
2146 if (VK != VK_RValue && Field->isBitField())
2147 OK = OK_BitField;
2148
2149 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2150 QualType MemberType = Field->getType();
2151 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2152 MemberType = Ref->getPointeeType();
2153 VK = VK_LValue;
2154 } else {
2155 QualType BaseType = BaseExpr->getType();
2156 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2157
2158 Qualifiers BaseQuals = BaseType.getQualifiers();
2159
2160 // GC attributes are never picked up by members.
2161 BaseQuals.removeObjCGCAttr();
2162
2163 // CVR attributes from the base are picked up by members,
2164 // except that 'mutable' members don't pick up 'const'.
2165 if (Field->isMutable()) BaseQuals.removeConst();
2166
2167 Qualifiers MemberQuals
2168 = S.Context.getCanonicalType(MemberType).getQualifiers();
2169
2170 // TR 18037 does not allow fields to be declared with address spaces.
2171 assert(!MemberQuals.hasAddressSpace());
2172
2173 Qualifiers Combined = BaseQuals + MemberQuals;
2174 if (Combined != MemberQuals)
2175 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2176 }
2177
2178 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002179 ExprResult Base =
2180 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2181 FoundDecl, Field);
2182 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002183 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002184 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002185 Field, FoundDecl, MemberNameInfo,
2186 MemberType, VK, OK));
2187}
2188
John McCall2d74de92009-12-01 22:10:20 +00002189/// Builds an implicit member access expression. The current context
2190/// is known to be an instance method, and the given unqualified lookup
2191/// set is known to contain only instance members, at least one of which
2192/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002193ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002194Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2195 LookupResult &R,
2196 const TemplateArgumentListInfo *TemplateArgs,
2197 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002198 assert(!R.empty() && !R.isAmbiguous());
2199
John McCallf3a88602011-02-03 08:15:49 +00002200 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002201
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002202 // We may have found a field within an anonymous union or struct
2203 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002204 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002205 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002206 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002207
John McCallf3a88602011-02-03 08:15:49 +00002208 // If this is known to be an instance access, go ahead and build an
2209 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002210 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002211 CXXMethodDecl *method = tryCaptureCXXThis();
2212 assert(method && "didn't correctly pre-flight capture of 'this'");
2213
2214 QualType thisType = method->getThisType(Context);
2215 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002216 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002217 SourceLocation Loc = R.getNameLoc();
2218 if (SS.getRange().isValid())
2219 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002220 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002221 }
2222
John McCallf3a88602011-02-03 08:15:49 +00002223 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002224 /*OpLoc*/ SourceLocation(),
2225 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002226 SS,
2227 /*FirstQualifierInScope*/ 0,
2228 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002229}
2230
John McCalle66edc12009-11-24 19:00:30 +00002231bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002232 const LookupResult &R,
2233 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002234 // Only when used directly as the postfix-expression of a call.
2235 if (!HasTrailingLParen)
2236 return false;
2237
2238 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002239 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002240 return false;
2241
2242 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002243 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002244 return false;
2245
2246 // Turn off ADL when we find certain kinds of declarations during
2247 // normal lookup:
2248 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2249 NamedDecl *D = *I;
2250
2251 // C++0x [basic.lookup.argdep]p3:
2252 // -- a declaration of a class member
2253 // Since using decls preserve this property, we check this on the
2254 // original decl.
John McCall57500772009-12-16 12:17:52 +00002255 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002256 return false;
2257
2258 // C++0x [basic.lookup.argdep]p3:
2259 // -- a block-scope function declaration that is not a
2260 // using-declaration
2261 // NOTE: we also trigger this for function templates (in fact, we
2262 // don't check the decl type at all, since all other decl types
2263 // turn off ADL anyway).
2264 if (isa<UsingShadowDecl>(D))
2265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2266 else if (D->getDeclContext()->isFunctionOrMethod())
2267 return false;
2268
2269 // C++0x [basic.lookup.argdep]p3:
2270 // -- a declaration that is neither a function or a function
2271 // template
2272 // And also for builtin functions.
2273 if (isa<FunctionDecl>(D)) {
2274 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2275
2276 // But also builtin functions.
2277 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2278 return false;
2279 } else if (!isa<FunctionTemplateDecl>(D))
2280 return false;
2281 }
2282
2283 return true;
2284}
2285
2286
John McCalld14a8642009-11-21 08:51:07 +00002287/// Diagnoses obvious problems with the use of the given declaration
2288/// as an expression. This is only actually called for lookups that
2289/// were not overloaded, and it doesn't promise that the declaration
2290/// will in fact be used.
2291static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2292 if (isa<TypedefDecl>(D)) {
2293 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2294 return true;
2295 }
2296
2297 if (isa<ObjCInterfaceDecl>(D)) {
2298 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2299 return true;
2300 }
2301
2302 if (isa<NamespaceDecl>(D)) {
2303 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2304 return true;
2305 }
2306
2307 return false;
2308}
2309
John McCalldadc5752010-08-24 06:29:42 +00002310ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002311Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002312 LookupResult &R,
2313 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002314 // If this is a single, fully-resolved result and we don't need ADL,
2315 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002316 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002317 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2318 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002319
2320 // We only need to check the declaration if there's exactly one
2321 // result, because in the overloaded case the results can only be
2322 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002323 if (R.isSingleResult() &&
2324 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002325 return ExprError();
2326
John McCall58cc69d2010-01-27 01:50:18 +00002327 // Otherwise, just build an unresolved lookup expression. Suppress
2328 // any lookup-related diagnostics; we'll hash these out later, when
2329 // we've picked a target.
2330 R.suppressDiagnostics();
2331
John McCalld14a8642009-11-21 08:51:07 +00002332 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002333 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002334 SS.getWithLocInContext(Context),
2335 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002336 NeedsADL, R.isOverloadedResult(),
2337 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002338
2339 return Owned(ULE);
2340}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002341
John McCalld14a8642009-11-21 08:51:07 +00002342/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002343ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002344Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002345 const DeclarationNameInfo &NameInfo,
2346 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002347 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002348 assert(!isa<FunctionTemplateDecl>(D) &&
2349 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002350
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002351 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002352 if (CheckDeclInExpr(*this, Loc, D))
2353 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002354
Douglas Gregore7488b92009-12-01 16:58:18 +00002355 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2356 // Specifically diagnose references to class templates that are missing
2357 // a template argument list.
2358 Diag(Loc, diag::err_template_decl_ref)
2359 << Template << SS.getRange();
2360 Diag(Template->getLocation(), diag::note_template_decl_here);
2361 return ExprError();
2362 }
2363
2364 // Make sure that we're referring to a value.
2365 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2366 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002367 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002368 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002369 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002370 return ExprError();
2371 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002372
Douglas Gregor171c45a2009-02-18 21:56:37 +00002373 // Check whether this declaration can be used. Note that we suppress
2374 // this check when we're going to perform argument-dependent lookup
2375 // on this function name, because this might not be the function
2376 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002377 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002378 return ExprError();
2379
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002380 // Only create DeclRefExpr's for valid Decl's.
2381 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002382 return ExprError();
2383
John McCallf3a88602011-02-03 08:15:49 +00002384 // Handle members of anonymous structs and unions. If we got here,
2385 // and the reference is to a class member indirect field, then this
2386 // must be the subject of a pointer-to-member expression.
2387 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2388 if (!indirectField->isCXXClassMember())
2389 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2390 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002391
Chris Lattner2a9d9892008-10-20 05:16:36 +00002392 // If the identifier reference is inside a block, and it refers to a value
2393 // that is outside the block, create a BlockDeclRefExpr instead of a
2394 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2395 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002396 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002397 // We do not do this for things like enum constants, global variables, etc,
2398 // as they do not get snapshotted.
2399 //
John McCall351762c2011-02-07 10:33:21 +00002400 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002401 case CR_Error:
2402 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002403
John McCallc63de662011-02-02 13:00:07 +00002404 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002405 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2406 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2407
2408 case CR_CaptureByRef:
2409 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2410 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002411
2412 case CR_NoCapture: {
2413 // If this reference is not in a block or if the referenced
2414 // variable is within the block, create a normal DeclRefExpr.
2415
2416 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002417 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002418
2419 switch (D->getKind()) {
2420 // Ignore all the non-ValueDecl kinds.
2421#define ABSTRACT_DECL(kind)
2422#define VALUE(type, base)
2423#define DECL(type, base) \
2424 case Decl::type:
2425#include "clang/AST/DeclNodes.inc"
2426 llvm_unreachable("invalid value decl kind");
2427 return ExprError();
2428
2429 // These shouldn't make it here.
2430 case Decl::ObjCAtDefsField:
2431 case Decl::ObjCIvar:
2432 llvm_unreachable("forming non-member reference to ivar?");
2433 return ExprError();
2434
2435 // Enum constants are always r-values and never references.
2436 // Unresolved using declarations are dependent.
2437 case Decl::EnumConstant:
2438 case Decl::UnresolvedUsingValue:
2439 valueKind = VK_RValue;
2440 break;
2441
2442 // Fields and indirect fields that got here must be for
2443 // pointer-to-member expressions; we just call them l-values for
2444 // internal consistency, because this subexpression doesn't really
2445 // exist in the high-level semantics.
2446 case Decl::Field:
2447 case Decl::IndirectField:
2448 assert(getLangOptions().CPlusPlus &&
2449 "building reference to field in C?");
2450
2451 // These can't have reference type in well-formed programs, but
2452 // for internal consistency we do this anyway.
2453 type = type.getNonReferenceType();
2454 valueKind = VK_LValue;
2455 break;
2456
2457 // Non-type template parameters are either l-values or r-values
2458 // depending on the type.
2459 case Decl::NonTypeTemplateParm: {
2460 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2461 type = reftype->getPointeeType();
2462 valueKind = VK_LValue; // even if the parameter is an r-value reference
2463 break;
2464 }
2465
2466 // For non-references, we need to strip qualifiers just in case
2467 // the template parameter was declared as 'const int' or whatever.
2468 valueKind = VK_RValue;
2469 type = type.getUnqualifiedType();
2470 break;
2471 }
2472
2473 case Decl::Var:
2474 // In C, "extern void blah;" is valid and is an r-value.
2475 if (!getLangOptions().CPlusPlus &&
2476 !type.hasQualifiers() &&
2477 type->isVoidType()) {
2478 valueKind = VK_RValue;
2479 break;
2480 }
2481 // fallthrough
2482
2483 case Decl::ImplicitParam:
2484 case Decl::ParmVar:
2485 // These are always l-values.
2486 valueKind = VK_LValue;
2487 type = type.getNonReferenceType();
2488 break;
2489
2490 case Decl::Function: {
2491 // Functions are l-values in C++.
2492 if (getLangOptions().CPlusPlus) {
2493 valueKind = VK_LValue;
2494 break;
2495 }
2496
2497 // C99 DR 316 says that, if a function type comes from a
2498 // function definition (without a prototype), that type is only
2499 // used for checking compatibility. Therefore, when referencing
2500 // the function, we pretend that we don't have the full function
2501 // type.
2502 if (!cast<FunctionDecl>(VD)->hasPrototype())
2503 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2504 type = Context.getFunctionNoProtoType(proto->getResultType(),
2505 proto->getExtInfo());
2506
2507 // Functions are r-values in C.
2508 valueKind = VK_RValue;
2509 break;
2510 }
2511
2512 case Decl::CXXMethod:
2513 // C++ methods are l-values if static, r-values if non-static.
2514 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2515 valueKind = VK_LValue;
2516 break;
2517 }
2518 // fallthrough
2519
2520 case Decl::CXXConversion:
2521 case Decl::CXXDestructor:
2522 case Decl::CXXConstructor:
2523 valueKind = VK_RValue;
2524 break;
2525 }
2526
2527 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2528 }
2529
John McCallc63de662011-02-02 13:00:07 +00002530 }
John McCall7decc9e2010-11-18 06:31:45 +00002531
John McCall351762c2011-02-07 10:33:21 +00002532 llvm_unreachable("unknown capture result");
2533 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002534}
Chris Lattnere168f762006-11-10 05:29:30 +00002535
John McCalldadc5752010-08-24 06:29:42 +00002536ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002537 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002538 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002539
Chris Lattnere168f762006-11-10 05:29:30 +00002540 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002541 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002542 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2543 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2544 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002545 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002546
Chris Lattnera81a0272008-01-12 08:14:25 +00002547 // Pre-defined identifiers are of type char[x], where x is the length of the
2548 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002549
Anders Carlsson2fb08242009-09-08 18:24:21 +00002550 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002551 if (!currentDecl && getCurBlock())
2552 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002553 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002554 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002555 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002556 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002557
Anders Carlsson0b209a82009-09-11 01:22:35 +00002558 QualType ResTy;
2559 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2560 ResTy = Context.DependentTy;
2561 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002562 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002563
Anders Carlsson0b209a82009-09-11 01:22:35 +00002564 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002565 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002566 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2567 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002568 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002569}
2570
John McCalldadc5752010-08-24 06:29:42 +00002571ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002572 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002573 bool Invalid = false;
2574 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2575 if (Invalid)
2576 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002577
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002578 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2579 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002580 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002581 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002582
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002583 QualType Ty;
2584 if (!getLangOptions().CPlusPlus)
2585 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2586 else if (Literal.isWide())
2587 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002588 else if (Literal.isMultiChar())
2589 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002590 else
2591 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002592
Sebastian Redl20614a72009-01-20 22:23:13 +00002593 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2594 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002595 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002596}
2597
John McCalldadc5752010-08-24 06:29:42 +00002598ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002599 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002600 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2601 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002602 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002603 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002604 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002605 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002606 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002607
Chris Lattner23b7eb62007-06-15 23:05:46 +00002608 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002609 // Add padding so that NumericLiteralParser can overread by one character.
2610 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002611 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002612
Chris Lattner67ca9252007-05-21 01:08:44 +00002613 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002614 bool Invalid = false;
2615 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2616 if (Invalid)
2617 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002618
Mike Stump11289f42009-09-09 15:08:12 +00002619 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002620 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002621 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622 return ExprError();
2623
Chris Lattner1c20a172007-08-26 03:42:43 +00002624 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002625
Chris Lattner1c20a172007-08-26 03:42:43 +00002626 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002627 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002628 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002629 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002630 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002631 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002632 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002633 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002634
2635 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2636
John McCall53b93a02009-12-24 09:08:04 +00002637 using llvm::APFloat;
2638 APFloat Val(Format);
2639
2640 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002641
2642 // Overflow is always an error, but underflow is only an error if
2643 // we underflowed to zero (APFloat reports denormals as underflow).
2644 if ((result & APFloat::opOverflow) ||
2645 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002646 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002647 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002648 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002649 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002650 APFloat::getLargest(Format).toString(buffer);
2651 } else {
John McCall62abc942010-02-26 23:35:57 +00002652 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002653 APFloat::getSmallest(Format).toString(buffer);
2654 }
2655
2656 Diag(Tok.getLocation(), diagnostic)
2657 << Ty
2658 << llvm::StringRef(buffer.data(), buffer.size());
2659 }
2660
2661 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002662 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002663
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002664 if (Ty == Context.DoubleTy) {
2665 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002666 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002667 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2668 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002669 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002670 }
2671 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002672 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002673 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002674 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002675 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002676
Neil Boothac582c52007-08-29 22:00:19 +00002677 // long long is a C99 feature.
2678 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002679 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002680 Diag(Tok.getLocation(), diag::ext_longlong);
2681
Chris Lattner67ca9252007-05-21 01:08:44 +00002682 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002683 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002684
Chris Lattner67ca9252007-05-21 01:08:44 +00002685 if (Literal.GetIntegerValue(ResultVal)) {
2686 // If this value didn't fit into uintmax_t, warn and force to ull.
2687 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002688 Ty = Context.UnsignedLongLongTy;
2689 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002690 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002691 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002692 // If this value fits into a ULL, try to figure out what else it fits into
2693 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002694
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2696 // be an unsigned int.
2697 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2698
2699 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002701 if (!Literal.isLong && !Literal.isLongLong) {
2702 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002703 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002704
Chris Lattner67ca9252007-05-21 01:08:44 +00002705 // Does it fit in a unsigned int?
2706 if (ResultVal.isIntN(IntSize)) {
2707 // Does it fit in a signed int?
2708 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002709 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002710 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002711 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002712 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002713 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002714 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002715
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002719
Chris Lattner67ca9252007-05-21 01:08:44 +00002720 // Does it fit in a unsigned long?
2721 if (ResultVal.isIntN(LongSize)) {
2722 // Does it fit in a signed long?
2723 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002724 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002725 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002726 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002727 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002728 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002729 }
2730
Chris Lattner67ca9252007-05-21 01:08:44 +00002731 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002732 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002733 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002734
Chris Lattner67ca9252007-05-21 01:08:44 +00002735 // Does it fit in a unsigned long long?
2736 if (ResultVal.isIntN(LongLongSize)) {
2737 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002738 // To be compatible with MSVC, hex integer literals ending with the
2739 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002740 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2741 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002742 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002743 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002744 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002745 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002746 }
2747 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002748
Chris Lattner67ca9252007-05-21 01:08:44 +00002749 // If we still couldn't decide a type, we probably have something that
2750 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002751 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002752 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002753 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002754 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002755 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002756
Chris Lattner55258cf2008-05-09 05:59:00 +00002757 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002758 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002759 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002760 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002761 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002762
Chris Lattner1c20a172007-08-26 03:42:43 +00002763 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2764 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002765 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002766 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002767
2768 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002769}
2770
John McCalldadc5752010-08-24 06:29:42 +00002771ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002772 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002773 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002774 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002775}
2776
Steve Naroff71b59a92007-06-04 22:22:31 +00002777/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002778/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002779bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2780 SourceLocation OpLoc,
2781 SourceRange ExprRange,
2782 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002783 if (exprType->isDependentType())
2784 return false;
2785
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002786 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2787 // the result is the size of the referenced type."
2788 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2789 // result shall be the alignment of the referenced type."
2790 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2791 exprType = Ref->getPointeeType();
2792
Peter Collingbournee190dee2011-03-11 19:24:49 +00002793 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2794 // scalar or vector data type argument..."
2795 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2796 // type (C99 6.2.5p18) or void.
2797 if (ExprKind == UETT_VecStep) {
2798 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2799 exprType->isVectorType())) {
2800 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2801 << exprType << ExprRange;
2802 return true;
2803 }
2804 }
2805
Steve Naroff043d45d2007-05-15 02:32:35 +00002806 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002807 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002808 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002809 if (ExprKind == UETT_SizeOf)
2810 Diag(OpLoc, diag::ext_sizeof_function_type)
2811 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002812 return false;
2813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
Peter Collingbournee190dee2011-03-11 19:24:49 +00002815 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2816 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002817 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002818 if (ExprKind != UETT_VecStep)
2819 Diag(OpLoc, diag::ext_sizeof_void_type)
2820 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002821 return false;
2822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Chris Lattner62975a72009-04-24 00:30:45 +00002824 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002825 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002826 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002827 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002828
Chris Lattner62975a72009-04-24 00:30:45 +00002829 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002830 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002831 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002832 << exprType << (ExprKind == UETT_SizeOf)
2833 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002834 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002835 }
Mike Stump11289f42009-09-09 15:08:12 +00002836
Chris Lattner62975a72009-04-24 00:30:45 +00002837 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002838}
2839
John McCall36e7fe32010-10-12 00:20:44 +00002840static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2841 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002842 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002843
Mike Stump11289f42009-09-09 15:08:12 +00002844 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002845 if (isa<DeclRefExpr>(E))
2846 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002847
2848 // Cannot know anything else if the expression is dependent.
2849 if (E->isTypeDependent())
2850 return false;
2851
Douglas Gregor71235ec2009-05-02 02:18:30 +00002852 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002853 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002854 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002855 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002856
2857 // Alignment of a field access is always okay, so long as it isn't a
2858 // bit-field.
2859 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002860 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002861 return false;
2862
Peter Collingbournee190dee2011-03-11 19:24:49 +00002863 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2864 UETT_AlignOf);
2865}
2866
2867bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2868 SourceRange ExprRange) {
2869 E = E->IgnoreParens();
2870
2871 // Cannot know anything else if the expression is dependent.
2872 if (E->isTypeDependent())
2873 return false;
2874
2875 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2876 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002877}
2878
Douglas Gregor0950e412009-03-13 21:01:28 +00002879/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002880ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002881Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2882 SourceLocation OpLoc,
2883 UnaryExprOrTypeTrait ExprKind,
2884 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002885 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002886 return ExprError();
2887
John McCallbcd03502009-12-07 02:54:59 +00002888 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002889
Douglas Gregor0950e412009-03-13 21:01:28 +00002890 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002891 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002892 return ExprError();
2893
2894 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002895 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2896 Context.getSizeType(),
2897 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002898}
2899
2900/// \brief Build a sizeof or alignof expression given an expression
2901/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002902ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002903Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2904 UnaryExprOrTypeTrait ExprKind,
2905 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 // Verify that the operand is valid.
2907 bool isInvalid = false;
2908 if (E->isTypeDependent()) {
2909 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002910 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002911 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002912 } else if (ExprKind == UETT_VecStep) {
2913 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002914 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002915 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2916 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002917 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002918 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00002919 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002920 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002921 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002922 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2923 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002924 }
2925
2926 if (isInvalid)
2927 return ExprError();
2928
2929 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002930 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2931 Context.getSizeType(),
2932 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002933}
2934
Peter Collingbournee190dee2011-03-11 19:24:49 +00002935/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2936/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002937/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002938ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002939Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2940 UnaryExprOrTypeTrait ExprKind, bool isType,
2941 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002942 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002943 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002944
Sebastian Redl6f282892008-11-11 17:56:53 +00002945 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002946 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002947 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002948 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002949 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002950
Douglas Gregor0950e412009-03-13 21:01:28 +00002951 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002952 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002953 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2954 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002955
Douglas Gregor0950e412009-03-13 21:01:28 +00002956 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002957}
2958
John Wiegley01296292011-04-08 18:41:53 +00002959static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002960 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002961 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002962 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002963
John McCall34376a62010-12-04 03:47:34 +00002964 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002965 if (V.get()->getObjectKind() != OK_Ordinary) {
2966 V = S.DefaultLvalueConversion(V.take());
2967 if (V.isInvalid())
2968 return QualType();
2969 }
John McCall34376a62010-12-04 03:47:34 +00002970
Chris Lattnere267f5d2007-08-26 05:39:26 +00002971 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002972 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002973 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Chris Lattnere267f5d2007-08-26 05:39:26 +00002975 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002976 if (V.get()->getType()->isArithmeticType())
2977 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002978
John McCall36226622010-10-12 02:09:17 +00002979 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002980 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002981 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002982 if (PR.get() != V.get()) {
2983 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002984 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002985 }
2986
Chris Lattnere267f5d2007-08-26 05:39:26 +00002987 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002988 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002989 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002990 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002991}
2992
2993
Chris Lattnere168f762006-11-10 05:29:30 +00002994
John McCalldadc5752010-08-24 06:29:42 +00002995ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002996Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002997 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002998 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002999 switch (Kind) {
3000 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003001 case tok::plusplus: Opc = UO_PostInc; break;
3002 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003003 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003004
John McCallb268a282010-08-23 23:25:46 +00003005 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003006}
3007
John McCall4bc41ae2010-11-18 19:01:18 +00003008/// Expressions of certain arbitrary types are forbidden by C from
3009/// having l-value type. These are:
3010/// - 'void', but not qualified void
3011/// - function types
3012///
3013/// The exact rule here is C99 6.3.2.1:
3014/// An lvalue is an expression with an object type or an incomplete
3015/// type other than void.
3016static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3017 return ((T->isVoidType() && !T.hasQualifiers()) ||
3018 T->isFunctionType());
3019}
3020
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
John McCallb268a282010-08-23 23:25:46 +00003022Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3023 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003024 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003025 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003026 if (Result.isInvalid()) return ExprError();
3027 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003028
John McCallb268a282010-08-23 23:25:46 +00003029 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Douglas Gregor40412ac2008-11-19 17:17:41 +00003031 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003032 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003033 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003034 Context.DependentTy,
3035 VK_LValue, OK_Ordinary,
3036 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003037 }
3038
Mike Stump11289f42009-09-09 15:08:12 +00003039 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003040 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003041 LHSExp->getType()->isEnumeralType() ||
3042 RHSExp->getType()->isRecordType() ||
3043 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003044 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003045 }
3046
John McCallb268a282010-08-23 23:25:46 +00003047 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003048}
3049
3050
John McCalldadc5752010-08-24 06:29:42 +00003051ExprResult
John McCallb268a282010-08-23 23:25:46 +00003052Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3053 Expr *Idx, SourceLocation RLoc) {
3054 Expr *LHSExp = Base;
3055 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003056
Chris Lattner36d572b2007-07-16 00:14:47 +00003057 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003058 if (!LHSExp->getType()->getAs<VectorType>()) {
3059 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3060 if (Result.isInvalid())
3061 return ExprError();
3062 LHSExp = Result.take();
3063 }
3064 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3065 if (Result.isInvalid())
3066 return ExprError();
3067 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003068
Chris Lattner36d572b2007-07-16 00:14:47 +00003069 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003070 ExprValueKind VK = VK_LValue;
3071 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003072
Steve Naroffc1aadb12007-03-28 21:49:40 +00003073 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003074 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003075 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003076 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003077 Expr *BaseExpr, *IndexExpr;
3078 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003079 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003083 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003086 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003087 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003088 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003089 BaseExpr = RHSExp;
3090 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003091 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003092 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003093 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003094 BaseExpr = LHSExp;
3095 IndexExpr = RHSExp;
3096 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003097 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003098 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003099 // Handle the uncommon case of "123[Ptr]".
3100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
3102 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003103 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003104 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003105 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003106 VK = LHSExp->getValueKind();
3107 if (VK != VK_RValue)
3108 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003109
Chris Lattner36d572b2007-07-16 00:14:47 +00003110 // FIXME: need to deal with const...
3111 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003112 } else if (LHSTy->isArrayType()) {
3113 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003114 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003115 // wasn't promoted because of the C90 rule that doesn't
3116 // allow promoting non-lvalue arrays. Warn, then
3117 // force the promotion here.
3118 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3119 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003120 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3121 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003122 LHSTy = LHSExp->getType();
3123
3124 BaseExpr = LHSExp;
3125 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003126 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003127 } else if (RHSTy->isArrayType()) {
3128 // Same as previous, except for 123[f().a] case
3129 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3130 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003131 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3132 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003133 RHSTy = RHSExp->getType();
3134
3135 BaseExpr = RHSExp;
3136 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003137 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003138 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003139 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3140 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003142 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003143 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003144 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3145 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003146
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003147 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003148 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3149 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003150 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3151
Douglas Gregorac1fb652009-03-24 19:52:54 +00003152 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003153 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3154 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003155 // incomplete types are not object types.
3156 if (ResultType->isFunctionType()) {
3157 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3158 << ResultType << BaseExpr->getSourceRange();
3159 return ExprError();
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003162 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3163 // GNU extension: subscripting on pointer to void
3164 Diag(LLoc, diag::ext_gnu_void_ptr)
3165 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003166
3167 // C forbids expressions of unqualified void type from being l-values.
3168 // See IsCForbiddenLValueType.
3169 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003170 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003171 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003172 PDiag(diag::err_subscript_incomplete_type)
3173 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003174 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003175
Chris Lattner62975a72009-04-24 00:30:45 +00003176 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003177 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003178 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3179 << ResultType << BaseExpr->getSourceRange();
3180 return ExprError();
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
John McCall4bc41ae2010-11-18 19:01:18 +00003183 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3184 !IsCForbiddenLValueType(Context, ResultType));
3185
Mike Stump4e1f26a2009-02-19 03:04:26 +00003186 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003187 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003188}
3189
John McCall4bc41ae2010-11-18 19:01:18 +00003190/// Check an ext-vector component access expression.
3191///
3192/// VK should be set in advance to the value kind of the base
3193/// expression.
3194static QualType
3195CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3196 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003197 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003198 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3199 // see FIXME there.
3200 //
3201 // FIXME: This logic can be greatly simplified by splitting it along
3202 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003203 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003204
Steve Narofff8fd09e2007-07-27 22:15:19 +00003205 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003206 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003207
Mike Stump4e1f26a2009-02-19 03:04:26 +00003208 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003209 // special names that indicate a subset of exactly half the elements are
3210 // to be selected.
3211 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003212
Nate Begemanbb70bf62009-01-18 01:47:54 +00003213 // This flag determines whether or not CompName has an 's' char prefix,
3214 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003215 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003216
John McCall4bc41ae2010-11-18 19:01:18 +00003217 bool HasRepeated = false;
3218 bool HasIndex[16] = {};
3219
3220 int Idx;
3221
Nate Begemanf322eab2008-05-09 06:41:27 +00003222 // Check that we've found one of the special components, or that the component
3223 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003224 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003225 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3226 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003227 } else if (!HexSwizzle &&
3228 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3229 do {
3230 if (HasIndex[Idx]) HasRepeated = true;
3231 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003232 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003233 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3234 } else {
3235 if (HexSwizzle) compStr++;
3236 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3237 if (HasIndex[Idx]) HasRepeated = true;
3238 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003239 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003240 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003241 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003242
Mike Stump4e1f26a2009-02-19 03:04:26 +00003243 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003244 // We didn't get to the end of the string. This means the component names
3245 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003246 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003247 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003248 return QualType();
3249 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003250
Nate Begemanbb70bf62009-01-18 01:47:54 +00003251 // Ensure no component accessor exceeds the width of the vector type it
3252 // operates on.
3253 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003254 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003255
3256 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003257 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003258
3259 while (*compStr) {
3260 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003261 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003262 << baseType << SourceRange(CompLoc);
3263 return QualType();
3264 }
3265 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003266 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003267
Steve Narofff8fd09e2007-07-27 22:15:19 +00003268 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003269 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003270 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003271 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003272 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003273 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003274 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003275 if (HexSwizzle)
3276 CompSize--;
3277
Steve Narofff8fd09e2007-07-27 22:15:19 +00003278 if (CompSize == 1)
3279 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003280
John McCall4bc41ae2010-11-18 19:01:18 +00003281 if (HasRepeated) VK = VK_RValue;
3282
3283 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003284 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003285 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003286 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3287 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3288 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003289 }
3290 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003291}
3292
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003293static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003294 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003295 const Selector &Sel,
3296 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003297 if (Member)
3298 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3299 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003300 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003301 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003302
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003303 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3304 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003305 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3306 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003307 return D;
3308 }
3309 return 0;
3310}
3311
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003312static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3313 IdentifierInfo *Member,
3314 const Selector &Sel,
3315 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003316 // Check protocols on qualified interfaces.
3317 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003318 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003319 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003320 if (Member)
3321 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3322 GDecl = PD;
3323 break;
3324 }
3325 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003326 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003327 GDecl = OMD;
3328 break;
3329 }
3330 }
3331 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003332 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003333 E = QIdTy->qual_end(); I != E; ++I) {
3334 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003335 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3336 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003337 if (GDecl)
3338 return GDecl;
3339 }
3340 }
3341 return GDecl;
3342}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003343
John McCalldadc5752010-08-24 06:29:42 +00003344ExprResult
John McCallb268a282010-08-23 23:25:46 +00003345Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003346 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003347 const CXXScopeSpec &SS,
3348 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003349 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003350 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003351 // Even in dependent contexts, try to diagnose base expressions with
3352 // obviously wrong types, e.g.:
3353 //
3354 // T* t;
3355 // t.f;
3356 //
3357 // In Obj-C++, however, the above expression is valid, since it could be
3358 // accessing the 'f' property if T is an Obj-C interface. The extra check
3359 // allows this, while still reporting an error if T is a struct pointer.
3360 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003361 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003362 if (PT && (!getLangOptions().ObjC1 ||
3363 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003364 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003365 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003366 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003367 return ExprError();
3368 }
3369 }
3370
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003371 assert(BaseType->isDependentType() ||
3372 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003373 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003374
3375 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3376 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003377 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003378 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003379 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003380 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003381 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003382}
3383
3384/// We know that the given qualified member reference points only to
3385/// declarations which do not belong to the static type of the base
3386/// expression. Diagnose the problem.
3387static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3388 Expr *BaseExpr,
3389 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003390 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003391 NamedDecl *rep,
3392 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003393 // If this is an implicit member access, use a different set of
3394 // diagnostics.
3395 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003396 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003397
John McCallf3a88602011-02-03 08:15:49 +00003398 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3399 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003400}
3401
3402// Check whether the declarations we found through a nested-name
3403// specifier in a member expression are actually members of the base
3404// type. The restriction here is:
3405//
3406// C++ [expr.ref]p2:
3407// ... In these cases, the id-expression shall name a
3408// member of the class or of one of its base classes.
3409//
3410// So it's perfectly legitimate for the nested-name specifier to name
3411// an unrelated class, and for us to find an overload set including
3412// decls from classes which are not superclasses, as long as the decl
3413// we actually pick through overload resolution is from a superclass.
3414bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3415 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003416 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003417 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003418 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3419 if (!BaseRT) {
3420 // We can't check this yet because the base type is still
3421 // dependent.
3422 assert(BaseType->isDependentType());
3423 return false;
3424 }
3425 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003426
3427 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003428 // If this is an implicit member reference and we find a
3429 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003430 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003431 return false;
John McCall10eae182009-11-30 22:42:35 +00003432
John McCall2d74de92009-12-01 22:10:20 +00003433 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003434 DeclContext *DC = (*I)->getDeclContext();
3435 while (DC->isTransparentContext())
3436 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003437
Douglas Gregora9c3e822010-07-28 22:27:52 +00003438 if (!DC->isRecord())
3439 continue;
3440
John McCall2d74de92009-12-01 22:10:20 +00003441 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003442 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003443
3444 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3445 return false;
3446 }
3447
John McCallf3a88602011-02-03 08:15:49 +00003448 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3449 R.getRepresentativeDecl(),
3450 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003451 return true;
3452}
3453
3454static bool
3455LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3456 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003457 SourceLocation OpLoc, CXXScopeSpec &SS,
3458 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003459 RecordDecl *RDecl = RTy->getDecl();
3460 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003461 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003462 << BaseRange))
3463 return true;
3464
John McCalle9cccd82010-06-16 08:42:20 +00003465 if (HasTemplateArgs) {
3466 // LookupTemplateName doesn't expect these both to exist simultaneously.
3467 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3468
3469 bool MOUS;
3470 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3471 return false;
3472 }
3473
John McCall2d74de92009-12-01 22:10:20 +00003474 DeclContext *DC = RDecl;
3475 if (SS.isSet()) {
3476 // If the member name was a qualified-id, look into the
3477 // nested-name-specifier.
3478 DC = SemaRef.computeDeclContext(SS, false);
3479
John McCall0b66eb32010-05-01 00:40:08 +00003480 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003481 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3482 << SS.getRange() << DC;
3483 return true;
3484 }
3485
John McCall2d74de92009-12-01 22:10:20 +00003486 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003487
John McCall2d74de92009-12-01 22:10:20 +00003488 if (!isa<TypeDecl>(DC)) {
3489 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3490 << DC << SS.getRange();
3491 return true;
John McCall10eae182009-11-30 22:42:35 +00003492 }
3493 }
3494
John McCall2d74de92009-12-01 22:10:20 +00003495 // The record definition is complete, now look up the member.
3496 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003497
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003498 if (!R.empty())
3499 return false;
3500
3501 // We didn't find anything with the given name, so try to correct
3502 // for typos.
3503 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003504 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003505 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003506 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3507 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3508 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003509 << FixItHint::CreateReplacement(R.getNameLoc(),
3510 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003511 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3512 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3513 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003514 return false;
3515 } else {
3516 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003517 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003518 }
3519
John McCall10eae182009-11-30 22:42:35 +00003520 return false;
3521}
3522
John McCalldadc5752010-08-24 06:29:42 +00003523ExprResult
John McCallb268a282010-08-23 23:25:46 +00003524Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003525 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003526 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003527 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003528 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003529 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003530 if (BaseType->isDependentType() ||
3531 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003532 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003533 IsArrow, OpLoc,
3534 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003535 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003536
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003537 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003538
John McCall2d74de92009-12-01 22:10:20 +00003539 // Implicit member accesses.
3540 if (!Base) {
3541 QualType RecordTy = BaseType;
3542 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3543 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3544 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003545 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003546 return ExprError();
3547
3548 // Explicit member accesses.
3549 } else {
John Wiegley01296292011-04-08 18:41:53 +00003550 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003551 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003552 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003553 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003554
John Wiegley01296292011-04-08 18:41:53 +00003555 if (BaseResult.isInvalid())
3556 return ExprError();
3557 Base = BaseResult.take();
3558
John McCall2d74de92009-12-01 22:10:20 +00003559 if (Result.isInvalid()) {
3560 Owned(Base);
3561 return ExprError();
3562 }
3563
3564 if (Result.get())
3565 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003566
3567 // LookupMemberExpr can modify Base, and thus change BaseType
3568 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003569 }
3570
John McCallb268a282010-08-23 23:25:46 +00003571 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003572 OpLoc, IsArrow, SS, FirstQualifierInScope,
3573 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003574}
3575
John McCalldadc5752010-08-24 06:29:42 +00003576ExprResult
John McCallb268a282010-08-23 23:25:46 +00003577Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003578 SourceLocation OpLoc, bool IsArrow,
3579 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003580 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003581 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003582 const TemplateArgumentListInfo *TemplateArgs,
3583 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003584 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003585 if (IsArrow) {
3586 assert(BaseType->isPointerType());
3587 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3588 }
John McCalla8ae2222010-04-06 21:38:20 +00003589 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003590
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003591 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3592 DeclarationName MemberName = MemberNameInfo.getName();
3593 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003594
3595 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003596 return ExprError();
3597
John McCall10eae182009-11-30 22:42:35 +00003598 if (R.empty()) {
3599 // Rederive where we looked up.
3600 DeclContext *DC = (SS.isSet()
3601 ? computeDeclContext(SS, false)
3602 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003603
John McCall10eae182009-11-30 22:42:35 +00003604 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003605 << MemberName << DC
3606 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003607 return ExprError();
3608 }
3609
John McCall38836f02010-01-15 08:34:02 +00003610 // Diagnose lookups that find only declarations from a non-base
3611 // type. This is possible for either qualified lookups (which may
3612 // have been qualified with an unrelated type) or implicit member
3613 // expressions (which were found with unqualified lookup and thus
3614 // may have come from an enclosing scope). Note that it's okay for
3615 // lookup to find declarations from a non-base type as long as those
3616 // aren't the ones picked by overload resolution.
3617 if ((SS.isSet() || !BaseExpr ||
3618 (isa<CXXThisExpr>(BaseExpr) &&
3619 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003620 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003621 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003622 return ExprError();
3623
3624 // Construct an unresolved result if we in fact got an unresolved
3625 // result.
3626 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003627 // Suppress any lookup-related diagnostics; we'll do these when we
3628 // pick a member.
3629 R.suppressDiagnostics();
3630
John McCall10eae182009-11-30 22:42:35 +00003631 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003632 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003633 BaseExpr, BaseExprType,
3634 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003635 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003636 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003637 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003638
3639 return Owned(MemExpr);
3640 }
3641
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003642 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003643 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003644 NamedDecl *MemberDecl = R.getFoundDecl();
3645
3646 // FIXME: diagnose the presence of template arguments now.
3647
3648 // If the decl being referenced had an error, return an error for this
3649 // sub-expr without emitting another error, in order to avoid cascading
3650 // error cases.
3651 if (MemberDecl->isInvalidDecl())
3652 return ExprError();
3653
John McCall2d74de92009-12-01 22:10:20 +00003654 // Handle the implicit-member-access case.
3655 if (!BaseExpr) {
3656 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003657 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003658 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003659
Douglas Gregorb15af892010-01-07 23:12:05 +00003660 SourceLocation Loc = R.getNameLoc();
3661 if (SS.getRange().isValid())
3662 Loc = SS.getRange().getBegin();
3663 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003664 }
3665
John McCall10eae182009-11-30 22:42:35 +00003666 bool ShouldCheckUse = true;
3667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3668 // Don't diagnose the use of a virtual member function unless it's
3669 // explicitly qualified.
3670 if (MD->isVirtual() && !SS.isSet())
3671 ShouldCheckUse = false;
3672 }
3673
3674 // Check the use of this member.
3675 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3676 Owned(BaseExpr);
3677 return ExprError();
3678 }
3679
John McCall34376a62010-12-04 03:47:34 +00003680 // Perform a property load on the base regardless of whether we
3681 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003682 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3683 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3684 if (Result.isInvalid())
3685 return ExprError();
3686 BaseExpr = Result.take();
3687 }
John McCall34376a62010-12-04 03:47:34 +00003688
John McCallfeb624a2010-11-23 20:48:44 +00003689 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3690 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3691 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003692
Francois Pichet783dd6e2010-11-21 06:08:52 +00003693 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3694 // We may have found a field within an anonymous union or struct
3695 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003696 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003697 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003698
John McCall10eae182009-11-30 22:42:35 +00003699 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3700 MarkDeclarationReferenced(MemberLoc, Var);
3701 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003702 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003703 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003704 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003705 }
3706
John McCall7decc9e2010-11-18 06:31:45 +00003707 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003708 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3709 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003710 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003711 MemberFn->getType(),
3712 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3713 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003714 }
John McCall7decc9e2010-11-18 06:31:45 +00003715 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003716
3717 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3718 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3719 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003720 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003721 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003722 }
3723
3724 Owned(BaseExpr);
3725
Douglas Gregor861eb802010-04-25 20:55:08 +00003726 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003727 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003728 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003729 << MemberName << BaseType << int(IsArrow);
3730 else
3731 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3732 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003733
Douglas Gregor861eb802010-04-25 20:55:08 +00003734 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3735 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003736 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003737 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003738}
3739
John McCall68fc88ec2010-12-15 16:46:44 +00003740/// Given that normal member access failed on the given expression,
3741/// and given that the expression's type involves builtin-id or
3742/// builtin-Class, decide whether substituting in the redefinition
3743/// types would be profitable. The redefinition type is whatever
3744/// this translation unit tried to typedef to id/Class; we store
3745/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00003746static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00003747 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00003748 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00003749 if (!opty) return false;
3750
3751 const ObjCObjectType *ty = opty->getObjectType();
3752
3753 QualType redef;
3754 if (ty->isObjCId()) {
3755 redef = S.Context.ObjCIdRedefinitionType;
3756 } else if (ty->isObjCClass()) {
3757 redef = S.Context.ObjCClassRedefinitionType;
3758 } else {
3759 return false;
3760 }
3761
3762 // Do the substitution as long as the redefinition type isn't just a
3763 // possibly-qualified pointer to builtin-id or builtin-Class again.
3764 opty = redef->getAs<ObjCObjectPointerType>();
3765 if (opty && !opty->getObjectType()->getInterface() != 0)
3766 return false;
3767
John Wiegley01296292011-04-08 18:41:53 +00003768 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00003769 return true;
3770}
3771
John McCall10eae182009-11-30 22:42:35 +00003772/// Look up the given member of the given non-type-dependent
3773/// expression. This can return in one of two ways:
3774/// * If it returns a sentinel null-but-valid result, the caller will
3775/// assume that lookup was performed and the results written into
3776/// the provided structure. It will take over from there.
3777/// * Otherwise, the returned expression will be produced in place of
3778/// an ordinary member expression.
3779///
3780/// The ObjCImpDecl bit is a gross hack that will need to be properly
3781/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003782ExprResult
John Wiegley01296292011-04-08 18:41:53 +00003783Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003784 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003785 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003786 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00003787 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003788
Steve Naroffeaaae462007-12-16 21:42:28 +00003789 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003790 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003791
John Wiegley01296292011-04-08 18:41:53 +00003792 if (IsArrow) {
3793 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3794 if (BaseExpr.isInvalid())
3795 return ExprError();
3796 }
3797
3798 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00003799 assert(!BaseType->isDependentType());
3800
3801 DeclarationName MemberName = R.getLookupName();
3802 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003803
John McCall68fc88ec2010-12-15 16:46:44 +00003804 // For later type-checking purposes, turn arrow accesses into dot
3805 // accesses. The only access type we support that doesn't follow
3806 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3807 // and those never use arrows, so this is unaffected.
3808 if (IsArrow) {
3809 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3810 BaseType = Ptr->getPointeeType();
3811 else if (const ObjCObjectPointerType *Ptr
3812 = BaseType->getAs<ObjCObjectPointerType>())
3813 BaseType = Ptr->getPointeeType();
3814 else if (BaseType->isRecordType()) {
3815 // Recover from arrow accesses to records, e.g.:
3816 // struct MyRecord foo;
3817 // foo->bar
3818 // This is actually well-formed in C++ if MyRecord has an
3819 // overloaded operator->, but that should have been dealt with
3820 // by now.
3821 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00003822 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00003823 << FixItHint::CreateReplacement(OpLoc, ".");
3824 IsArrow = false;
3825 } else {
3826 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00003827 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00003828 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003829 }
3830 }
3831
John McCall68fc88ec2010-12-15 16:46:44 +00003832 // Handle field access to simple records.
3833 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00003834 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00003835 RTy, OpLoc, SS, HasTemplateArgs))
3836 return ExprError();
3837
3838 // Returning valid-but-null is how we indicate to the caller that
3839 // the lookup result was filled in.
3840 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003841 }
John McCall10eae182009-11-30 22:42:35 +00003842
John McCall68fc88ec2010-12-15 16:46:44 +00003843 // Handle ivar access to Objective-C objects.
3844 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003845 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003846
3847 // There are three cases for the base type:
3848 // - builtin id (qualified or unqualified)
3849 // - builtin Class (qualified or unqualified)
3850 // - an interface
3851 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3852 if (!IDecl) {
3853 // There's an implicit 'isa' ivar on all objects.
3854 // But we only actually find it this way on objects of type 'id',
3855 // apparently.
3856 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00003857 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00003858 Context.getObjCClassType()));
3859
3860 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3861 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3862 ObjCImpDecl, HasTemplateArgs);
3863 goto fail;
3864 }
3865
3866 ObjCInterfaceDecl *ClassDeclared;
3867 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3868
3869 if (!IV) {
3870 // Attempt to correct for typos in ivar names.
3871 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3872 LookupMemberName);
3873 if (CorrectTypo(Res, 0, 0, IDecl, false,
3874 IsArrow ? CTC_ObjCIvarLookup
3875 : CTC_ObjCPropertyLookup) &&
3876 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3877 Diag(R.getNameLoc(),
3878 diag::err_typecheck_member_reference_ivar_suggest)
3879 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3880 << FixItHint::CreateReplacement(R.getNameLoc(),
3881 IV->getNameAsString());
3882 Diag(IV->getLocation(), diag::note_previous_decl)
3883 << IV->getDeclName();
3884 } else {
3885 Res.clear();
3886 Res.setLookupName(Member);
3887
3888 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3889 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00003890 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00003891 return ExprError();
3892 }
3893 }
3894
3895 // If the decl being referenced had an error, return an error for this
3896 // sub-expr without emitting another error, in order to avoid cascading
3897 // error cases.
3898 if (IV->isInvalidDecl())
3899 return ExprError();
3900
3901 // Check whether we can reference this field.
3902 if (DiagnoseUseOfDecl(IV, MemberLoc))
3903 return ExprError();
3904 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3905 IV->getAccessControl() != ObjCIvarDecl::Package) {
3906 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3907 if (ObjCMethodDecl *MD = getCurMethodDecl())
3908 ClassOfMethodDecl = MD->getClassInterface();
3909 else if (ObjCImpDecl && getCurFunctionDecl()) {
3910 // Case of a c-function declared inside an objc implementation.
3911 // FIXME: For a c-style function nested inside an objc implementation
3912 // class, there is no implementation context available, so we pass
3913 // down the context as argument to this routine. Ideally, this context
3914 // need be passed down in the AST node and somehow calculated from the
3915 // AST for a function decl.
3916 if (ObjCImplementationDecl *IMPD =
3917 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3918 ClassOfMethodDecl = IMPD->getClassInterface();
3919 else if (ObjCCategoryImplDecl* CatImplClass =
3920 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3921 ClassOfMethodDecl = CatImplClass->getClassInterface();
3922 }
3923
3924 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3925 if (ClassDeclared != IDecl ||
3926 ClassOfMethodDecl != ClassDeclared)
3927 Diag(MemberLoc, diag::error_private_ivar_access)
3928 << IV->getDeclName();
3929 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3930 // @protected
3931 Diag(MemberLoc, diag::error_protected_ivar_access)
3932 << IV->getDeclName();
3933 }
3934
3935 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00003936 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00003937 IsArrow));
3938 }
3939
3940 // Objective-C property access.
3941 const ObjCObjectPointerType *OPT;
3942 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3943 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00003944 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3945 if (BaseExpr.isInvalid())
3946 return ExprError();
3947
3948 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00003949
3950 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3951
3952 const ObjCObjectType *OT = OPT->getObjectType();
3953
3954 // id, with and without qualifiers.
3955 if (OT->isObjCId()) {
3956 // Check protocols on qualified interfaces.
3957 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3958 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3959 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3960 // Check the use of this declaration
3961 if (DiagnoseUseOfDecl(PD, MemberLoc))
3962 return ExprError();
3963
3964 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3965 VK_LValue,
3966 OK_ObjCProperty,
3967 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00003968 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00003969 }
3970
3971 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3972 // Check the use of this method.
3973 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3974 return ExprError();
3975 Selector SetterSel =
3976 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3977 PP.getSelectorTable(), Member);
3978 ObjCMethodDecl *SMD = 0;
3979 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3980 SetterSel, Context))
3981 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3982 QualType PType = OMD->getSendResultType();
3983
3984 ExprValueKind VK = VK_LValue;
3985 if (!getLangOptions().CPlusPlus &&
3986 IsCForbiddenLValueType(Context, PType))
3987 VK = VK_RValue;
3988 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3989
3990 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3991 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00003992 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00003993 }
3994 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003995 // Use of id.member can only be for a property reference. Do not
3996 // use the 'id' redefinition in this case.
3997 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003998 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3999 ObjCImpDecl, HasTemplateArgs);
4000
4001 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4002 << MemberName << BaseType);
4003 }
4004
4005 // 'Class', unqualified only.
4006 if (OT->isObjCClass()) {
4007 // Only works in a method declaration (??!).
4008 ObjCMethodDecl *MD = getCurMethodDecl();
4009 if (!MD) {
4010 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4011 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4012 ObjCImpDecl, HasTemplateArgs);
4013
4014 goto fail;
4015 }
4016
4017 // Also must look for a getter name which uses property syntax.
4018 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004019 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4020 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004021 if ((Getter = IFace->lookupClassMethod(Sel))) {
4022 // Check the use of this method.
4023 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4024 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004025 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004026 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004027 // If we found a getter then this may be a valid dot-reference, we
4028 // will look for the matching setter, in case it is needed.
4029 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004030 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4031 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004032 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4033 if (!Setter) {
4034 // If this reference is in an @implementation, also check for 'private'
4035 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004036 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004037 }
4038 // Look through local category implementations associated with the class.
4039 if (!Setter)
4040 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004041
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004042 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4043 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004044
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004045 if (Getter || Setter) {
4046 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004047
John McCall4bc41ae2010-11-18 19:01:18 +00004048 ExprValueKind VK = VK_LValue;
4049 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004050 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004051 if (!getLangOptions().CPlusPlus &&
4052 IsCForbiddenLValueType(Context, PType))
4053 VK = VK_RValue;
4054 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004055 // Get the expression type from Setter's incoming parameter.
4056 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004057 }
4058 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4059
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004060 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004061 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4062 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004063 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004064 }
John McCall68fc88ec2010-12-15 16:46:44 +00004065
4066 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4067 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4068 ObjCImpDecl, HasTemplateArgs);
4069
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004070 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004071 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004072 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004073
John McCall68fc88ec2010-12-15 16:46:44 +00004074 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004075 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004076 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004077 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004078
Chris Lattnerb63a7452008-07-21 04:28:12 +00004079 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004080 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004081 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004082 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004083 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004084 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4085 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004086 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004087 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004088
John Wiegley01296292011-04-08 18:41:53 +00004089 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004090 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004091 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004092
John McCall68fc88ec2010-12-15 16:46:44 +00004093 // Adjust builtin-sel to the appropriate redefinition type if that's
4094 // not just a pointer to builtin-sel again.
4095 if (IsArrow &&
4096 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4097 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004098 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4099 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004100 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4101 ObjCImpDecl, HasTemplateArgs);
4102 }
4103
4104 // Failure cases.
4105 fail:
4106
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004107 // Recover from dot accesses to pointers, e.g.:
4108 // type *foo;
4109 // foo.bar
4110 // This is actually well-formed in two cases:
4111 // - 'type' is an Objective C type
4112 // - 'bar' is a pseudo-destructor name which happens to refer to
4113 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004114 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004115 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4116 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004117 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004118 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004119 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004120
4121 // Recurse as an -> access.
4122 IsArrow = true;
4123 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4124 ObjCImpDecl, HasTemplateArgs);
4125 }
John McCall68fc88ec2010-12-15 16:46:44 +00004126 }
4127
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004128 // If the user is trying to apply -> or . to a function name, it's probably
4129 // because they forgot parentheses to call that function.
4130 bool TryCall = false;
4131 bool Overloaded = false;
4132 UnresolvedSet<8> AllOverloads;
John Wiegley01296292011-04-08 18:41:53 +00004133 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004134 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4135 TryCall = true;
4136 Overloaded = true;
John Wiegley01296292011-04-08 18:41:53 +00004137 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004138 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4139 AllOverloads.addDecl(Fun);
4140 TryCall = true;
4141 }
4142 }
John McCall68fc88ec2010-12-15 16:46:44 +00004143
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004144 if (TryCall) {
4145 // Plunder the overload set for something that would make the member
4146 // expression valid.
4147 UnresolvedSet<4> ViableOverloads;
4148 bool HasViableZeroArgOverload = false;
4149 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4150 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004151 // Our overload set may include TemplateDecls, which we'll ignore for the
4152 // purposes of determining whether we can issue a '()' fixit.
4153 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4154 QualType ResultTy = OverloadDecl->getResultType();
4155 if ((!IsArrow && ResultTy->isRecordType()) ||
4156 (IsArrow && ResultTy->isPointerType() &&
4157 ResultTy->getPointeeType()->isRecordType())) {
4158 ViableOverloads.addDecl(*it);
4159 if (OverloadDecl->getMinRequiredArguments() == 0) {
4160 HasViableZeroArgOverload = true;
4161 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004162 }
John McCall68fc88ec2010-12-15 16:46:44 +00004163 }
4164 }
4165
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004166 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley01296292011-04-08 18:41:53 +00004167 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004168 << (AllOverloads.size() > 1) << 0
John Wiegley01296292011-04-08 18:41:53 +00004169 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004170 int ViableOverloadCount = ViableOverloads.size();
4171 int I;
4172 for (I = 0; I < ViableOverloadCount; ++I) {
4173 // FIXME: Magic number for max shown overloads stolen from
4174 // OverloadCandidateSet::NoteCandidates.
4175 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4176 break;
4177 }
4178 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4179 diag::note_member_ref_possible_intended_overload);
4180 }
4181 if (I != ViableOverloadCount) {
John Wiegley01296292011-04-08 18:41:53 +00004182 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004183 << int(ViableOverloadCount - I);
4184 }
4185 return ExprError();
4186 }
4187 } else {
4188 // We don't have an expression that's convenient to get a Decl from, but we
4189 // can at least check if the type is "function of 0 arguments which returns
4190 // an acceptable type".
4191 const FunctionType *Fun = NULL;
4192 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4193 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4194 TryCall = true;
4195 }
4196 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4197 TryCall = true;
4198 }
John McCall68fc88ec2010-12-15 16:46:44 +00004199
4200 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004201 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4202 if (FPT->getNumArgs() == 0) {
4203 QualType ResultTy = Fun->getResultType();
4204 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4205 (IsArrow && ResultTy->isPointerType() &&
4206 ResultTy->getPointeeType()->isRecordType());
4207 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004208 }
John McCall68fc88ec2010-12-15 16:46:44 +00004209 }
4210 }
4211
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004212 if (TryCall) {
4213 // At this point, we know BaseExpr looks like it's potentially callable with
4214 // 0 arguments, and that it returns something of a reasonable type, so we
4215 // can emit a fixit and carry on pretending that BaseExpr was actually a
4216 // CallExpr.
4217 SourceLocation ParenInsertionLoc =
John Wiegley01296292011-04-08 18:41:53 +00004218 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4219 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004220 << int(Overloaded) << 1
John Wiegley01296292011-04-08 18:41:53 +00004221 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004222 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley01296292011-04-08 18:41:53 +00004223 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004224 MultiExprArg(*this, 0, 0),
4225 ParenInsertionLoc);
4226 if (NewBase.isInvalid())
4227 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004228 BaseExpr = NewBase;
4229 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004230 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4231 ObjCImpDecl, HasTemplateArgs);
4232 }
4233
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004234 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004235 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004236
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004237 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004238}
4239
John McCall10eae182009-11-30 22:42:35 +00004240/// The main callback when the parser finds something like
4241/// expression . [nested-name-specifier] identifier
4242/// expression -> [nested-name-specifier] identifier
4243/// where 'identifier' encompasses a fairly broad spectrum of
4244/// possibilities, including destructor and operator references.
4245///
4246/// \param OpKind either tok::arrow or tok::period
4247/// \param HasTrailingLParen whether the next token is '(', which
4248/// is used to diagnose mis-uses of special members that can
4249/// only be called
4250/// \param ObjCImpDecl the current ObjC @implementation decl;
4251/// this is an ugly hack around the fact that ObjC @implementations
4252/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004253ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004254 SourceLocation OpLoc,
4255 tok::TokenKind OpKind,
4256 CXXScopeSpec &SS,
4257 UnqualifiedId &Id,
4258 Decl *ObjCImpDecl,
4259 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004260 if (SS.isSet() && SS.isInvalid())
4261 return ExprError();
4262
Francois Pichet64225792011-01-18 05:04:39 +00004263 // Warn about the explicit constructor calls Microsoft extension.
4264 if (getLangOptions().Microsoft &&
4265 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4266 Diag(Id.getSourceRange().getBegin(),
4267 diag::ext_ms_explicit_constructor_call);
4268
John McCall10eae182009-11-30 22:42:35 +00004269 TemplateArgumentListInfo TemplateArgsBuffer;
4270
4271 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004272 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004273 const TemplateArgumentListInfo *TemplateArgs;
4274 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004275 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004276
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004277 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004278 bool IsArrow = (OpKind == tok::arrow);
4279
4280 NamedDecl *FirstQualifierInScope
4281 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4282 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4283
4284 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004285 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004286 if (Result.isInvalid()) return ExprError();
4287 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004288
Douglas Gregor41f90302010-04-12 20:54:26 +00004289 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4290 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004291 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004292 IsArrow, OpLoc,
4293 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004294 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004295 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004296 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004297 ExprResult BaseResult = Owned(Base);
4298 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004299 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004300 if (BaseResult.isInvalid())
4301 return ExprError();
4302 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004303
John McCalle9cccd82010-06-16 08:42:20 +00004304 if (Result.isInvalid()) {
4305 Owned(Base);
4306 return ExprError();
4307 }
John McCall10eae182009-11-30 22:42:35 +00004308
John McCalle9cccd82010-06-16 08:42:20 +00004309 if (Result.get()) {
4310 // The only way a reference to a destructor can be used is to
4311 // immediately call it, which falls into this case. If the
4312 // next token is not a '(', produce a diagnostic and build the
4313 // call now.
4314 if (!HasTrailingLParen &&
4315 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004316 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004317
John McCalle9cccd82010-06-16 08:42:20 +00004318 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004319 }
4320
John McCallb268a282010-08-23 23:25:46 +00004321 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004322 OpLoc, IsArrow, SS, FirstQualifierInScope,
4323 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004324 }
4325
4326 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004327}
4328
John McCalldadc5752010-08-24 06:29:42 +00004329ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004330 FunctionDecl *FD,
4331 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004332 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004333 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004334 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004335 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004336 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004337 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004338 return ExprError();
4339 }
4340
4341 if (Param->hasUninstantiatedDefaultArg()) {
4342 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004343
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004344 // Instantiate the expression.
4345 MultiLevelTemplateArgumentList ArgList
4346 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004347
Nico Weber44887f62010-11-29 18:19:25 +00004348 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004349 = ArgList.getInnermost();
4350 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4351 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004352
Nico Weber44887f62010-11-29 18:19:25 +00004353 ExprResult Result;
4354 {
4355 // C++ [dcl.fct.default]p5:
4356 // The names in the [default argument] expression are bound, and
4357 // the semantic constraints are checked, at the point where the
4358 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004359 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004360 Result = SubstExpr(UninstExpr, ArgList);
4361 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004362 if (Result.isInvalid())
4363 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004365 // Check the expression as an initializer for the parameter.
4366 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004367 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004368 InitializationKind Kind
4369 = InitializationKind::CreateCopy(Param->getLocation(),
4370 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4371 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004372
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004373 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4374 Result = InitSeq.Perform(*this, Entity, Kind,
4375 MultiExprArg(*this, &ResultE, 1));
4376 if (Result.isInvalid())
4377 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004378
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004379 // Build the default argument expression.
4380 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4381 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004382 }
4383
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004384 // If the default expression creates temporaries, we need to
4385 // push them to the current stack of expression temporaries so they'll
4386 // be properly destroyed.
4387 // FIXME: We should really be rebuilding the default argument with new
4388 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004389 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4390 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4391 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4392 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4393 ExprTemporaries.push_back(Temporary);
4394 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004395
4396 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004397 // Just mark all of the declarations in this potentially-evaluated expression
4398 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004399 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004400 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004401}
4402
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004403/// ConvertArgumentsForCall - Converts the arguments specified in
4404/// Args/NumArgs to the parameter types of the function FDecl with
4405/// function prototype Proto. Call is the call expression itself, and
4406/// Fn is the function expression. For a C++ member function, this
4407/// routine does not attempt to convert the object argument. Returns
4408/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004409bool
4410Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004411 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004412 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004413 Expr **Args, unsigned NumArgs,
4414 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004415 // Bail out early if calling a builtin with custom typechecking.
4416 // We don't need to do this in the
4417 if (FDecl)
4418 if (unsigned ID = FDecl->getBuiltinID())
4419 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4420 return false;
4421
Mike Stump4e1f26a2009-02-19 03:04:26 +00004422 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004423 // assignment, to the types of the corresponding parameter, ...
4424 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004425 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004426
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004427 // If too few arguments are available (and we don't have default
4428 // arguments for the remaining parameters), don't make the call.
4429 if (NumArgs < NumArgsInProto) {
4430 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4431 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004432 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004433 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004434 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004435 }
4436
4437 // If too many are passed and not variadic, error on the extras and drop
4438 // them.
4439 if (NumArgs > NumArgsInProto) {
4440 if (!Proto->isVariadic()) {
4441 Diag(Args[NumArgsInProto]->getLocStart(),
4442 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004443 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004444 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004445 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4446 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004447
4448 // Emit the location of the prototype.
4449 if (FDecl && !FDecl->getBuiltinID())
4450 Diag(FDecl->getLocStart(),
4451 diag::note_typecheck_call_too_many_args)
4452 << FDecl;
4453
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004454 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004455 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004456 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004457 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004458 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004459 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004460 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004461 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4462 if (Fn->getType()->isBlockPointerType())
4463 CallType = VariadicBlock; // Block
4464 else if (isa<MemberExpr>(Fn))
4465 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004466 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004467 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004468 if (Invalid)
4469 return true;
4470 unsigned TotalNumArgs = AllArgs.size();
4471 for (unsigned i = 0; i < TotalNumArgs; ++i)
4472 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004474 return false;
4475}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004476
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004477bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4478 FunctionDecl *FDecl,
4479 const FunctionProtoType *Proto,
4480 unsigned FirstProtoArg,
4481 Expr **Args, unsigned NumArgs,
4482 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004483 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004484 unsigned NumArgsInProto = Proto->getNumArgs();
4485 unsigned NumArgsToCheck = NumArgs;
4486 bool Invalid = false;
4487 if (NumArgs != NumArgsInProto)
4488 // Use default arguments for missing arguments
4489 NumArgsToCheck = NumArgsInProto;
4490 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004491 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004492 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004493 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004494
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004495 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004496 if (ArgIx < NumArgs) {
4497 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004498
Eli Friedman3164fb12009-03-22 22:00:50 +00004499 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4500 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004501 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004502 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004503 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004504
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004505 // Pass the argument
4506 ParmVarDecl *Param = 0;
4507 if (FDecl && i < FDecl->getNumParams())
4508 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004509
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004510 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004511 Param? InitializedEntity::InitializeParameter(Context, Param)
4512 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004513 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004514 SourceLocation(),
4515 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004516 if (ArgE.isInvalid())
4517 return true;
4518
4519 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004520 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004521 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004522
John McCalldadc5752010-08-24 06:29:42 +00004523 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004524 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004525 if (ArgExpr.isInvalid())
4526 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004527
Anders Carlsson355933d2009-08-25 03:49:14 +00004528 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004529 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004530 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004532
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004533 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004534 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004535 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004536 for (unsigned i = ArgIx; i != NumArgs; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004537 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4538 Invalid |= Arg.isInvalid();
4539 AllArgs.push_back(Arg.take());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004540 }
4541 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004542 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004543}
4544
Steve Naroff83895f72007-09-16 03:34:24 +00004545/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004546/// This provides the location of the left/right parens and a list of comma
4547/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004548ExprResult
John McCallb268a282010-08-23 23:25:46 +00004549Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004550 MultiExprArg args, SourceLocation RParenLoc,
4551 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004552 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004553
4554 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004555 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004556 if (Result.isInvalid()) return ExprError();
4557 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004558
John McCallb268a282010-08-23 23:25:46 +00004559 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004560
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004561 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004562 // If this is a pseudo-destructor expression, build the call immediately.
4563 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4564 if (NumArgs > 0) {
4565 // Pseudo-destructor calls should not have any arguments.
4566 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004567 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004568 SourceRange(Args[0]->getLocStart(),
4569 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004570
Douglas Gregorad8a3362009-09-04 17:36:40 +00004571 NumArgs = 0;
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
Douglas Gregorad8a3362009-09-04 17:36:40 +00004574 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004575 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004576 }
Mike Stump11289f42009-09-09 15:08:12 +00004577
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004578 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004579 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004580 // FIXME: Will need to cache the results of name lookup (including ADL) in
4581 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004582 bool Dependent = false;
4583 if (Fn->isTypeDependent())
4584 Dependent = true;
4585 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4586 Dependent = true;
4587
Peter Collingbourne41f85462011-02-09 21:07:24 +00004588 if (Dependent) {
4589 if (ExecConfig) {
4590 return Owned(new (Context) CUDAKernelCallExpr(
4591 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4592 Context.DependentTy, VK_RValue, RParenLoc));
4593 } else {
4594 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4595 Context.DependentTy, VK_RValue,
4596 RParenLoc));
4597 }
4598 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004599
4600 // Determine whether this is a call to an object (C++ [over.call.object]).
4601 if (Fn->getType()->isRecordType())
4602 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004603 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004604
John McCall10eae182009-11-30 22:42:35 +00004605 Expr *NakedFn = Fn->IgnoreParens();
4606
4607 // Determine whether this is a call to an unresolved member function.
4608 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4609 // If lookup was unresolved but not dependent (i.e. didn't find
4610 // an unresolved using declaration), it has to be an overloaded
4611 // function set, which means it must contain either multiple
4612 // declarations (all methods or method templates) or a single
4613 // method template.
4614 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004615 isa<FunctionTemplateDecl>(
4616 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004617 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004618
John McCall2d74de92009-12-01 22:10:20 +00004619 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004620 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004621 }
4622
Douglas Gregore254f902009-02-04 00:32:51 +00004623 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004624 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004625 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004626 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004627 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004628 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004629 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004630
Anders Carlsson61914b52009-10-03 17:40:22 +00004631 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004632 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004633 if (BO->getOpcode() == BO_PtrMemD ||
4634 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004635 if (const FunctionProtoType *FPT
4636 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004637 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004638 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004639
Douglas Gregor125fa402011-02-04 12:57:49 +00004640 // Check that the object type isn't more qualified than the
4641 // member function we're calling.
4642 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4643 Qualifiers ObjectQuals
4644 = BO->getOpcode() == BO_PtrMemD
4645 ? BO->getLHS()->getType().getQualifiers()
4646 : BO->getLHS()->getType()->getAs<PointerType>()
4647 ->getPointeeType().getQualifiers();
4648
4649 Qualifiers Difference = ObjectQuals - FuncQuals;
4650 Difference.removeObjCGCAttr();
4651 Difference.removeAddressSpace();
4652 if (Difference) {
4653 std::string QualsString = Difference.getAsString();
4654 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4655 << BO->getType().getUnqualifiedType()
4656 << QualsString
4657 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4658 }
4659
John McCallb268a282010-08-23 23:25:46 +00004660 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004661 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004662 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004663 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004664
4665 if (CheckCallReturnType(FPT->getResultType(),
4666 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004667 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004668 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004669
John McCallb268a282010-08-23 23:25:46 +00004670 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004671 RParenLoc))
4672 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004673
John McCallb268a282010-08-23 23:25:46 +00004674 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004675 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004676 }
4677 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004678 }
4679
Douglas Gregore254f902009-02-04 00:32:51 +00004680 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004681 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004682 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683
Eli Friedmane14b1992009-12-26 03:35:45 +00004684 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004685 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4686 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4687 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004688 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004689 }
4690
John McCall57500772009-12-16 12:17:52 +00004691 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004692 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4693 if (UnOp->getOpcode() == UO_AddrOf)
4694 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4695
John McCall57500772009-12-16 12:17:52 +00004696 if (isa<DeclRefExpr>(NakedFn))
4697 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4698
Peter Collingbourne41f85462011-02-09 21:07:24 +00004699 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4700 ExecConfig);
4701}
4702
4703ExprResult
4704Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4705 MultiExprArg execConfig, SourceLocation GGGLoc) {
4706 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4707 if (!ConfigDecl)
4708 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4709 << "cudaConfigureCall");
4710 QualType ConfigQTy = ConfigDecl->getType();
4711
4712 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4713 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4714
4715 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004716}
4717
John McCall31996342011-04-07 08:22:57 +00004718/// Given a function expression of unknown-any type, rebuild it to
4719/// have a type appropriate for being called with the given arguments,
4720/// yielding a value of unknown-any type.
4721static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn,
4722 Expr **args, unsigned numArgs) {
John McCall39439732011-04-09 22:50:59 +00004723 // Strip an lvalue-to-rvalue conversion off.
4724 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(fn))
4725 if (ice->getCastKind() == CK_LValueToRValue)
4726 fn = ice->getSubExpr();
4727
John McCall31996342011-04-07 08:22:57 +00004728 // Build a simple function type exactly matching the arguments.
4729 llvm::SmallVector<QualType, 8> argTypes;
4730 argTypes.reserve(numArgs);
4731 for (unsigned i = 0; i != numArgs; ++i) {
4732 // Require all the sub-expression to not be placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00004733 ExprResult result = S.CheckPlaceholderExpr(args[i]);
John McCall31996342011-04-07 08:22:57 +00004734 if (result.isInvalid()) return ExprError();
4735 args[i] = result.take();
4736
4737 // Do l2r conversions on all the arguments.
4738 S.DefaultLvalueConversion(args[i]);
4739
4740 argTypes.push_back(args[i]->getType());
4741 }
4742
4743 // Resolve the symbol to a function type that returns an unknown-any
4744 // type. In the fully resolved expression, this cast will surround
4745 // the DeclRefExpr.
4746 FunctionProtoType::ExtProtoInfo extInfo;
4747 QualType fnType = S.Context.getFunctionType(S.Context.UnknownAnyTy,
4748 argTypes.data(), numArgs,
4749 extInfo);
4750 fn = ImplicitCastExpr::Create(S.Context, fnType,
4751 CK_ResolveUnknownAnyType,
4752 fn, /*path*/ 0,
4753 (S.getLangOptions().CPlusPlus ? VK_LValue : VK_RValue));
4754
4755 // Decay that to a pointer.
4756 fnType = S.Context.getPointerType(fnType);
4757 fn = ImplicitCastExpr::Create(S.Context, fnType,
4758 CK_FunctionToPointerDecay,
4759 fn, /*path*/ 0, VK_RValue);
4760
4761 return S.Owned(fn);
4762}
4763
John McCall57500772009-12-16 12:17:52 +00004764/// BuildResolvedCallExpr - Build a call to a resolved expression,
4765/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004766/// unary-convert to an expression of function-pointer or
4767/// block-pointer type.
4768///
4769/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004770ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004771Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4772 SourceLocation LParenLoc,
4773 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004774 SourceLocation RParenLoc,
4775 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004776 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4777
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004778 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004779 ExprResult Result = UsualUnaryConversions(Fn);
4780 if (Result.isInvalid())
4781 return ExprError();
4782 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004783
Chris Lattner08464942007-12-28 05:29:59 +00004784 // Make the call expr early, before semantic checks. This guarantees cleanup
4785 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004786 CallExpr *TheCall;
4787 if (Config) {
4788 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4789 cast<CallExpr>(Config),
4790 Args, NumArgs,
4791 Context.BoolTy,
4792 VK_RValue,
4793 RParenLoc);
4794 } else {
4795 TheCall = new (Context) CallExpr(Context, Fn,
4796 Args, NumArgs,
4797 Context.BoolTy,
4798 VK_RValue,
4799 RParenLoc);
4800 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004801
John McCallbebede42011-02-26 05:39:39 +00004802 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4803
4804 // Bail out early if calling a builtin with custom typechecking.
4805 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4806 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4807
John McCall31996342011-04-07 08:22:57 +00004808 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004809 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004810 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004811 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4812 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004813 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004814 if (FuncT == 0)
4815 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4816 << Fn->getType() << Fn->getSourceRange());
4817 } else if (const BlockPointerType *BPT =
4818 Fn->getType()->getAs<BlockPointerType>()) {
4819 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4820 } else {
John McCall31996342011-04-07 08:22:57 +00004821 // Handle calls to expressions of unknown-any type.
4822 if (Fn->getType() == Context.UnknownAnyTy) {
4823 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn, Args, NumArgs);
4824 if (rewrite.isInvalid()) return ExprError();
4825 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004826 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004827 NDecl = FDecl = 0;
4828 goto retry;
4829 }
4830
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004831 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4832 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004833 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004834
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004835 if (getLangOptions().CUDA) {
4836 if (Config) {
4837 // CUDA: Kernel calls must be to global functions
4838 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4839 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4840 << FDecl->getName() << Fn->getSourceRange());
4841
4842 // CUDA: Kernel function must have 'void' return type
4843 if (!FuncT->getResultType()->isVoidType())
4844 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4845 << Fn->getType() << Fn->getSourceRange());
4846 }
4847 }
4848
Eli Friedman3164fb12009-03-22 22:00:50 +00004849 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004850 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004851 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004852 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004853 return ExprError();
4854
Chris Lattner08464942007-12-28 05:29:59 +00004855 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004856 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004857 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004858
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004859 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004860 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004861 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004862 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004863 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004864 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004865
Douglas Gregord8e97de2009-04-02 15:37:10 +00004866 if (FDecl) {
4867 // Check if we have too few/too many template arguments, based
4868 // on our knowledge of the function definition.
4869 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004870 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004871 const FunctionProtoType *Proto
4872 = Def->getType()->getAs<FunctionProtoType>();
4873 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004874 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4875 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004876 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004877
4878 // If the function we're calling isn't a function prototype, but we have
4879 // a function prototype from a prior declaratiom, use that prototype.
4880 if (!FDecl->hasPrototype())
4881 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004882 }
4883
Steve Naroff0b661582007-08-28 23:30:39 +00004884 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004885 for (unsigned i = 0; i != NumArgs; i++) {
4886 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004887
4888 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004889 InitializedEntity Entity
4890 = InitializedEntity::InitializeParameter(Context,
4891 Proto->getArgType(i));
4892 ExprResult ArgE = PerformCopyInitialization(Entity,
4893 SourceLocation(),
4894 Owned(Arg));
4895 if (ArgE.isInvalid())
4896 return true;
4897
4898 Arg = ArgE.takeAs<Expr>();
4899
4900 } else {
John Wiegley01296292011-04-08 18:41:53 +00004901 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4902
4903 if (ArgE.isInvalid())
4904 return true;
4905
4906 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004907 }
4908
Douglas Gregor83025412010-10-26 05:45:40 +00004909 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4910 Arg->getType(),
4911 PDiag(diag::err_call_incomplete_argument)
4912 << Arg->getSourceRange()))
4913 return ExprError();
4914
Chris Lattner08464942007-12-28 05:29:59 +00004915 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004916 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004917 }
Chris Lattner08464942007-12-28 05:29:59 +00004918
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004919 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4920 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004921 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4922 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004923
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004924 // Check for sentinels
4925 if (NDecl)
4926 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004927
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004928 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004929 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004930 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004931 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004932
John McCallbebede42011-02-26 05:39:39 +00004933 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004934 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004935 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004936 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004937 return ExprError();
4938 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004939
John McCallb268a282010-08-23 23:25:46 +00004940 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004941}
4942
John McCalldadc5752010-08-24 06:29:42 +00004943ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004944Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004945 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004946 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004947 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004948 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004949
4950 TypeSourceInfo *TInfo;
4951 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4952 if (!TInfo)
4953 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4954
John McCallb268a282010-08-23 23:25:46 +00004955 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004956}
4957
John McCalldadc5752010-08-24 06:29:42 +00004958ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004959Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004960 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004961 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004962
Eli Friedman37a186d2008-05-20 05:22:08 +00004963 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004964 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4965 PDiag(diag::err_illegal_decl_array_incomplete_type)
4966 << SourceRange(LParenLoc,
4967 literalExpr->getSourceRange().getEnd())))
4968 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004969 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004970 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4971 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004972 } else if (!literalType->isDependentType() &&
4973 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004974 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004975 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004976 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004977 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004978
Douglas Gregor85dabae2009-12-16 01:38:02 +00004979 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004980 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004981 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004982 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004983 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004984 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004985 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004986 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004987 &literalType);
4988 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004989 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004990 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004991
Chris Lattner79413952008-12-04 23:50:19 +00004992 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004993 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004994 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004995 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004996 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004997
John McCall7decc9e2010-11-18 06:31:45 +00004998 // In C, compound literals are l-values for some reason.
4999 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5000
John McCall5d7aa7f2010-01-19 22:33:45 +00005001 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005002 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005003}
5004
John McCalldadc5752010-08-24 06:29:42 +00005005ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005006Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005007 SourceLocation RBraceLoc) {
5008 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005009 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005010
Steve Naroff30d242c2007-09-15 18:49:24 +00005011 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005012 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005013
Ted Kremenekac034612010-04-13 23:39:13 +00005014 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5015 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005016 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005017 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005018}
5019
John McCalld7646252010-11-14 08:17:51 +00005020/// Prepares for a scalar cast, performing all the necessary stages
5021/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005022static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005023 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5024 // Also, callers should have filtered out the invalid cases with
5025 // pointers. Everything else should be possible.
5026
John Wiegley01296292011-04-08 18:41:53 +00005027 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005028 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005029 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005030
John McCall8cb679e2010-11-15 09:13:47 +00005031 switch (SrcTy->getScalarTypeKind()) {
5032 case Type::STK_MemberPointer:
5033 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005034
John McCall8cb679e2010-11-15 09:13:47 +00005035 case Type::STK_Pointer:
5036 switch (DestTy->getScalarTypeKind()) {
5037 case Type::STK_Pointer:
5038 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005039 CK_AnyPointerToObjCPointerCast :
5040 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005041 case Type::STK_Bool:
5042 return CK_PointerToBoolean;
5043 case Type::STK_Integral:
5044 return CK_PointerToIntegral;
5045 case Type::STK_Floating:
5046 case Type::STK_FloatingComplex:
5047 case Type::STK_IntegralComplex:
5048 case Type::STK_MemberPointer:
5049 llvm_unreachable("illegal cast from pointer");
5050 }
5051 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005052
John McCall8cb679e2010-11-15 09:13:47 +00005053 case Type::STK_Bool: // casting from bool is like casting from an integer
5054 case Type::STK_Integral:
5055 switch (DestTy->getScalarTypeKind()) {
5056 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005057 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005058 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005059 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005060 case Type::STK_Bool:
5061 return CK_IntegralToBoolean;
5062 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005063 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005064 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005065 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005066 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005067 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5068 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005069 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005070 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005071 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5072 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005073 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005074 case Type::STK_MemberPointer:
5075 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005076 }
5077 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005078
John McCall8cb679e2010-11-15 09:13:47 +00005079 case Type::STK_Floating:
5080 switch (DestTy->getScalarTypeKind()) {
5081 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005082 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005083 case Type::STK_Bool:
5084 return CK_FloatingToBoolean;
5085 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005086 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005087 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005088 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5089 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005090 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005091 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005092 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5093 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005094 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005095 case Type::STK_Pointer:
5096 llvm_unreachable("valid float->pointer cast?");
5097 case Type::STK_MemberPointer:
5098 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005099 }
5100 break;
5101
John McCall8cb679e2010-11-15 09:13:47 +00005102 case Type::STK_FloatingComplex:
5103 switch (DestTy->getScalarTypeKind()) {
5104 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005105 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005106 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005107 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005108 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005109 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005110 if (S.Context.hasSameType(ET, DestTy))
5111 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005112 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005113 return CK_FloatingCast;
5114 }
John McCall8cb679e2010-11-15 09:13:47 +00005115 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005116 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005117 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005118 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5119 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005120 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005121 case Type::STK_Pointer:
5122 llvm_unreachable("valid complex float->pointer cast?");
5123 case Type::STK_MemberPointer:
5124 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005125 }
5126 break;
5127
John McCall8cb679e2010-11-15 09:13:47 +00005128 case Type::STK_IntegralComplex:
5129 switch (DestTy->getScalarTypeKind()) {
5130 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005131 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005132 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005133 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005134 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005135 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005136 if (S.Context.hasSameType(ET, DestTy))
5137 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005138 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005139 return CK_IntegralCast;
5140 }
John McCall8cb679e2010-11-15 09:13:47 +00005141 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005142 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005143 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005144 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5145 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005146 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005147 case Type::STK_Pointer:
5148 llvm_unreachable("valid complex int->pointer cast?");
5149 case Type::STK_MemberPointer:
5150 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005151 }
5152 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005153 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005154
John McCalld7646252010-11-14 08:17:51 +00005155 llvm_unreachable("Unhandled scalar cast");
5156 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005157}
5158
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005159/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005160ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5161 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5162 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005163 if (castExpr->getType() == Context.UnknownAnyTy)
5164 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5165
Sebastian Redl9f831db2009-07-25 15:41:38 +00005166 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005167 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5168 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005169 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005170 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005171
John McCall3aef3d82011-04-10 19:13:55 +00005172 assert(!castExpr->getType()->isPlaceholderType());
5173
John McCall7decc9e2010-11-18 06:31:45 +00005174 // We only support r-value casts in C.
5175 VK = VK_RValue;
5176
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005177 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5178 // type needs to be scalar.
5179 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005180 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005181 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5182 if (castExprRes.isInvalid())
5183 return ExprError();
5184 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005185
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005186 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005187 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005188 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005189 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005190
John Wiegley01296292011-04-08 18:41:53 +00005191 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5192 if (castExprRes.isInvalid())
5193 return ExprError();
5194 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005195
Eli Friedmane98194d2010-07-17 20:43:49 +00005196 if (RequireCompleteType(TyR.getBegin(), castType,
5197 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005198 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005199
Anders Carlssonef918ac2009-10-16 02:35:04 +00005200 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005201 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005202 (castType->isStructureType() || castType->isUnionType())) {
5203 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005204 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005205 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5206 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005207 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005208 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005209 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005210
Anders Carlsson525b76b2009-10-16 02:48:28 +00005211 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005212 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005213 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005214 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005215 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005216 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005217 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005218 castExpr->getType()) &&
5219 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005220 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5221 << castExpr->getSourceRange();
5222 break;
5223 }
5224 }
John Wiegley01296292011-04-08 18:41:53 +00005225 if (Field == FieldEnd) {
5226 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005227 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005228 return ExprError();
5229 }
John McCalle3027922010-08-25 11:45:40 +00005230 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005231 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005232 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005233
Anders Carlsson525b76b2009-10-16 02:48:28 +00005234 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005235 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005236 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005237 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005238 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005239
John McCalld7646252010-11-14 08:17:51 +00005240 // The type we're casting to is known to be a scalar or vector.
5241
5242 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005243 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005244 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005245 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005246 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005247 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005248 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005249 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005250
5251 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005252 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005253
Anton Yartsev28ccef72011-03-27 09:32:40 +00005254 if (castType->isVectorType()) {
5255 if (castType->getAs<VectorType>()->getVectorKind() ==
5256 VectorType::AltiVecVector &&
5257 (castExpr->getType()->isIntegerType() ||
5258 castExpr->getType()->isFloatingType())) {
5259 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005260 return Owned(castExpr);
5261 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5262 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005263 } else
John Wiegley01296292011-04-08 18:41:53 +00005264 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005265 }
John Wiegley01296292011-04-08 18:41:53 +00005266 if (castExpr->getType()->isVectorType()) {
5267 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5268 return ExprError();
5269 else
5270 return Owned(castExpr);
5271 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005272
John McCalld7646252010-11-14 08:17:51 +00005273 // The source and target types are both scalars, i.e.
5274 // - arithmetic types (fundamental, enum, and complex)
5275 // - all kinds of pointers
5276 // Note that member pointers were filtered out with C++, above.
5277
John Wiegley01296292011-04-08 18:41:53 +00005278 if (isa<ObjCSelectorExpr>(castExpr)) {
5279 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5280 return ExprError();
5281 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005282
John McCalld7646252010-11-14 08:17:51 +00005283 // If either type is a pointer, the other type has to be either an
5284 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005285 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005286 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005287 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005288 castExprType->isArithmeticType()) {
5289 Diag(castExpr->getLocStart(),
5290 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005291 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005292 return ExprError();
5293 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005294 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005295 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5296 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005297 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005298 return ExprError();
5299 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005300 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005301
John Wiegley01296292011-04-08 18:41:53 +00005302 castExprRes = Owned(castExpr);
5303 Kind = PrepareScalarCast(*this, castExprRes, castType);
5304 if (castExprRes.isInvalid())
5305 return ExprError();
5306 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005307
John McCalld7646252010-11-14 08:17:51 +00005308 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005309 CheckCastAlign(castExpr, castType, TyR);
5310
John Wiegley01296292011-04-08 18:41:53 +00005311 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005312}
5313
Anders Carlsson525b76b2009-10-16 02:48:28 +00005314bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005315 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005316 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005317
Anders Carlssonde71adf2007-11-27 05:51:55 +00005318 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005319 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005320 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005321 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005322 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005323 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005324 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005325 } else
5326 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005327 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005328 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005329
John McCalle3027922010-08-25 11:45:40 +00005330 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005331 return false;
5332}
5333
John Wiegley01296292011-04-08 18:41:53 +00005334ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5335 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005336 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005337
Anders Carlsson43d70f82009-10-16 05:23:41 +00005338 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005339
Nate Begemanc8961a42009-06-27 22:05:55 +00005340 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5341 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005342 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005343 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5344 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005345 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005346 return ExprError();
5347 }
John McCalle3027922010-08-25 11:45:40 +00005348 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005349 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005350 }
5351
Nate Begemanbd956c42009-06-28 02:36:38 +00005352 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005353 // conversion will take place first from scalar to elt type, and then
5354 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005355 if (SrcTy->isPointerType())
5356 return Diag(R.getBegin(),
5357 diag::err_invalid_conversion_between_vector_and_scalar)
5358 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005359
5360 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005361 ExprResult CastExprRes = Owned(CastExpr);
5362 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5363 if (CastExprRes.isInvalid())
5364 return ExprError();
5365 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005366
John McCalle3027922010-08-25 11:45:40 +00005367 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005368 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005369}
5370
John McCalldadc5752010-08-24 06:29:42 +00005371ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005372Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005373 SourceLocation RParenLoc, Expr *castExpr) {
5374 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005375 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005376
John McCall97513962010-01-15 18:39:57 +00005377 TypeSourceInfo *castTInfo;
5378 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5379 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005380 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005381
Nate Begeman5ec4b312009-08-10 23:49:36 +00005382 // If the Expr being casted is a ParenListExpr, handle it specially.
5383 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005384 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005385 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005386
John McCallb268a282010-08-23 23:25:46 +00005387 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005388}
5389
John McCalldadc5752010-08-24 06:29:42 +00005390ExprResult
John McCallebe54742010-01-15 18:56:44 +00005391Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005392 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005393 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005394 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005395 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005396 ExprResult CastResult =
5397 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5398 Kind, VK, BasePath);
5399 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005400 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005401 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005402
John McCallcf142162010-08-07 06:22:56 +00005403 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005404 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005405 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005406 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005407}
5408
Nate Begeman5ec4b312009-08-10 23:49:36 +00005409/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5410/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005411ExprResult
John McCallb268a282010-08-23 23:25:46 +00005412Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005413 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5414 if (!E)
5415 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005416
John McCalldadc5752010-08-24 06:29:42 +00005417 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005418
Nate Begeman5ec4b312009-08-10 23:49:36 +00005419 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005420 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5421 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005422
John McCallb268a282010-08-23 23:25:46 +00005423 if (Result.isInvalid()) return ExprError();
5424
5425 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005426}
5427
John McCalldadc5752010-08-24 06:29:42 +00005428ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005429Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005430 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005431 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005432 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005433 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005434 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005435
Anton Yartsev28ccef72011-03-27 09:32:40 +00005436 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005437 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005438 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5439 if (PE->getNumExprs() == 0) {
5440 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5441 return ExprError();
5442 }
John Thompson781ad172010-06-30 22:55:51 +00005443 if (PE->getNumExprs() == 1) {
5444 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005445 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005446 }
5447 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005448 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005449 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005450
Anton Yartsev28ccef72011-03-27 09:32:40 +00005451 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005452 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005453 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005454 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005455 // '(...)' form of vector initialization in AltiVec: the number of
5456 // initializers must be one or must match the size of the vector.
5457 // If a single value is specified in the initializer then it will be
5458 // replicated to all the components of the vector
5459 if (Ty->getAs<VectorType>()->getVectorKind() ==
5460 VectorType::AltiVecVector) {
5461 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5462 // The number of initializers must be one or must match the size of the
5463 // vector. If a single value is specified in the initializer then it will
5464 // be replicated to all the components of the vector
5465 if (PE->getNumExprs() == 1) {
5466 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005467 ExprResult Literal = Owned(PE->getExpr(0));
5468 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5469 PrepareScalarCast(*this, Literal, ElemTy));
5470 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005471 }
5472 else if (PE->getNumExprs() < numElems) {
5473 Diag(PE->getExprLoc(),
5474 diag::err_incorrect_number_of_vector_initializers);
5475 return ExprError();
5476 }
5477 else
5478 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5479 initExprs.push_back(PE->getExpr(i));
5480 }
5481 else
5482 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5483 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005484
5485 // FIXME: This means that pretty-printing the final AST will produce curly
5486 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005487 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5488 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005489 initExprs.size(), RParenLoc);
5490 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005491 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005492 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005493 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005494 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005495 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005496 if (Result.isInvalid()) return ExprError();
5497 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005498 }
5499}
5500
John McCalldadc5752010-08-24 06:29:42 +00005501ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005502 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005503 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005504 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005505 unsigned nexprs = Val.size();
5506 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005507 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5508 Expr *expr;
5509 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5510 expr = new (Context) ParenExpr(L, R, exprs[0]);
5511 else
5512 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005513 return Owned(expr);
5514}
5515
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005516/// \brief Emit a specialized diagnostic when one expression is a null pointer
5517/// constant and the other is not a pointer.
5518bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5519 SourceLocation QuestionLoc) {
5520 Expr *NullExpr = LHS;
5521 Expr *NonPointerExpr = RHS;
5522 Expr::NullPointerConstantKind NullKind =
5523 NullExpr->isNullPointerConstant(Context,
5524 Expr::NPC_ValueDependentIsNotNull);
5525
5526 if (NullKind == Expr::NPCK_NotNull) {
5527 NullExpr = RHS;
5528 NonPointerExpr = LHS;
5529 NullKind =
5530 NullExpr->isNullPointerConstant(Context,
5531 Expr::NPC_ValueDependentIsNotNull);
5532 }
5533
5534 if (NullKind == Expr::NPCK_NotNull)
5535 return false;
5536
5537 if (NullKind == Expr::NPCK_ZeroInteger) {
5538 // In this case, check to make sure that we got here from a "NULL"
5539 // string in the source code.
5540 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005541 SourceLocation loc = NullExpr->getExprLoc();
5542 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005543 return false;
5544 }
5545
5546 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5547 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5548 << NonPointerExpr->getType() << DiagType
5549 << NonPointerExpr->getSourceRange();
5550 return true;
5551}
5552
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005553/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5554/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005555/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005556QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005557 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005558 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005559
John McCall3aef3d82011-04-10 19:13:55 +00005560 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005561 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005562 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005563
John McCall3aef3d82011-04-10 19:13:55 +00005564 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005565 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005566 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005567
Sebastian Redl1a99f442009-04-16 17:51:27 +00005568 // C++ is sufficiently different to merit its own checker.
5569 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005570 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005571
5572 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005573 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005574
John Wiegley01296292011-04-08 18:41:53 +00005575 Cond = UsualUnaryConversions(Cond.take());
5576 if (Cond.isInvalid())
5577 return QualType();
5578 LHS = UsualUnaryConversions(LHS.take());
5579 if (LHS.isInvalid())
5580 return QualType();
5581 RHS = UsualUnaryConversions(RHS.take());
5582 if (RHS.isInvalid())
5583 return QualType();
5584
5585 QualType CondTy = Cond.get()->getType();
5586 QualType LHSTy = LHS.get()->getType();
5587 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005588
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005589 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005590 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005591 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5592 // Throw an error if its not either.
5593 if (getLangOptions().OpenCL) {
5594 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005595 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005596 diag::err_typecheck_cond_expect_scalar_or_vector)
5597 << CondTy;
5598 return QualType();
5599 }
5600 }
5601 else {
John Wiegley01296292011-04-08 18:41:53 +00005602 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005603 << CondTy;
5604 return QualType();
5605 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005606 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005607
Chris Lattnere2949f42008-01-06 22:42:25 +00005608 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005609 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5610 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005611
Nate Begemanabb5a732010-09-20 22:41:17 +00005612 // OpenCL: If the condition is a vector, and both operands are scalar,
5613 // attempt to implicity convert them to the vector type to act like the
5614 // built in select.
5615 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5616 // Both operands should be of scalar type.
5617 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005618 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005619 << CondTy;
5620 return QualType();
5621 }
5622 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005623 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005624 << CondTy;
5625 return QualType();
5626 }
5627 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005628 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5629 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005630 }
5631
Chris Lattnere2949f42008-01-06 22:42:25 +00005632 // If both operands have arithmetic type, do the usual arithmetic conversions
5633 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005634 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5635 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005636 if (LHS.isInvalid() || RHS.isInvalid())
5637 return QualType();
5638 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005639 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005640
Chris Lattnere2949f42008-01-06 22:42:25 +00005641 // If both operands are the same structure or union type, the result is that
5642 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005643 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5644 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005645 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005646 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005647 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005648 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005649 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005650 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005651
Chris Lattnere2949f42008-01-06 22:42:25 +00005652 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005653 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005654 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5655 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005656 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5657 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005658 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005659 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5660 << LHS.get()->getSourceRange();
5661 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5662 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005663 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005664 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005665 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5666 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005667 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005668 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005669 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005670 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005671 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005672 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005673 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005674 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5675 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005676 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005677 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005678
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005679 // All objective-c pointer type analysis is done here.
5680 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5681 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005682 if (LHS.isInvalid() || RHS.isInvalid())
5683 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005684 if (!compositeType.isNull())
5685 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005686
5687
Steve Naroff05efa972009-07-01 14:36:47 +00005688 // Handle block pointer types.
5689 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5690 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5691 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5692 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005693 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5694 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005695 return destType;
5696 }
5697 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005698 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005699 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005700 }
Steve Naroff05efa972009-07-01 14:36:47 +00005701 // We have 2 block pointer types.
5702 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5703 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005704 return LHSTy;
5705 }
Steve Naroff05efa972009-07-01 14:36:47 +00005706 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005707 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5708 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005709
Steve Naroff05efa972009-07-01 14:36:47 +00005710 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5711 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005712 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005713 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005714 // In this situation, we assume void* type. No especially good
5715 // reason, but this is what gcc does, and we do have to pick
5716 // to get a consistent AST.
5717 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005718 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5719 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005720 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005721 }
Steve Naroff05efa972009-07-01 14:36:47 +00005722 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005723 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5724 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005725 return LHSTy;
5726 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005727
Steve Naroff05efa972009-07-01 14:36:47 +00005728 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5729 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5730 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005731 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5732 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005733
5734 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5735 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5736 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005737 QualType destPointee
5738 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005739 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005740 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005741 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005742 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005743 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005744 return destType;
5745 }
5746 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005747 QualType destPointee
5748 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005749 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005750 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005751 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005752 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005753 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005754 return destType;
5755 }
5756
5757 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5758 // Two identical pointer types are always compatible.
5759 return LHSTy;
5760 }
5761 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5762 rhptee.getUnqualifiedType())) {
5763 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005764 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005765 // In this situation, we assume void* type. No especially good
5766 // reason, but this is what gcc does, and we do have to pick
5767 // to get a consistent AST.
5768 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005769 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5770 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005771 return incompatTy;
5772 }
5773 // The pointer types are compatible.
5774 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5775 // differently qualified versions of compatible types, the result type is
5776 // a pointer to an appropriately qualified version of the *composite*
5777 // type.
5778 // FIXME: Need to calculate the composite type.
5779 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005780 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5781 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005782 return LHSTy;
5783 }
Mike Stump11289f42009-09-09 15:08:12 +00005784
John McCalle84af4e2010-11-13 01:35:44 +00005785 // GCC compatibility: soften pointer/integer mismatch. Note that
5786 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005787 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5788 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005789 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5790 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005791 return RHSTy;
5792 }
5793 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5794 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005795 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5796 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005797 return LHSTy;
5798 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005799
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005800 // Emit a better diagnostic if one of the expressions is a null pointer
5801 // constant and the other is not a pointer type. In this case, the user most
5802 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005803 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005804 return QualType();
5805
Chris Lattnere2949f42008-01-06 22:42:25 +00005806 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005807 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005808 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005809 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005810}
5811
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005812/// FindCompositeObjCPointerType - Helper method to find composite type of
5813/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005814QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005815 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005816 QualType LHSTy = LHS.get()->getType();
5817 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005818
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005819 // Handle things like Class and struct objc_class*. Here we case the result
5820 // to the pseudo-builtin, because that will be implicitly cast back to the
5821 // redefinition type if an attempt is made to access its fields.
5822 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005823 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005824 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005825 return LHSTy;
5826 }
5827 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005828 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005829 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005830 return RHSTy;
5831 }
5832 // And the same for struct objc_object* / id
5833 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005834 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005835 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005836 return LHSTy;
5837 }
5838 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005839 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005840 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005841 return RHSTy;
5842 }
5843 // And the same for struct objc_selector* / SEL
5844 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005845 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005846 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005847 return LHSTy;
5848 }
5849 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005850 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005851 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005852 return RHSTy;
5853 }
5854 // Check constraints for Objective-C object pointers types.
5855 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005856
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005857 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5858 // Two identical object pointer types are always compatible.
5859 return LHSTy;
5860 }
5861 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5862 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5863 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005864
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005865 // If both operands are interfaces and either operand can be
5866 // assigned to the other, use that type as the composite
5867 // type. This allows
5868 // xxx ? (A*) a : (B*) b
5869 // where B is a subclass of A.
5870 //
5871 // Additionally, as for assignment, if either type is 'id'
5872 // allow silent coercion. Finally, if the types are
5873 // incompatible then make sure to use 'id' as the composite
5874 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005875
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005876 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5877 // It could return the composite type.
5878 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5879 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5880 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5881 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5882 } else if ((LHSTy->isObjCQualifiedIdType() ||
5883 RHSTy->isObjCQualifiedIdType()) &&
5884 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5885 // Need to handle "id<xx>" explicitly.
5886 // GCC allows qualified id and any Objective-C type to devolve to
5887 // id. Currently localizing to here until clear this should be
5888 // part of ObjCQualifiedIdTypesAreCompatible.
5889 compositeType = Context.getObjCIdType();
5890 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5891 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005892 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005893 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5894 ;
5895 else {
5896 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5897 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005898 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005899 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005900 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5901 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005902 return incompatTy;
5903 }
5904 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005905 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5906 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005907 return compositeType;
5908 }
5909 // Check Objective-C object pointer types and 'void *'
5910 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5911 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5912 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5913 QualType destPointee
5914 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5915 QualType destType = Context.getPointerType(destPointee);
5916 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005917 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005918 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005919 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005920 return destType;
5921 }
5922 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5923 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5924 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5925 QualType destPointee
5926 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5927 QualType destType = Context.getPointerType(destPointee);
5928 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005929 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005930 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005931 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005932 return destType;
5933 }
5934 return QualType();
5935}
5936
Steve Naroff83895f72007-09-16 03:34:24 +00005937/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005938/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005939ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005940 SourceLocation ColonLoc,
5941 Expr *CondExpr, Expr *LHSExpr,
5942 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005943 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5944 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005945 OpaqueValueExpr *opaqueValue = 0;
5946 Expr *commonExpr = 0;
5947 if (LHSExpr == 0) {
5948 commonExpr = CondExpr;
5949
5950 // We usually want to apply unary conversions *before* saving, except
5951 // in the special case of a C++ l-value conditional.
5952 if (!(getLangOptions().CPlusPlus
5953 && !commonExpr->isTypeDependent()
5954 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5955 && commonExpr->isGLValue()
5956 && commonExpr->isOrdinaryOrBitFieldObject()
5957 && RHSExpr->isOrdinaryOrBitFieldObject()
5958 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005959 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5960 if (commonRes.isInvalid())
5961 return ExprError();
5962 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005963 }
5964
5965 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5966 commonExpr->getType(),
5967 commonExpr->getValueKind(),
5968 commonExpr->getObjectKind());
5969 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005970 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005971
John McCall7decc9e2010-11-18 06:31:45 +00005972 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005973 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005974 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5975 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005976 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005977 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5978 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005979 return ExprError();
5980
John McCallc07a0c72011-02-17 10:25:35 +00005981 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005982 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5983 LHS.take(), ColonLoc,
5984 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005985
5986 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005987 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5988 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005989}
5990
John McCallaba90822011-01-31 23:13:11 +00005991// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005993// routine is it effectively iqnores the qualifiers on the top level pointee.
5994// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5995// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005996static Sema::AssignConvertType
5997checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5998 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5999 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006000
Steve Naroff1f4d7272007-05-11 04:00:31 +00006001 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006002 const Type *lhptee, *rhptee;
6003 Qualifiers lhq, rhq;
6004 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6005 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006006
John McCallaba90822011-01-31 23:13:11 +00006007 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006008
6009 // C99 6.5.16.1p1: This following citation is common to constraints
6010 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6011 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006012 Qualifiers lq;
6013
6014 if (!lhq.compatiblyIncludes(rhq)) {
6015 // Treat address-space mismatches as fatal. TODO: address subspaces
6016 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6017 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6018
John McCall78535952011-03-26 02:56:45 +00006019 // It's okay to add or remove GC qualifiers when converting to
6020 // and from void*.
6021 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6022 && (lhptee->isVoidType() || rhptee->isVoidType()))
6023 ; // keep old
6024
John McCall4fff8f62011-02-01 00:10:29 +00006025 // For GCC compatibility, other qualifier mismatches are treated
6026 // as still compatible in C.
6027 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6028 }
Steve Naroff3f597292007-05-11 22:18:03 +00006029
Mike Stump4e1f26a2009-02-19 03:04:26 +00006030 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6031 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006032 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006033 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006034 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006035 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006036
Chris Lattner0a788432008-01-03 22:56:36 +00006037 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006038 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006039 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006040 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006041
Chris Lattner0a788432008-01-03 22:56:36 +00006042 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006043 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006044 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006045
6046 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006047 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006048 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006049 }
John McCall4fff8f62011-02-01 00:10:29 +00006050
Mike Stump4e1f26a2009-02-19 03:04:26 +00006051 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006052 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006053 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6054 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006055 // Check if the pointee types are compatible ignoring the sign.
6056 // We explicitly check for char so that we catch "char" vs
6057 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006058 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006059 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006060 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006061 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006062
Chris Lattnerec3a1562009-10-17 20:33:28 +00006063 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006064 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006065 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006066 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006067
John McCall4fff8f62011-02-01 00:10:29 +00006068 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006069 // Types are compatible ignoring the sign. Qualifier incompatibility
6070 // takes priority over sign incompatibility because the sign
6071 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006072 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006073 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006074
John McCallaba90822011-01-31 23:13:11 +00006075 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006076 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006077
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006078 // If we are a multi-level pointer, it's possible that our issue is simply
6079 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6080 // the eventual target type is the same and the pointers have the same
6081 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006082 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006083 do {
John McCall4fff8f62011-02-01 00:10:29 +00006084 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6085 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006086 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006087
John McCall4fff8f62011-02-01 00:10:29 +00006088 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006089 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006090 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006091
Eli Friedman80160bd2009-03-22 23:59:44 +00006092 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006093 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006094 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006095 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006096}
6097
John McCallaba90822011-01-31 23:13:11 +00006098/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006099/// block pointer types are compatible or whether a block and normal pointer
6100/// are compatible. It is more restrict than comparing two function pointer
6101// types.
John McCallaba90822011-01-31 23:13:11 +00006102static Sema::AssignConvertType
6103checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6104 QualType rhsType) {
6105 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6106 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6107
Steve Naroff081c7422008-09-04 15:10:53 +00006108 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006109
Steve Naroff081c7422008-09-04 15:10:53 +00006110 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006111 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6112 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006113
John McCallaba90822011-01-31 23:13:11 +00006114 // In C++, the types have to match exactly.
6115 if (S.getLangOptions().CPlusPlus)
6116 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006117
John McCallaba90822011-01-31 23:13:11 +00006118 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006119
Steve Naroff081c7422008-09-04 15:10:53 +00006120 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006121 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6122 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006123
John McCallaba90822011-01-31 23:13:11 +00006124 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6125 return Sema::IncompatibleBlockPointer;
6126
Steve Naroff081c7422008-09-04 15:10:53 +00006127 return ConvTy;
6128}
6129
John McCallaba90822011-01-31 23:13:11 +00006130/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006131/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006132static Sema::AssignConvertType
6133checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6134 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6135 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6136
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006137 if (lhsType->isObjCBuiltinType()) {
6138 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006139 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6140 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006141 return Sema::IncompatiblePointer;
6142 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006143 }
6144 if (rhsType->isObjCBuiltinType()) {
6145 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006146 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6147 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006148 return Sema::IncompatiblePointer;
6149 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006150 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006151 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006152 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006153 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006154 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006155
John McCallaba90822011-01-31 23:13:11 +00006156 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6157 return Sema::CompatiblePointerDiscardsQualifiers;
6158
6159 if (S.Context.typesAreCompatible(lhsType, rhsType))
6160 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006161 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006162 return Sema::IncompatibleObjCQualifiedId;
6163 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006164}
6165
John McCall29600e12010-11-16 02:32:08 +00006166Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006167Sema::CheckAssignmentConstraints(SourceLocation Loc,
6168 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006169 // Fake up an opaque expression. We don't actually care about what
6170 // cast operations are required, so if CheckAssignmentConstraints
6171 // adds casts to this they'll be wasted, but fortunately that doesn't
6172 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006173 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006174 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006175 CastKind K = CK_Invalid;
6176
6177 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6178}
6179
Mike Stump4e1f26a2009-02-19 03:04:26 +00006180/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6181/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006182/// pointers. Here are some objectionable examples that GCC considers warnings:
6183///
6184/// int a, *pint;
6185/// short *pshort;
6186/// struct foo *pfoo;
6187///
6188/// pint = pshort; // warning: assignment from incompatible pointer type
6189/// a = pint; // warning: assignment makes integer from pointer without a cast
6190/// pint = a; // warning: assignment makes pointer from integer without a cast
6191/// pint = pfoo; // warning: assignment from incompatible pointer type
6192///
6193/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006194/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006195///
John McCall8cb679e2010-11-15 09:13:47 +00006196/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006197Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006198Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006199 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006200 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006201
Chris Lattnera52c2f22008-01-04 23:18:45 +00006202 // Get canonical types. We're not formatting these types, just comparing
6203 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006204 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6205 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006206
John McCalle5255932011-01-31 22:28:28 +00006207 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006208 if (lhsType == rhsType) {
6209 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006210 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006211 }
6212
Douglas Gregor6b754842008-10-28 00:22:11 +00006213 // If the left-hand side is a reference type, then we are in a
6214 // (rare!) case where we've allowed the use of references in C,
6215 // e.g., as a parameter type in a built-in function. In this case,
6216 // just make sure that the type referenced is compatible with the
6217 // right-hand side type. The caller is responsible for adjusting
6218 // lhsType so that the resulting expression does not have reference
6219 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006220 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006221 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6222 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006223 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006224 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006225 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006226 }
John McCalle5255932011-01-31 22:28:28 +00006227
Nate Begemanbd956c42009-06-28 02:36:38 +00006228 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6229 // to the same ExtVector type.
6230 if (lhsType->isExtVectorType()) {
6231 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006232 return Incompatible;
6233 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006234 // CK_VectorSplat does T -> vector T, so first cast to the
6235 // element type.
6236 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6237 if (elType != rhsType) {
6238 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006239 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006240 }
6241 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006242 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006243 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006244 }
Mike Stump11289f42009-09-09 15:08:12 +00006245
John McCalle5255932011-01-31 22:28:28 +00006246 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006247 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006248 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006249 // Allow assignments of an AltiVec vector type to an equivalent GCC
6250 // vector type and vice versa
6251 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6252 Kind = CK_BitCast;
6253 return Compatible;
6254 }
6255
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006256 // If we are allowing lax vector conversions, and LHS and RHS are both
6257 // vectors, the total size only needs to be the same. This is a bitcast;
6258 // no bits are changed but the result type is different.
6259 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006260 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006261 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006262 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006263 }
Chris Lattner881a2122008-01-04 23:32:24 +00006264 }
6265 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006266 }
Eli Friedman3360d892008-05-30 18:07:22 +00006267
John McCalle5255932011-01-31 22:28:28 +00006268 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006269 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006270 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006271 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006272 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006273 }
Eli Friedman3360d892008-05-30 18:07:22 +00006274
John McCalle5255932011-01-31 22:28:28 +00006275 // Conversions to normal pointers.
6276 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6277 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006278 if (isa<PointerType>(rhsType)) {
6279 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006280 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006281 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006282
John McCalle5255932011-01-31 22:28:28 +00006283 // int -> T*
6284 if (rhsType->isIntegerType()) {
6285 Kind = CK_IntegralToPointer; // FIXME: null?
6286 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006287 }
John McCalle5255932011-01-31 22:28:28 +00006288
6289 // C pointers are not compatible with ObjC object pointers,
6290 // with two exceptions:
6291 if (isa<ObjCObjectPointerType>(rhsType)) {
6292 // - conversions to void*
6293 if (lhsPointer->getPointeeType()->isVoidType()) {
6294 Kind = CK_AnyPointerToObjCPointerCast;
6295 return Compatible;
6296 }
6297
6298 // - conversions from 'Class' to the redefinition type
6299 if (rhsType->isObjCClassType() &&
6300 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006301 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006302 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006303 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006304
John McCalle5255932011-01-31 22:28:28 +00006305 Kind = CK_BitCast;
6306 return IncompatiblePointer;
6307 }
6308
6309 // U^ -> void*
6310 if (rhsType->getAs<BlockPointerType>()) {
6311 if (lhsPointer->getPointeeType()->isVoidType()) {
6312 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006313 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006314 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006315 }
John McCalle5255932011-01-31 22:28:28 +00006316
Steve Naroff081c7422008-09-04 15:10:53 +00006317 return Incompatible;
6318 }
6319
John McCalle5255932011-01-31 22:28:28 +00006320 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006321 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006322 // U^ -> T^
6323 if (rhsType->isBlockPointerType()) {
6324 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006325 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006326 }
6327
6328 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006329 if (rhsType->isIntegerType()) {
6330 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006331 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006332 }
6333
John McCalle5255932011-01-31 22:28:28 +00006334 // id -> T^
6335 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6336 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006337 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006338 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006339
John McCalle5255932011-01-31 22:28:28 +00006340 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006341 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006342 if (RHSPT->getPointeeType()->isVoidType()) {
6343 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006344 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006345 }
John McCall8cb679e2010-11-15 09:13:47 +00006346
Chris Lattnera52c2f22008-01-04 23:18:45 +00006347 return Incompatible;
6348 }
6349
John McCalle5255932011-01-31 22:28:28 +00006350 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006351 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006352 // A* -> B*
6353 if (rhsType->isObjCObjectPointerType()) {
6354 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006355 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006356 }
6357
6358 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006359 if (rhsType->isIntegerType()) {
6360 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006361 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006362 }
6363
John McCalle5255932011-01-31 22:28:28 +00006364 // In general, C pointers are not compatible with ObjC object pointers,
6365 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006366 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006367 // - conversions from 'void*'
6368 if (rhsType->isVoidPointerType()) {
6369 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006370 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006371 }
6372
6373 // - conversions to 'Class' from its redefinition type
6374 if (lhsType->isObjCClassType() &&
6375 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6376 Kind = CK_BitCast;
6377 return Compatible;
6378 }
6379
6380 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006381 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006382 }
John McCalle5255932011-01-31 22:28:28 +00006383
6384 // T^ -> A*
6385 if (rhsType->isBlockPointerType()) {
6386 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006387 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006388 }
6389
Steve Naroff7cae42b2009-07-10 23:34:53 +00006390 return Incompatible;
6391 }
John McCalle5255932011-01-31 22:28:28 +00006392
6393 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006394 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006395 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006396 if (lhsType == Context.BoolTy) {
6397 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006398 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006399 }
Eli Friedman3360d892008-05-30 18:07:22 +00006400
John McCalle5255932011-01-31 22:28:28 +00006401 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006402 if (lhsType->isIntegerType()) {
6403 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006404 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006405 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006406
Chris Lattnera52c2f22008-01-04 23:18:45 +00006407 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006408 }
John McCalle5255932011-01-31 22:28:28 +00006409
6410 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006411 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006412 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006413 if (lhsType == Context.BoolTy) {
6414 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006415 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006416 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006417
John McCalle5255932011-01-31 22:28:28 +00006418 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006419 if (lhsType->isIntegerType()) {
6420 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006421 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006422 }
6423
Steve Naroff7cae42b2009-07-10 23:34:53 +00006424 return Incompatible;
6425 }
Eli Friedman3360d892008-05-30 18:07:22 +00006426
John McCalle5255932011-01-31 22:28:28 +00006427 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006428 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006429 if (Context.typesAreCompatible(lhsType, rhsType)) {
6430 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006431 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006432 }
Bill Wendling216423b2007-05-30 06:30:29 +00006433 }
John McCalle5255932011-01-31 22:28:28 +00006434
Steve Naroff98cf3e92007-06-06 18:38:38 +00006435 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006436}
6437
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006438/// \brief Constructs a transparent union from an expression that is
6439/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006440static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006441 QualType UnionType, FieldDecl *Field) {
6442 // Build an initializer list that designates the appropriate member
6443 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006444 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006445 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006446 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006447 SourceLocation());
6448 Initializer->setType(UnionType);
6449 Initializer->setInitializedFieldInUnion(Field);
6450
6451 // Build a compound literal constructing a value of the transparent
6452 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006453 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006454 EResult = S.Owned(
6455 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6456 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006457}
6458
6459Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006460Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6461 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006462
Mike Stump11289f42009-09-09 15:08:12 +00006463 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006464 // transparent_union GCC extension.
6465 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006466 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006467 return Incompatible;
6468
6469 // The field to initialize within the transparent union.
6470 RecordDecl *UD = UT->getDecl();
6471 FieldDecl *InitField = 0;
6472 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006473 for (RecordDecl::field_iterator it = UD->field_begin(),
6474 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006475 it != itend; ++it) {
6476 if (it->getType()->isPointerType()) {
6477 // If the transparent union contains a pointer type, we allow:
6478 // 1) void pointer
6479 // 2) null pointer constant
6480 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006481 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006482 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006483 InitField = *it;
6484 break;
6485 }
Mike Stump11289f42009-09-09 15:08:12 +00006486
John Wiegley01296292011-04-08 18:41:53 +00006487 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006488 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006489 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006490 InitField = *it;
6491 break;
6492 }
6493 }
6494
John McCall8cb679e2010-11-15 09:13:47 +00006495 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006496 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006497 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006498 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006499 InitField = *it;
6500 break;
6501 }
6502 }
6503
6504 if (!InitField)
6505 return Incompatible;
6506
John Wiegley01296292011-04-08 18:41:53 +00006507 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006508 return Compatible;
6509}
6510
Chris Lattner9bad62c2008-01-04 18:04:52 +00006511Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006512Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006513 if (getLangOptions().CPlusPlus) {
6514 if (!lhsType->isRecordType()) {
6515 // C++ 5.17p3: If the left operand is not of class type, the
6516 // expression is implicitly converted (C++ 4) to the
6517 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006518 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6519 lhsType.getUnqualifiedType(),
6520 AA_Assigning);
6521 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006522 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006523 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006524 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006525 }
6526
6527 // FIXME: Currently, we fall through and treat C++ classes like C
6528 // structures.
John McCall34376a62010-12-04 03:47:34 +00006529 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006530
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006531 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6532 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006533 if ((lhsType->isPointerType() ||
6534 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006535 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006536 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006537 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006538 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006539 return Compatible;
6540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006541
Chris Lattnere6dcd502007-10-16 02:55:40 +00006542 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006543 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006544 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006545 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006546 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006547 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006548 if (!lhsType->isReferenceType()) {
6549 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6550 if (rExpr.isInvalid())
6551 return Incompatible;
6552 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006553
John McCall8cb679e2010-11-15 09:13:47 +00006554 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006555 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006556 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006557
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006558 // C99 6.5.16.1p2: The value of the right operand is converted to the
6559 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006560 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6561 // so that we can use references in built-in functions even in C.
6562 // The getNonReferenceType() call makes sure that the resulting expression
6563 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006564 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6565 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006566 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006567}
6568
John Wiegley01296292011-04-08 18:41:53 +00006569QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006570 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006571 << lex.get()->getType() << rex.get()->getType()
6572 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006573 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006574}
6575
John Wiegley01296292011-04-08 18:41:53 +00006576QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006577 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006578 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006579 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006580 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006581 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006582 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006583
Nate Begeman191a6b12008-07-14 18:02:46 +00006584 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006585 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006586 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006587
Nate Begeman191a6b12008-07-14 18:02:46 +00006588 // Handle the case of a vector & extvector type of the same size and element
6589 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006590 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006591 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006592 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006593 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006594 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006595 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006596 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006597 return lhsType;
6598 }
6599
John Wiegley01296292011-04-08 18:41:53 +00006600 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006601 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006602 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6603 // If we are allowing lax vector conversions, and LHS and RHS are both
6604 // vectors, the total size only needs to be the same. This is a
6605 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006606 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006607 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006608 }
Eric Christophera613f562010-08-26 00:42:16 +00006609 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006610 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006611 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006612
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006613 // Handle the case of equivalent AltiVec and GCC vector types
6614 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6615 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006616 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006617 return rhsType;
6618 }
6619
Nate Begemanbd956c42009-06-28 02:36:38 +00006620 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6621 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6622 bool swapped = false;
6623 if (rhsType->isExtVectorType()) {
6624 swapped = true;
6625 std::swap(rex, lex);
6626 std::swap(rhsType, lhsType);
6627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Nate Begeman886448d2009-06-28 19:12:57 +00006629 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006630 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006631 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006632 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006633 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6634 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006635 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006636 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006637 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006638 if (swapped) std::swap(rex, lex);
6639 return lhsType;
6640 }
6641 }
6642 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6643 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006644 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6645 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006646 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006647 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006648 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006649 if (swapped) std::swap(rex, lex);
6650 return lhsType;
6651 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006652 }
6653 }
Mike Stump11289f42009-09-09 15:08:12 +00006654
Nate Begeman886448d2009-06-28 19:12:57 +00006655 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006656 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006657 << lex.get()->getType() << rex.get()->getType()
6658 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006659 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006660}
6661
Chris Lattnerfaa54172010-01-12 21:23:57 +00006662QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006663 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6664 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006665 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006666
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006667 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006668 if (lex.isInvalid() || rex.isInvalid())
6669 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006670
John Wiegley01296292011-04-08 18:41:53 +00006671 if (!lex.get()->getType()->isArithmeticType() ||
6672 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006673 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006674
Chris Lattnerfaa54172010-01-12 21:23:57 +00006675 // Check for division by zero.
6676 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006677 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6678 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6679 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006680
Chris Lattnerfaa54172010-01-12 21:23:57 +00006681 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006682}
6683
Chris Lattnerfaa54172010-01-12 21:23:57 +00006684QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006685 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6686 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6687 if (lex.get()->getType()->hasIntegerRepresentation() &&
6688 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006689 return CheckVectorOperands(Loc, lex, rex);
6690 return InvalidOperands(Loc, lex, rex);
6691 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006692
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006693 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006694 if (lex.isInvalid() || rex.isInvalid())
6695 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006696
John Wiegley01296292011-04-08 18:41:53 +00006697 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006698 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006699
Chris Lattnerfaa54172010-01-12 21:23:57 +00006700 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006701 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6702 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6703 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006704
Chris Lattnerfaa54172010-01-12 21:23:57 +00006705 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006706}
6707
Chris Lattnerfaa54172010-01-12 21:23:57 +00006708QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006709 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6710 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006711 QualType compType = CheckVectorOperands(Loc, lex, rex);
6712 if (CompLHSTy) *CompLHSTy = compType;
6713 return compType;
6714 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006715
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006716 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006717 if (lex.isInvalid() || rex.isInvalid())
6718 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006719
Steve Naroffe4718892007-04-27 18:30:00 +00006720 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006721 if (lex.get()->getType()->isArithmeticType() &&
6722 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006723 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006724 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006725 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006726
Eli Friedman8e122982008-05-18 18:08:51 +00006727 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006728 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006729 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006730 std::swap(PExp, IExp);
6731
Steve Naroff6b712a72009-07-14 18:25:06 +00006732 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006733
Eli Friedman8e122982008-05-18 18:08:51 +00006734 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006735 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006736
Chris Lattner12bdebb2009-04-24 23:50:08 +00006737 // Check for arithmetic on pointers to incomplete types.
6738 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006739 if (getLangOptions().CPlusPlus) {
6740 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006741 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006742 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006743 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006744
6745 // GNU extension: arithmetic on pointer to void
6746 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006747 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006748 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006749 if (getLangOptions().CPlusPlus) {
6750 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006751 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006752 return QualType();
6753 }
6754
6755 // GNU extension: arithmetic on pointer to function
6756 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006757 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006758 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006759 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006760 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006761 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006762 PExp->getType()->isObjCObjectPointerType()) &&
6763 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006764 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6765 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006766 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006767 return QualType();
6768 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006769 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006770 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006771 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6772 << PointeeTy << PExp->getSourceRange();
6773 return QualType();
6774 }
Mike Stump11289f42009-09-09 15:08:12 +00006775
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006776 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006777 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006778 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006779 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006780 if (LHSTy->isPromotableIntegerType())
6781 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006782 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006783 *CompLHSTy = LHSTy;
6784 }
Eli Friedman8e122982008-05-18 18:08:51 +00006785 return PExp->getType();
6786 }
6787 }
6788
Chris Lattner326f7572008-11-18 01:30:42 +00006789 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006790}
6791
Chris Lattner2a3569b2008-04-07 05:30:13 +00006792// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006793QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006794 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006795 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006796 QualType compType = CheckVectorOperands(Loc, lex, rex);
6797 if (CompLHSTy) *CompLHSTy = compType;
6798 return compType;
6799 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006800
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006801 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006802 if (lex.isInvalid() || rex.isInvalid())
6803 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006804
Chris Lattner4d62f422007-12-09 21:53:25 +00006805 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006806
Chris Lattner4d62f422007-12-09 21:53:25 +00006807 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006808 if (lex.get()->getType()->isArithmeticType() &&
6809 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006810 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006811 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006812 }
Mike Stump11289f42009-09-09 15:08:12 +00006813
Chris Lattner4d62f422007-12-09 21:53:25 +00006814 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006815 if (lex.get()->getType()->isAnyPointerType()) {
6816 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006817
Douglas Gregorac1fb652009-03-24 19:52:54 +00006818 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006819
Douglas Gregorac1fb652009-03-24 19:52:54 +00006820 bool ComplainAboutVoid = false;
6821 Expr *ComplainAboutFunc = 0;
6822 if (lpointee->isVoidType()) {
6823 if (getLangOptions().CPlusPlus) {
6824 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006825 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006826 return QualType();
6827 }
6828
6829 // GNU C extension: arithmetic on pointer to void
6830 ComplainAboutVoid = true;
6831 } else if (lpointee->isFunctionType()) {
6832 if (getLangOptions().CPlusPlus) {
6833 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006834 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006835 return QualType();
6836 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006837
6838 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00006839 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006840 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006841 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006842 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006843 << lex.get()->getSourceRange()
6844 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006845 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006846
Chris Lattner12bdebb2009-04-24 23:50:08 +00006847 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006848 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006849 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006850 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006851 return QualType();
6852 }
Mike Stump11289f42009-09-09 15:08:12 +00006853
Chris Lattner4d62f422007-12-09 21:53:25 +00006854 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006855 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006856 if (ComplainAboutVoid)
6857 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006858 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006859 if (ComplainAboutFunc)
6860 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006861 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006862 << ComplainAboutFunc->getSourceRange();
6863
John Wiegley01296292011-04-08 18:41:53 +00006864 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6865 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006866 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006867
Chris Lattner4d62f422007-12-09 21:53:25 +00006868 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00006869 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006870 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006871
Douglas Gregorac1fb652009-03-24 19:52:54 +00006872 // RHS must be a completely-type object type.
6873 // Handle the GNU void* extension.
6874 if (rpointee->isVoidType()) {
6875 if (getLangOptions().CPlusPlus) {
6876 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006877 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006878 return QualType();
6879 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006880
Douglas Gregorac1fb652009-03-24 19:52:54 +00006881 ComplainAboutVoid = true;
6882 } else if (rpointee->isFunctionType()) {
6883 if (getLangOptions().CPlusPlus) {
6884 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006885 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006886 return QualType();
6887 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006888
6889 // GNU extension: arithmetic on pointer to function
6890 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00006891 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006892 } else if (!rpointee->isDependentType() &&
6893 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006894 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006895 << rex.get()->getSourceRange()
6896 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006897 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006898
Eli Friedman168fe152009-05-16 13:54:38 +00006899 if (getLangOptions().CPlusPlus) {
6900 // Pointee types must be the same: C++ [expr.add]
6901 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6902 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006903 << lex.get()->getType() << rex.get()->getType()
6904 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006905 return QualType();
6906 }
6907 } else {
6908 // Pointee types must be compatible C99 6.5.6p3
6909 if (!Context.typesAreCompatible(
6910 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6911 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6912 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006913 << lex.get()->getType() << rex.get()->getType()
6914 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006915 return QualType();
6916 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006917 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006918
Douglas Gregorac1fb652009-03-24 19:52:54 +00006919 if (ComplainAboutVoid)
6920 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006921 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006922 if (ComplainAboutFunc)
6923 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006924 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006925 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006926
John Wiegley01296292011-04-08 18:41:53 +00006927 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006928 return Context.getPointerDiffType();
6929 }
6930 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006931
Chris Lattner326f7572008-11-18 01:30:42 +00006932 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006933}
6934
Douglas Gregor0bf31402010-10-08 23:50:27 +00006935static bool isScopedEnumerationType(QualType T) {
6936 if (const EnumType *ET = dyn_cast<EnumType>(T))
6937 return ET->getDecl()->isScoped();
6938 return false;
6939}
6940
John Wiegley01296292011-04-08 18:41:53 +00006941static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006942 SourceLocation Loc, unsigned Opc,
6943 QualType LHSTy) {
6944 llvm::APSInt Right;
6945 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00006946 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006947 return;
6948
6949 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006950 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006951 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006952 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006953 return;
6954 }
6955 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006956 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006957 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006958 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006959 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006960 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006961 return;
6962 }
6963 if (Opc != BO_Shl)
6964 return;
6965
6966 // When left shifting an ICE which is signed, we can check for overflow which
6967 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6968 // integers have defined behavior modulo one more than the maximum value
6969 // representable in the result type, so never warn for those.
6970 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00006971 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006972 LHSTy->hasUnsignedIntegerRepresentation())
6973 return;
6974 llvm::APInt ResultBits =
6975 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6976 if (LeftBits.uge(ResultBits))
6977 return;
6978 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6979 Result = Result.shl(Right);
6980
6981 // If we are only missing a sign bit, this is less likely to result in actual
6982 // bugs -- if the result is cast back to an unsigned type, it will have the
6983 // expected value. Thus we place this behind a different warning that can be
6984 // turned off separately if needed.
6985 if (LeftBits == ResultBits - 1) {
6986 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6987 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006988 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006989 return;
6990 }
6991
6992 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6993 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006994 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006995}
6996
Chris Lattner2a3569b2008-04-07 05:30:13 +00006997// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00006998QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006999 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007000 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007001 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7002 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007003 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007004
Douglas Gregor0bf31402010-10-08 23:50:27 +00007005 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7006 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007007 if (isScopedEnumerationType(lex.get()->getType()) ||
7008 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007009 return InvalidOperands(Loc, lex, rex);
7010 }
7011
Nate Begemane46ee9a2009-10-25 02:26:48 +00007012 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007013 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007014 return CheckVectorOperands(Loc, lex, rex);
7015
Chris Lattner5c11c412007-12-12 05:47:28 +00007016 // Shifts don't perform usual arithmetic conversions, they just do integer
7017 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007018
John McCall57cdd882010-12-16 19:28:59 +00007019 // For the LHS, do usual unary conversions, but then reset them away
7020 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007021 ExprResult old_lex = lex;
7022 lex = UsualUnaryConversions(lex.take());
7023 if (lex.isInvalid())
7024 return QualType();
7025 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007026 if (isCompAssign) lex = old_lex;
7027
7028 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007029 rex = UsualUnaryConversions(rex.take());
7030 if (rex.isInvalid())
7031 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007032
Ryan Flynnf53fab82009-08-07 16:20:20 +00007033 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007034 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007035
Chris Lattner5c11c412007-12-12 05:47:28 +00007036 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007037 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007038}
7039
Chandler Carruth17773fc2010-07-10 12:30:03 +00007040static bool IsWithinTemplateSpecialization(Decl *D) {
7041 if (DeclContext *DC = D->getDeclContext()) {
7042 if (isa<ClassTemplateSpecializationDecl>(DC))
7043 return true;
7044 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7045 return FD->isFunctionTemplateSpecialization();
7046 }
7047 return false;
7048}
7049
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007050// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007051QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007052 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007053 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007054
Chris Lattner9a152e22009-12-05 05:40:13 +00007055 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007056 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007057 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007058
John Wiegley01296292011-04-08 18:41:53 +00007059 QualType lType = lex.get()->getType();
7060 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007061
John Wiegley01296292011-04-08 18:41:53 +00007062 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7063 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007064 QualType LHSStrippedType = LHSStripped->getType();
7065 QualType RHSStrippedType = RHSStripped->getType();
7066
Douglas Gregor1beec452011-03-12 01:48:56 +00007067
7068
Chandler Carruth712563b2011-02-17 08:37:06 +00007069 // Two different enums will raise a warning when compared.
7070 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7071 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7072 if (LHSEnumType->getDecl()->getIdentifier() &&
7073 RHSEnumType->getDecl()->getIdentifier() &&
7074 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7075 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7076 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007077 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007078 }
7079 }
7080 }
7081
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007082 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007083 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007084 !lex.get()->getLocStart().isMacroID() &&
7085 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007086 // For non-floating point types, check for self-comparisons of the form
7087 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7088 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007089 //
7090 // NOTE: Don't warn about comparison expressions resulting from macro
7091 // expansion. Also don't warn about comparisons which are only self
7092 // comparisons within a template specialization. The warnings should catch
7093 // obvious cases in the definition of the template anyways. The idea is to
7094 // warn when the typed comparison operator will always evaluate to the same
7095 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007096 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007097 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007098 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007099 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007100 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007101 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007102 << (Opc == BO_EQ
7103 || Opc == BO_LE
7104 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007105 } else if (lType->isArrayType() && rType->isArrayType() &&
7106 !DRL->getDecl()->getType()->isReferenceType() &&
7107 !DRR->getDecl()->getType()->isReferenceType()) {
7108 // what is it always going to eval to?
7109 char always_evals_to;
7110 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007111 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007112 always_evals_to = 0; // false
7113 break;
John McCalle3027922010-08-25 11:45:40 +00007114 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007115 always_evals_to = 1; // true
7116 break;
7117 default:
7118 // best we can say is 'a constant'
7119 always_evals_to = 2; // e.g. array1 <= array2
7120 break;
7121 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007122 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007123 << 1 // array
7124 << always_evals_to);
7125 }
7126 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007127 }
Mike Stump11289f42009-09-09 15:08:12 +00007128
Chris Lattner222b8bd2009-03-08 19:39:53 +00007129 if (isa<CastExpr>(LHSStripped))
7130 LHSStripped = LHSStripped->IgnoreParenCasts();
7131 if (isa<CastExpr>(RHSStripped))
7132 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007133
Chris Lattner222b8bd2009-03-08 19:39:53 +00007134 // Warn about comparisons against a string constant (unless the other
7135 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007136 Expr *literalString = 0;
7137 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007138 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007139 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007140 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007141 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007142 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007143 } else if ((isa<StringLiteral>(RHSStripped) ||
7144 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007145 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007146 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007147 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007148 literalStringStripped = RHSStripped;
7149 }
7150
7151 if (literalString) {
7152 std::string resultComparison;
7153 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007154 case BO_LT: resultComparison = ") < 0"; break;
7155 case BO_GT: resultComparison = ") > 0"; break;
7156 case BO_LE: resultComparison = ") <= 0"; break;
7157 case BO_GE: resultComparison = ") >= 0"; break;
7158 case BO_EQ: resultComparison = ") == 0"; break;
7159 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007160 default: assert(false && "Invalid comparison operator");
7161 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007162
Ted Kremenek3427fac2011-02-23 01:52:04 +00007163 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007164 PDiag(diag::warn_stringcompare)
7165 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007166 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007167 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007168 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007169
Douglas Gregorec170db2010-06-08 19:50:34 +00007170 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007171 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007172 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007173 if (lex.isInvalid() || rex.isInvalid())
7174 return QualType();
7175 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007176 else {
John Wiegley01296292011-04-08 18:41:53 +00007177 lex = UsualUnaryConversions(lex.take());
7178 if (lex.isInvalid())
7179 return QualType();
7180
7181 rex = UsualUnaryConversions(rex.take());
7182 if (rex.isInvalid())
7183 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007184 }
7185
John Wiegley01296292011-04-08 18:41:53 +00007186 lType = lex.get()->getType();
7187 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007188
Douglas Gregorca63811b2008-11-19 03:25:36 +00007189 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007190 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007191
Chris Lattnerb620c342007-08-26 01:18:55 +00007192 if (isRelational) {
7193 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007194 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007195 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007196 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007197 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007198 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007199
Chris Lattnerb620c342007-08-26 01:18:55 +00007200 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007201 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007202 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203
John Wiegley01296292011-04-08 18:41:53 +00007204 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007205 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007206 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007207 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007208
Douglas Gregorf267edd2010-06-15 21:38:40 +00007209 // All of the following pointer-related warnings are GCC extensions, except
7210 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007211 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007212 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007213 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007214 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007215 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007216
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007217 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007218 if (LCanPointeeTy == RCanPointeeTy)
7219 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007220 if (!isRelational &&
7221 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7222 // Valid unless comparison between non-null pointer and function pointer
7223 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007224 // In a SFINAE context, we treat this as a hard error to maintain
7225 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007226 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7227 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007228 Diag(Loc,
7229 isSFINAEContext()?
7230 diag::err_typecheck_comparison_of_fptr_to_void
7231 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007232 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007233
7234 if (isSFINAEContext())
7235 return QualType();
7236
John Wiegley01296292011-04-08 18:41:53 +00007237 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007238 return ResultTy;
7239 }
7240 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007241
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007242 // C++ [expr.rel]p2:
7243 // [...] Pointer conversions (4.10) and qualification
7244 // conversions (4.4) are performed on pointer operands (or on
7245 // a pointer operand and a null pointer constant) to bring
7246 // them to their composite pointer type. [...]
7247 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007248 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007249 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007250 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007251 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007252 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007253 if (T.isNull()) {
7254 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007255 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007256 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007257 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007258 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007259 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007260 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007261 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007262 }
7263
John Wiegley01296292011-04-08 18:41:53 +00007264 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7265 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007266 return ResultTy;
7267 }
Eli Friedman16c209612009-08-23 00:27:47 +00007268 // C99 6.5.9p2 and C99 6.5.8p2
7269 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7270 RCanPointeeTy.getUnqualifiedType())) {
7271 // Valid unless a relational comparison of function pointers
7272 if (isRelational && LCanPointeeTy->isFunctionType()) {
7273 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007274 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007275 }
7276 } else if (!isRelational &&
7277 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7278 // Valid unless comparison between non-null pointer and function pointer
7279 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7280 && !LHSIsNull && !RHSIsNull) {
7281 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007282 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007283 }
7284 } else {
7285 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007286 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007287 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007288 }
John McCall7684dde2011-03-11 04:25:25 +00007289 if (LCanPointeeTy != RCanPointeeTy) {
7290 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007291 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007292 else
John Wiegley01296292011-04-08 18:41:53 +00007293 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007294 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007295 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297
Sebastian Redl576fd422009-05-10 18:38:11 +00007298 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007299 // Comparison of nullptr_t with itself.
7300 if (lType->isNullPtrType() && rType->isNullPtrType())
7301 return ResultTy;
7302
Mike Stump11289f42009-09-09 15:08:12 +00007303 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007304 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007305 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007306 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007307 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007308 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007309 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007310 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007311 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007312 return ResultTy;
7313 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007314 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007315 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007316 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007317 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007318 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007319 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007320 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007321 return ResultTy;
7322 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007323
7324 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007325 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007326 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7327 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007328 // In addition, pointers to members can be compared, or a pointer to
7329 // member and a null pointer constant. Pointer to member conversions
7330 // (4.11) and qualification conversions (4.4) are performed to bring
7331 // them to a common type. If one operand is a null pointer constant,
7332 // the common type is the type of the other operand. Otherwise, the
7333 // common type is a pointer to member type similar (4.4) to the type
7334 // of one of the operands, with a cv-qualification signature (4.4)
7335 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007336 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007337 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007338 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007339 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007340 if (T.isNull()) {
7341 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007342 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007343 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007344 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007345 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007346 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007347 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007348 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007349 }
Mike Stump11289f42009-09-09 15:08:12 +00007350
John Wiegley01296292011-04-08 18:41:53 +00007351 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7352 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007353 return ResultTy;
7354 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007355
7356 // Handle scoped enumeration types specifically, since they don't promote
7357 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007358 if (lex.get()->getType()->isEnumeralType() &&
7359 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007360 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007361 }
Mike Stump11289f42009-09-09 15:08:12 +00007362
Steve Naroff081c7422008-09-04 15:10:53 +00007363 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007364 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007365 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7366 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007367
Steve Naroff081c7422008-09-04 15:10:53 +00007368 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007369 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007370 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007371 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007372 }
John Wiegley01296292011-04-08 18:41:53 +00007373 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007374 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007375 }
John Wiegley01296292011-04-08 18:41:53 +00007376
Steve Naroffe18f94c2008-09-28 01:11:11 +00007377 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007378 if (!isRelational
7379 && ((lType->isBlockPointerType() && rType->isPointerType())
7380 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007381 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007382 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007383 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007384 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007385 ->getPointeeType()->isVoidType())))
7386 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007387 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007388 }
John McCall7684dde2011-03-11 04:25:25 +00007389 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007390 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007391 else
John Wiegley01296292011-04-08 18:41:53 +00007392 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007393 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007394 }
Steve Naroff081c7422008-09-04 15:10:53 +00007395
John McCall7684dde2011-03-11 04:25:25 +00007396 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7397 const PointerType *LPT = lType->getAs<PointerType>();
7398 const PointerType *RPT = rType->getAs<PointerType>();
7399 if (LPT || RPT) {
7400 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7401 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007402
Steve Naroff753567f2008-11-17 19:49:16 +00007403 if (!LPtrToVoid && !RPtrToVoid &&
7404 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007405 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007406 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007407 }
John McCall7684dde2011-03-11 04:25:25 +00007408 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007409 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007410 else
John Wiegley01296292011-04-08 18:41:53 +00007411 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007412 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007413 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007414 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007415 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007416 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007417 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007418 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007419 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007420 else
John Wiegley01296292011-04-08 18:41:53 +00007421 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007422 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007423 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007424 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007425 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7426 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007427 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007428 bool isError = false;
7429 if ((LHSIsNull && lType->isIntegerType()) ||
7430 (RHSIsNull && rType->isIntegerType())) {
7431 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007432 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007433 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007434 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007435 else if (getLangOptions().CPlusPlus) {
7436 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7437 isError = true;
7438 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007439 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007440
Chris Lattnerd99bd522009-08-23 00:03:44 +00007441 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007442 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007443 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007444 if (isError)
7445 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007446 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007447
7448 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007449 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007450 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007451 else
John Wiegley01296292011-04-08 18:41:53 +00007452 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007453 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007454 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007455 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007456
Steve Naroff4b191572008-09-04 16:56:14 +00007457 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007458 if (!isRelational && RHSIsNull
7459 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007460 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007461 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007462 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007463 if (!isRelational && LHSIsNull
7464 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007465 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007466 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007467 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007468
Chris Lattner326f7572008-11-18 01:30:42 +00007469 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007470}
7471
Nate Begeman191a6b12008-07-14 18:02:46 +00007472/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007473/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007474/// like a scalar comparison, a vector comparison produces a vector of integer
7475/// types.
John Wiegley01296292011-04-08 18:41:53 +00007476QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007477 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007478 bool isRelational) {
7479 // Check to make sure we're operating on vectors of the same type and width,
7480 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007481 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007482 if (vType.isNull())
7483 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007484
John Wiegley01296292011-04-08 18:41:53 +00007485 QualType lType = lex.get()->getType();
7486 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007487
Anton Yartsev530deb92011-03-27 15:36:07 +00007488 // If AltiVec, the comparison results in a numeric type, i.e.
7489 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007490 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007491 return Context.getLogicalOperationType();
7492
Nate Begeman191a6b12008-07-14 18:02:46 +00007493 // For non-floating point types, check for self-comparisons of the form
7494 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7495 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007496 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007497 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7498 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007499 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007500 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007501 PDiag(diag::warn_comparison_always)
7502 << 0 // self-
7503 << 2 // "a constant"
7504 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007505 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007506
Nate Begeman191a6b12008-07-14 18:02:46 +00007507 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007508 if (!isRelational && lType->hasFloatingRepresentation()) {
7509 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007510 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007511 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007512
Nate Begeman191a6b12008-07-14 18:02:46 +00007513 // Return the type for the comparison, which is the same as vector type for
7514 // integer vectors, or an integer type of identical size and number of
7515 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007516 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007517 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007518
John McCall9dd450b2009-09-21 23:43:11 +00007519 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007520 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007521 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007522 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007523 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007524 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7525
Mike Stump4e1f26a2009-02-19 03:04:26 +00007526 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007527 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007528 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7529}
7530
Steve Naroff218bc2b2007-05-04 21:54:46 +00007531inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007532 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7533 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7534 if (lex.get()->getType()->hasIntegerRepresentation() &&
7535 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007536 return CheckVectorOperands(Loc, lex, rex);
7537
7538 return InvalidOperands(Loc, lex, rex);
7539 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007540
John Wiegley01296292011-04-08 18:41:53 +00007541 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7542 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7543 if (lexResult.isInvalid() || rexResult.isInvalid())
7544 return QualType();
7545 lex = lexResult.take();
7546 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007547
John Wiegley01296292011-04-08 18:41:53 +00007548 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7549 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007550 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007551 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007552}
7553
Steve Naroff218bc2b2007-05-04 21:54:46 +00007554inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007555 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007556
7557 // Diagnose cases where the user write a logical and/or but probably meant a
7558 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7559 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007560 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7561 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007562 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007563 !Loc.isMacroID()) {
7564 // If the RHS can be constant folded, and if it constant folds to something
7565 // that isn't 0 or 1 (which indicate a potential logical operation that
7566 // happened to fold to true/false) then warn.
7567 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007568 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007569 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7570 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007571 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007572 << (Opc == BO_LAnd ? "&&" : "||")
7573 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007574 }
7575 }
Chris Lattner8406c512010-07-13 19:41:32 +00007576
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007577 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007578 lex = UsualUnaryConversions(lex.take());
7579 if (lex.isInvalid())
7580 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007581
John Wiegley01296292011-04-08 18:41:53 +00007582 rex = UsualUnaryConversions(rex.take());
7583 if (rex.isInvalid())
7584 return QualType();
7585
7586 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007587 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007588
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007589 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007590 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007591
John McCall4a2429a2010-06-04 00:29:51 +00007592 // The following is safe because we only use this method for
7593 // non-overloadable operands.
7594
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007595 // C++ [expr.log.and]p1
7596 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007597 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007598 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7599 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007600 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007601 lex = move(lexRes);
7602
7603 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7604 if (rexRes.isInvalid())
7605 return InvalidOperands(Loc, lex, rex);
7606 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007607
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007608 // C++ [expr.log.and]p2
7609 // C++ [expr.log.or]p2
7610 // The result is a bool.
7611 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007612}
7613
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007614/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7615/// is a read-only property; return true if so. A readonly property expression
7616/// depends on various declarations and thus must be treated specially.
7617///
Mike Stump11289f42009-09-09 15:08:12 +00007618static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007619 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7620 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007621 if (PropExpr->isImplicitProperty()) return false;
7622
7623 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7624 QualType BaseType = PropExpr->isSuperReceiver() ?
7625 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007626 PropExpr->getBase()->getType();
7627
John McCallb7bd14f2010-12-02 01:19:52 +00007628 if (const ObjCObjectPointerType *OPT =
7629 BaseType->getAsObjCInterfacePointerType())
7630 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7631 if (S.isPropertyReadonly(PDecl, IFace))
7632 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007633 }
7634 return false;
7635}
7636
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007637static bool IsConstProperty(Expr *E, Sema &S) {
7638 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7639 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7640 if (PropExpr->isImplicitProperty()) return false;
7641
7642 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7643 QualType T = PDecl->getType();
7644 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007645 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007646 CanQualType CT = S.Context.getCanonicalType(T);
7647 return CT.isConstQualified();
7648 }
7649 return false;
7650}
7651
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007652static bool IsReadonlyMessage(Expr *E, Sema &S) {
7653 if (E->getStmtClass() != Expr::MemberExprClass)
7654 return false;
7655 const MemberExpr *ME = cast<MemberExpr>(E);
7656 NamedDecl *Member = ME->getMemberDecl();
7657 if (isa<FieldDecl>(Member)) {
7658 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7659 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7660 return false;
7661 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7662 }
7663 return false;
7664}
7665
Chris Lattner30bd3272008-11-18 01:22:49 +00007666/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7667/// emit an error and return true. If so, return false.
7668static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007669 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007670 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007671 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007672 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7673 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007674 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7675 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007676 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7677 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007678 if (IsLV == Expr::MLV_Valid)
7679 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007680
Chris Lattner30bd3272008-11-18 01:22:49 +00007681 unsigned Diag = 0;
7682 bool NeedType = false;
7683 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007684 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007685 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007686 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7687 NeedType = true;
7688 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007689 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007690 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7691 NeedType = true;
7692 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007693 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007694 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7695 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007696 case Expr::MLV_Valid:
7697 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007698 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007699 case Expr::MLV_MemberFunction:
7700 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007701 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7702 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007703 case Expr::MLV_IncompleteType:
7704 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007705 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007706 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007707 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007708 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007709 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7710 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007711 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007712 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7713 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007714 case Expr::MLV_ReadonlyProperty:
7715 Diag = diag::error_readonly_property_assignment;
7716 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007717 case Expr::MLV_NoSetterProperty:
7718 Diag = diag::error_nosetter_property_assignment;
7719 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007720 case Expr::MLV_InvalidMessageExpression:
7721 Diag = diag::error_readonly_message_assignment;
7722 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007723 case Expr::MLV_SubObjCPropertySetting:
7724 Diag = diag::error_no_subobject_property_setting;
7725 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007726 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007727
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007728 SourceRange Assign;
7729 if (Loc != OrigLoc)
7730 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007731 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007732 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007733 else
Mike Stump11289f42009-09-09 15:08:12 +00007734 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007735 return true;
7736}
7737
7738
7739
7740// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007741QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007742 SourceLocation Loc,
7743 QualType CompoundType) {
7744 // Verify that LHS is a modifiable lvalue, and emit error if not.
7745 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007746 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007747
7748 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007749 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007750 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007751 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007752 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007753 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007754 if (LHS->getObjectKind() == OK_ObjCProperty) {
7755 ExprResult LHSResult = Owned(LHS);
7756 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7757 if (LHSResult.isInvalid())
7758 return QualType();
7759 LHS = LHSResult.take();
7760 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007761 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007762 if (RHS.isInvalid())
7763 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007764 // Special case of NSObject attributes on c-style pointer types.
7765 if (ConvTy == IncompatiblePointer &&
7766 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007767 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007768 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007769 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007770 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007771
John McCall7decc9e2010-11-18 06:31:45 +00007772 if (ConvTy == Compatible &&
7773 getLangOptions().ObjCNonFragileABI &&
7774 LHSType->isObjCObjectType())
7775 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7776 << LHSType;
7777
Chris Lattnerea714382008-08-21 18:04:13 +00007778 // If the RHS is a unary plus or minus, check to see if they = and + are
7779 // right next to each other. If so, the user may have typo'd "x =+ 4"
7780 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007781 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007782 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7783 RHSCheck = ICE->getSubExpr();
7784 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007785 if ((UO->getOpcode() == UO_Plus ||
7786 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007787 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007788 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007789 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7790 // And there is a space or other character before the subexpr of the
7791 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007792 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7793 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007794 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007795 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007796 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007797 }
Chris Lattnerea714382008-08-21 18:04:13 +00007798 }
7799 } else {
7800 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007801 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007802 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007803
Chris Lattner326f7572008-11-18 01:30:42 +00007804 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007805 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007806 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007807
Chris Lattner39561062010-07-07 06:14:23 +00007808
7809 // Check to see if the destination operand is a dereferenced null pointer. If
7810 // so, and if not volatile-qualified, this is undefined behavior that the
7811 // optimizer will delete, so warn about it. People sometimes try to use this
7812 // to get a deterministic trap and are surprised by clang's behavior. This
7813 // only handles the pattern "*null = whatever", which is a very syntactic
7814 // check.
7815 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007816 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007817 UO->getSubExpr()->IgnoreParenCasts()->
7818 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7819 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007820 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7821 PDiag(diag::warn_indirection_through_null)
7822 << UO->getSubExpr()->getSourceRange());
7823 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7824 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007825 }
7826
Ted Kremenek64699be2011-02-16 01:57:07 +00007827 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007828 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007829
Steve Naroff98cf3e92007-06-06 18:38:38 +00007830 // C99 6.5.16p3: The type of an assignment expression is the type of the
7831 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007832 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007833 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7834 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007835 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007836 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007837 return (getLangOptions().CPlusPlus
7838 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007839}
7840
Chris Lattner326f7572008-11-18 01:30:42 +00007841// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007842static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007843 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007844 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007845
John McCall3aef3d82011-04-10 19:13:55 +00007846 LHS = S.CheckPlaceholderExpr(LHS.take());
7847 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007848 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007849 return QualType();
7850
John McCall73d36182010-10-12 07:14:40 +00007851 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7852 // operands, but not unary promotions.
7853 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007854
John McCall34376a62010-12-04 03:47:34 +00007855 // So we treat the LHS as a ignored value, and in C++ we allow the
7856 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007857 LHS = S.IgnoredValueConversions(LHS.take());
7858 if (LHS.isInvalid())
7859 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007860
7861 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007862 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7863 if (RHS.isInvalid())
7864 return QualType();
7865 if (!RHS.get()->getType()->isVoidType())
7866 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007867 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007868
John Wiegley01296292011-04-08 18:41:53 +00007869 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007870}
7871
Steve Naroff7a5af782007-07-13 16:58:59 +00007872/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7873/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007874static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7875 ExprValueKind &VK,
7876 SourceLocation OpLoc,
7877 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007878 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007879 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007880
Chris Lattner6b0cf142008-11-21 07:05:48 +00007881 QualType ResType = Op->getType();
7882 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007883
John McCall4bc41ae2010-11-18 19:01:18 +00007884 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007885 // Decrement of bool is not allowed.
7886 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007887 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007888 return QualType();
7889 }
7890 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007891 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007892 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007893 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007894 } else if (ResType->isAnyPointerType()) {
7895 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007896
Chris Lattner6b0cf142008-11-21 07:05:48 +00007897 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007898 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007899 if (S.getLangOptions().CPlusPlus) {
7900 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007901 << Op->getSourceRange();
7902 return QualType();
7903 }
7904
7905 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007906 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007907 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007908 if (S.getLangOptions().CPlusPlus) {
7909 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007910 << Op->getType() << Op->getSourceRange();
7911 return QualType();
7912 }
7913
John McCall4bc41ae2010-11-18 19:01:18 +00007914 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007915 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007916 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7917 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007918 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007919 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007920 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007921 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007922 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7923 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007924 << PointeeTy << Op->getSourceRange();
7925 return QualType();
7926 }
Eli Friedman090addd2010-01-03 00:20:48 +00007927 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007928 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007929 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007930 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007931 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007932 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007933 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007934 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7935 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007936 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7937 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007938 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007939 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007940 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007941 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007942 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007943 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007944 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007945 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007946 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007947 // In C++, a prefix increment is the same type as the operand. Otherwise
7948 // (in C or with postfix), the increment is the unqualified type of the
7949 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007950 if (isPrefix && S.getLangOptions().CPlusPlus) {
7951 VK = VK_LValue;
7952 return ResType;
7953 } else {
7954 VK = VK_RValue;
7955 return ResType.getUnqualifiedType();
7956 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007957}
7958
John Wiegley01296292011-04-08 18:41:53 +00007959ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007960 assert(E->getValueKind() == VK_LValue &&
7961 E->getObjectKind() == OK_ObjCProperty);
7962 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7963
7964 ExprValueKind VK = VK_RValue;
7965 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007966 if (const ObjCMethodDecl *GetterMethod =
7967 PRE->getImplicitPropertyGetter()) {
7968 QualType Result = GetterMethod->getResultType();
7969 VK = Expr::getValueKindForType(Result);
7970 }
7971 else {
7972 Diag(PRE->getLocation(), diag::err_getter_not_found)
7973 << PRE->getBase()->getType();
7974 }
John McCall34376a62010-12-04 03:47:34 +00007975 }
7976
7977 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7978 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007979
7980 ExprResult Result = MaybeBindToTemporary(E);
7981 if (!Result.isInvalid())
7982 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007983
7984 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007985}
7986
John Wiegley01296292011-04-08 18:41:53 +00007987void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
7988 assert(LHS.get()->getValueKind() == VK_LValue &&
7989 LHS.get()->getObjectKind() == OK_ObjCProperty);
7990 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007991
John Wiegley01296292011-04-08 18:41:53 +00007992 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007993 // If using property-dot syntax notation for assignment, and there is a
7994 // setter, RHS expression is being passed to the setter argument. So,
7995 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007996 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007997 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7998 LHSTy = (*P)->getType();
7999
8000 // Otherwise, if the getter returns an l-value, just call that.
8001 } else {
John Wiegley01296292011-04-08 18:41:53 +00008002 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008003 ExprValueKind VK = Expr::getValueKindForType(Result);
8004 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008005 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8006 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008007 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008008 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008009 }
John McCall34376a62010-12-04 03:47:34 +00008010 }
8011
8012 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008013 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008014 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008015 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008016 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008017 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008018 }
8019}
8020
8021
Anders Carlsson806700f2008-02-01 07:15:58 +00008022/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008023/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008024/// where the declaration is needed for type checking. We only need to
8025/// handle cases when the expression references a function designator
8026/// or is an lvalue. Here are some examples:
8027/// - &(x) => x
8028/// - &*****f => f for f a function designator.
8029/// - &s.xx => s
8030/// - &s.zz[1].yy -> s, if zz is an array
8031/// - *(x + 1) -> x, if x is an array
8032/// - &"123"[2] -> 0
8033/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008034static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008035 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008036 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008037 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008038 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008039 // If this is an arrow operator, the address is an offset from
8040 // the base's value, so the object the base refers to is
8041 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008042 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008043 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008044 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008045 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008046 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008047 // FIXME: This code shouldn't be necessary! We should catch the implicit
8048 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008049 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8050 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8051 if (ICE->getSubExpr()->getType()->isArrayType())
8052 return getPrimaryDecl(ICE->getSubExpr());
8053 }
8054 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008055 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008056 case Stmt::UnaryOperatorClass: {
8057 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008058
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008059 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008060 case UO_Real:
8061 case UO_Imag:
8062 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008063 return getPrimaryDecl(UO->getSubExpr());
8064 default:
8065 return 0;
8066 }
8067 }
Steve Naroff47500512007-04-19 23:00:49 +00008068 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008069 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008070 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008071 // If the result of an implicit cast is an l-value, we care about
8072 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008073 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008074 default:
8075 return 0;
8076 }
8077}
8078
8079/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008080/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008081/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008082/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008083/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008084/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008085/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008086static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8087 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008088 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008089 return S.Context.DependentTy;
8090 if (OrigOp->getType() == S.Context.OverloadTy)
8091 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00008092
John McCall3aef3d82011-04-10 19:13:55 +00008093 ExprResult PR = S.CheckPlaceholderExpr(OrigOp);
John McCall36226622010-10-12 02:09:17 +00008094 if (PR.isInvalid()) return QualType();
8095 OrigOp = PR.take();
8096
John McCall8d08b9b2010-08-27 09:08:28 +00008097 // Make sure to ignore parentheses in subsequent checks
8098 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008099
John McCall4bc41ae2010-11-18 19:01:18 +00008100 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008101 // Implement C99-only parts of addressof rules.
8102 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008103 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008104 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8105 // (assuming the deref expression is valid).
8106 return uOp->getSubExpr()->getType();
8107 }
8108 // Technically, there should be a check for array subscript
8109 // expressions here, but the result of one is always an lvalue anyway.
8110 }
John McCallf3a88602011-02-03 08:15:49 +00008111 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008112 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008113
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008114 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008115 bool sfinae = S.isSFINAEContext();
8116 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8117 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008118 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008119 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008120 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008121 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008122 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008123 } else if (lval == Expr::LV_MemberFunction) {
8124 // If it's an instance method, make a member pointer.
8125 // The expression must have exactly the form &A::foo.
8126
8127 // If the underlying expression isn't a decl ref, give up.
8128 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008129 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008130 << OrigOp->getSourceRange();
8131 return QualType();
8132 }
8133 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8134 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8135
8136 // The id-expression was parenthesized.
8137 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008138 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008139 << OrigOp->getSourceRange();
8140
8141 // The method was named without a qualifier.
8142 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008143 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008144 << op->getSourceRange();
8145 }
8146
John McCall4bc41ae2010-11-18 19:01:18 +00008147 return S.Context.getMemberPointerType(op->getType(),
8148 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008149 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008150 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008151 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008152 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008153 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008154 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008155 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008156 return QualType();
8157 }
John McCall086a4642010-11-24 05:12:34 +00008158 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008159 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008160 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008161 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008162 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008163 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008164 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008165 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008166 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008167 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008168 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008169 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008170 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008171 << "property expression" << op->getSourceRange();
8172 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008173 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008174 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008175 // with the register storage-class specifier.
8176 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008177 // in C++ it is not error to take address of a register
8178 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008179 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008180 !S.getLangOptions().CPlusPlus) {
8181 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008182 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008183 return QualType();
8184 }
John McCalld14a8642009-11-21 08:51:07 +00008185 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008186 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008187 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008188 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008189 // Could be a pointer to member, though, if there is an explicit
8190 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008191 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008192 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008193 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008194 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008195 S.Diag(OpLoc,
8196 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008197 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008198 return QualType();
8199 }
Mike Stump11289f42009-09-09 15:08:12 +00008200
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008201 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8202 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008203 return S.Context.getMemberPointerType(op->getType(),
8204 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008205 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008206 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008207 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008208 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008209 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008210
Eli Friedmance7f9002009-05-16 23:27:50 +00008211 if (lval == Expr::LV_IncompleteVoidType) {
8212 // Taking the address of a void variable is technically illegal, but we
8213 // allow it in cases which are otherwise valid.
8214 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008215 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008216 }
8217
Steve Naroff47500512007-04-19 23:00:49 +00008218 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008219 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008220 return S.Context.getObjCObjectPointerType(op->getType());
8221 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008222}
8223
Chris Lattner9156f1b2010-07-05 19:17:26 +00008224/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008225static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8226 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008227 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008228 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008229
John Wiegley01296292011-04-08 18:41:53 +00008230 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8231 if (ConvResult.isInvalid())
8232 return QualType();
8233 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008234 QualType OpTy = Op->getType();
8235 QualType Result;
8236
8237 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8238 // is an incomplete type or void. It would be possible to warn about
8239 // dereferencing a void pointer, but it's completely well-defined, and such a
8240 // warning is unlikely to catch any mistakes.
8241 if (const PointerType *PT = OpTy->getAs<PointerType>())
8242 Result = PT->getPointeeType();
8243 else if (const ObjCObjectPointerType *OPT =
8244 OpTy->getAs<ObjCObjectPointerType>())
8245 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008246 else {
John McCall3aef3d82011-04-10 19:13:55 +00008247 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008248 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008249 if (PR.take() != Op)
8250 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008251 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008252
Chris Lattner9156f1b2010-07-05 19:17:26 +00008253 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008254 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008255 << OpTy << Op->getSourceRange();
8256 return QualType();
8257 }
John McCall4bc41ae2010-11-18 19:01:18 +00008258
8259 // Dereferences are usually l-values...
8260 VK = VK_LValue;
8261
8262 // ...except that certain expressions are never l-values in C.
8263 if (!S.getLangOptions().CPlusPlus &&
8264 IsCForbiddenLValueType(S.Context, Result))
8265 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008266
8267 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008268}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008269
John McCalle3027922010-08-25 11:45:40 +00008270static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008271 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008272 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008273 switch (Kind) {
8274 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008275 case tok::periodstar: Opc = BO_PtrMemD; break;
8276 case tok::arrowstar: Opc = BO_PtrMemI; break;
8277 case tok::star: Opc = BO_Mul; break;
8278 case tok::slash: Opc = BO_Div; break;
8279 case tok::percent: Opc = BO_Rem; break;
8280 case tok::plus: Opc = BO_Add; break;
8281 case tok::minus: Opc = BO_Sub; break;
8282 case tok::lessless: Opc = BO_Shl; break;
8283 case tok::greatergreater: Opc = BO_Shr; break;
8284 case tok::lessequal: Opc = BO_LE; break;
8285 case tok::less: Opc = BO_LT; break;
8286 case tok::greaterequal: Opc = BO_GE; break;
8287 case tok::greater: Opc = BO_GT; break;
8288 case tok::exclaimequal: Opc = BO_NE; break;
8289 case tok::equalequal: Opc = BO_EQ; break;
8290 case tok::amp: Opc = BO_And; break;
8291 case tok::caret: Opc = BO_Xor; break;
8292 case tok::pipe: Opc = BO_Or; break;
8293 case tok::ampamp: Opc = BO_LAnd; break;
8294 case tok::pipepipe: Opc = BO_LOr; break;
8295 case tok::equal: Opc = BO_Assign; break;
8296 case tok::starequal: Opc = BO_MulAssign; break;
8297 case tok::slashequal: Opc = BO_DivAssign; break;
8298 case tok::percentequal: Opc = BO_RemAssign; break;
8299 case tok::plusequal: Opc = BO_AddAssign; break;
8300 case tok::minusequal: Opc = BO_SubAssign; break;
8301 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8302 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8303 case tok::ampequal: Opc = BO_AndAssign; break;
8304 case tok::caretequal: Opc = BO_XorAssign; break;
8305 case tok::pipeequal: Opc = BO_OrAssign; break;
8306 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008307 }
8308 return Opc;
8309}
8310
John McCalle3027922010-08-25 11:45:40 +00008311static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008312 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008313 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008314 switch (Kind) {
8315 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008316 case tok::plusplus: Opc = UO_PreInc; break;
8317 case tok::minusminus: Opc = UO_PreDec; break;
8318 case tok::amp: Opc = UO_AddrOf; break;
8319 case tok::star: Opc = UO_Deref; break;
8320 case tok::plus: Opc = UO_Plus; break;
8321 case tok::minus: Opc = UO_Minus; break;
8322 case tok::tilde: Opc = UO_Not; break;
8323 case tok::exclaim: Opc = UO_LNot; break;
8324 case tok::kw___real: Opc = UO_Real; break;
8325 case tok::kw___imag: Opc = UO_Imag; break;
8326 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008327 }
8328 return Opc;
8329}
8330
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008331/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8332/// This warning is only emitted for builtin assignment operations. It is also
8333/// suppressed in the event of macro expansions.
8334static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8335 SourceLocation OpLoc) {
8336 if (!S.ActiveTemplateInstantiations.empty())
8337 return;
8338 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8339 return;
8340 lhs = lhs->IgnoreParenImpCasts();
8341 rhs = rhs->IgnoreParenImpCasts();
8342 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8343 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8344 if (!LeftDeclRef || !RightDeclRef ||
8345 LeftDeclRef->getLocation().isMacroID() ||
8346 RightDeclRef->getLocation().isMacroID())
8347 return;
8348 const ValueDecl *LeftDecl =
8349 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8350 const ValueDecl *RightDecl =
8351 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8352 if (LeftDecl != RightDecl)
8353 return;
8354 if (LeftDecl->getType().isVolatileQualified())
8355 return;
8356 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8357 if (RefTy->getPointeeType().isVolatileQualified())
8358 return;
8359
8360 S.Diag(OpLoc, diag::warn_self_assignment)
8361 << LeftDeclRef->getType()
8362 << lhs->getSourceRange() << rhs->getSourceRange();
8363}
8364
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008365/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8366/// operator @p Opc at location @c TokLoc. This routine only supports
8367/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008368ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008369 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008370 Expr *lhsExpr, Expr *rhsExpr) {
8371 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008372 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008373 // The following two variables are used for compound assignment operators
8374 QualType CompLHSTy; // Type of LHS after promotions for computation
8375 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008376 ExprValueKind VK = VK_RValue;
8377 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008378
Douglas Gregor1beec452011-03-12 01:48:56 +00008379 // Check if a 'foo<int>' involved in a binary op, identifies a single
8380 // function unambiguously (i.e. an lvalue ala 13.4)
8381 // But since an assignment can trigger target based overload, exclude it in
8382 // our blind search. i.e:
8383 // template<class T> void f(); template<class T, class U> void f(U);
8384 // f<int> == 0; // resolve f<int> blindly
8385 // void (*p)(int); p = f<int>; // resolve f<int> using target
8386 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008387 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008388 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008389 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008390
John McCall3aef3d82011-04-10 19:13:55 +00008391 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008392 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008393 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008394 }
8395
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008396 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008397 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008398 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008399 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008400 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8401 VK = lhs.get()->getValueKind();
8402 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008403 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008404 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008405 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008406 break;
John McCalle3027922010-08-25 11:45:40 +00008407 case BO_PtrMemD:
8408 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008409 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008410 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008411 break;
John McCalle3027922010-08-25 11:45:40 +00008412 case BO_Mul:
8413 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008414 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008415 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008416 break;
John McCalle3027922010-08-25 11:45:40 +00008417 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008418 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8419 break;
John McCalle3027922010-08-25 11:45:40 +00008420 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008421 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8422 break;
John McCalle3027922010-08-25 11:45:40 +00008423 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008424 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8425 break;
John McCalle3027922010-08-25 11:45:40 +00008426 case BO_Shl:
8427 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008428 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008429 break;
John McCalle3027922010-08-25 11:45:40 +00008430 case BO_LE:
8431 case BO_LT:
8432 case BO_GE:
8433 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008434 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008435 break;
John McCalle3027922010-08-25 11:45:40 +00008436 case BO_EQ:
8437 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008438 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008439 break;
John McCalle3027922010-08-25 11:45:40 +00008440 case BO_And:
8441 case BO_Xor:
8442 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008443 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8444 break;
John McCalle3027922010-08-25 11:45:40 +00008445 case BO_LAnd:
8446 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008447 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008448 break;
John McCalle3027922010-08-25 11:45:40 +00008449 case BO_MulAssign:
8450 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008451 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008452 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008453 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008454 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8455 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008456 break;
John McCalle3027922010-08-25 11:45:40 +00008457 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008458 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8459 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008460 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8461 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008462 break;
John McCalle3027922010-08-25 11:45:40 +00008463 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008464 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008465 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8466 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008467 break;
John McCalle3027922010-08-25 11:45:40 +00008468 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008469 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008470 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8471 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008472 break;
John McCalle3027922010-08-25 11:45:40 +00008473 case BO_ShlAssign:
8474 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008475 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008476 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008477 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8478 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008479 break;
John McCalle3027922010-08-25 11:45:40 +00008480 case BO_AndAssign:
8481 case BO_XorAssign:
8482 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008483 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8484 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008485 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8486 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008487 break;
John McCalle3027922010-08-25 11:45:40 +00008488 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008489 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008490 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8491 VK = rhs.get()->getValueKind();
8492 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008493 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008494 break;
8495 }
John Wiegley01296292011-04-08 18:41:53 +00008496 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008497 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008498 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008499 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8500 ResultTy, VK, OK, OpLoc));
8501 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008502 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008503 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008504 }
John Wiegley01296292011-04-08 18:41:53 +00008505 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8506 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008507 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008508}
8509
Sebastian Redl44615072009-10-27 12:10:02 +00008510/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8511/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008512static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8513 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008514 const PartialDiagnostic &FirstNote,
8515 SourceRange FirstParenRange,
8516 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008517 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008518 Self.Diag(Loc, PD);
8519
8520 if (!FirstNote.getDiagID())
8521 return;
8522
8523 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8524 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8525 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008526 return;
8527 }
8528
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008529 Self.Diag(Loc, FirstNote)
8530 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008531 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008532
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008533 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008534 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008535
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008536 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8537 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8538 // We can't display the parentheses, so just dig the
8539 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008540 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008541 return;
8542 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008543
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008544 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008545 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8546 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008547}
8548
Sebastian Redl44615072009-10-27 12:10:02 +00008549/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8550/// operators are mixed in a way that suggests that the programmer forgot that
8551/// comparison operators have higher precedence. The most typical example of
8552/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008553static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008554 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008555 typedef BinaryOperator BinOp;
8556 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8557 rhsopc = static_cast<BinOp::Opcode>(-1);
8558 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008559 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008560 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008561 rhsopc = BO->getOpcode();
8562
8563 // Subs are not binary operators.
8564 if (lhsopc == -1 && rhsopc == -1)
8565 return;
8566
8567 // Bitwise operations are sometimes used as eager logical ops.
8568 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008569 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8570 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008571 return;
8572
Sebastian Redl44615072009-10-27 12:10:02 +00008573 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008574 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008575 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008576 << SourceRange(lhs->getLocStart(), OpLoc)
8577 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008578 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008579 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008580 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8581 Self.PDiag(diag::note_precedence_bitwise_silence)
8582 << BinOp::getOpcodeStr(lhsopc),
8583 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008584 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008585 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008586 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008587 << SourceRange(OpLoc, rhs->getLocEnd())
8588 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008589 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008590 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008591 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8592 Self.PDiag(diag::note_precedence_bitwise_silence)
8593 << BinOp::getOpcodeStr(rhsopc),
8594 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008595}
8596
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008597/// \brief It accepts a '&&' expr that is inside a '||' one.
8598/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8599/// in parentheses.
8600static void
8601EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8602 Expr *E) {
8603 assert(isa<BinaryOperator>(E) &&
8604 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8605 SuggestParentheses(Self, OpLoc,
8606 Self.PDiag(diag::warn_logical_and_in_logical_or)
8607 << E->getSourceRange(),
8608 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8609 E->getSourceRange(),
8610 Self.PDiag(0), SourceRange());
8611}
8612
8613/// \brief Returns true if the given expression can be evaluated as a constant
8614/// 'true'.
8615static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8616 bool Res;
8617 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8618}
8619
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008620/// \brief Returns true if the given expression can be evaluated as a constant
8621/// 'false'.
8622static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8623 bool Res;
8624 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8625}
8626
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008627/// \brief Look for '&&' in the left hand of a '||' expr.
8628static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008629 Expr *OrLHS, Expr *OrRHS) {
8630 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008631 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008632 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8633 if (EvaluatesAsFalse(S, OrRHS))
8634 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008635 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8636 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8637 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8638 } else if (Bop->getOpcode() == BO_LOr) {
8639 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8640 // If it's "a || b && 1 || c" we didn't warn earlier for
8641 // "a || b && 1", but warn now.
8642 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8643 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8644 }
8645 }
8646 }
8647}
8648
8649/// \brief Look for '&&' in the right hand of a '||' expr.
8650static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008651 Expr *OrLHS, Expr *OrRHS) {
8652 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008653 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008654 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8655 if (EvaluatesAsFalse(S, OrLHS))
8656 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008657 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8658 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8659 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008660 }
8661 }
8662}
8663
Sebastian Redl43028242009-10-26 15:24:15 +00008664/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008665/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008666static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008667 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008668 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008669 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008670 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8671
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008672 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8673 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008674 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008675 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8676 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008677 }
Sebastian Redl43028242009-10-26 15:24:15 +00008678}
8679
Steve Naroff218bc2b2007-05-04 21:54:46 +00008680// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008681ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008682 tok::TokenKind Kind,
8683 Expr *lhs, Expr *rhs) {
8684 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008685 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8686 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008687
Sebastian Redl43028242009-10-26 15:24:15 +00008688 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8689 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8690
Douglas Gregor5287f092009-11-05 00:51:44 +00008691 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8692}
8693
John McCalldadc5752010-08-24 06:29:42 +00008694ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008695 BinaryOperatorKind Opc,
8696 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008697 if (getLangOptions().CPlusPlus) {
8698 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008699
John McCall622114c2010-12-06 05:26:58 +00008700 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8701 UseBuiltinOperator = false;
8702 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8703 UseBuiltinOperator = true;
8704 } else {
8705 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8706 !rhs->getType()->isOverloadableType();
8707 }
8708
8709 if (!UseBuiltinOperator) {
8710 // Find all of the overloaded operators visible from this
8711 // point. We perform both an operator-name lookup from the local
8712 // scope and an argument-dependent lookup based on the types of
8713 // the arguments.
8714 UnresolvedSet<16> Functions;
8715 OverloadedOperatorKind OverOp
8716 = BinaryOperator::getOverloadedOperator(Opc);
8717 if (S && OverOp != OO_None)
8718 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8719 Functions);
8720
8721 // Build the (potentially-overloaded, potentially-dependent)
8722 // binary operation.
8723 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8724 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008725 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008726
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008727 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008728 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008729}
8730
John McCalldadc5752010-08-24 06:29:42 +00008731ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008732 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008733 Expr *InputExpr) {
8734 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008735 ExprValueKind VK = VK_RValue;
8736 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008737 QualType resultType;
8738 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008739 case UO_PreInc:
8740 case UO_PreDec:
8741 case UO_PostInc:
8742 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008743 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008744 Opc == UO_PreInc ||
8745 Opc == UO_PostInc,
8746 Opc == UO_PreInc ||
8747 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008748 break;
John McCalle3027922010-08-25 11:45:40 +00008749 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008750 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008751 break;
John McCall31996342011-04-07 08:22:57 +00008752 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008753 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008754 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008755 Input = move(resolved);
8756 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8757 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008758 break;
John McCall31996342011-04-07 08:22:57 +00008759 }
John McCalle3027922010-08-25 11:45:40 +00008760 case UO_Plus:
8761 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008762 Input = UsualUnaryConversions(Input.take());
8763 if (Input.isInvalid()) return ExprError();
8764 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008765 if (resultType->isDependentType())
8766 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008767 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8768 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008769 break;
8770 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8771 resultType->isEnumeralType())
8772 break;
8773 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008774 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008775 resultType->isPointerType())
8776 break;
John McCall36226622010-10-12 02:09:17 +00008777 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008778 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008779 if (Input.isInvalid()) return ExprError();
8780 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008781 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008782
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008783 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008784 << resultType << Input.get()->getSourceRange());
8785
John McCalle3027922010-08-25 11:45:40 +00008786 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008787 Input = UsualUnaryConversions(Input.take());
8788 if (Input.isInvalid()) return ExprError();
8789 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008790 if (resultType->isDependentType())
8791 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008792 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8793 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8794 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008795 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008796 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008797 else if (resultType->hasIntegerRepresentation())
8798 break;
8799 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008800 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008801 if (Input.isInvalid()) return ExprError();
8802 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008803 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008805 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008806 }
Steve Naroff35d85152007-05-07 00:24:15 +00008807 break;
John Wiegley01296292011-04-08 18:41:53 +00008808
John McCalle3027922010-08-25 11:45:40 +00008809 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008810 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008811 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8812 if (Input.isInvalid()) return ExprError();
8813 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008814 if (resultType->isDependentType())
8815 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008816 if (resultType->isScalarType()) {
8817 // C99 6.5.3.3p1: ok, fallthrough;
8818 if (Context.getLangOptions().CPlusPlus) {
8819 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8820 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008821 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8822 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008823 }
John McCall36226622010-10-12 02:09:17 +00008824 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008825 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008826 if (Input.isInvalid()) return ExprError();
8827 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008828 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008829 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008830 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008831 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008832
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008833 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008834 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008835 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008836 break;
John McCalle3027922010-08-25 11:45:40 +00008837 case UO_Real:
8838 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008839 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008840 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008841 if (Input.isInvalid()) return ExprError();
8842 if (Input.get()->getValueKind() != VK_RValue &&
8843 Input.get()->getObjectKind() == OK_Ordinary)
8844 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008845 break;
John McCalle3027922010-08-25 11:45:40 +00008846 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008847 resultType = Input.get()->getType();
8848 VK = Input.get()->getValueKind();
8849 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008850 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008851 }
John Wiegley01296292011-04-08 18:41:53 +00008852 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008853 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008854
John Wiegley01296292011-04-08 18:41:53 +00008855 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008856 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008857}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008858
John McCalldadc5752010-08-24 06:29:42 +00008859ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008860 UnaryOperatorKind Opc,
8861 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008862 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008863 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008864 // Find all of the overloaded operators visible from this
8865 // point. We perform both an operator-name lookup from the local
8866 // scope and an argument-dependent lookup based on the types of
8867 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008868 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008869 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008870 if (S && OverOp != OO_None)
8871 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8872 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008873
John McCallb268a282010-08-23 23:25:46 +00008874 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008875 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008876
John McCallb268a282010-08-23 23:25:46 +00008877 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008878}
8879
Douglas Gregor5287f092009-11-05 00:51:44 +00008880// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008881ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008882 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008883 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008884}
8885
Steve Naroff66356bd2007-09-16 14:56:35 +00008886/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008887ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008888 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008889 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008890 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008891 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008892 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008893}
8894
John McCalldadc5752010-08-24 06:29:42 +00008895ExprResult
John McCallb268a282010-08-23 23:25:46 +00008896Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008897 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008898 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8899 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8900
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008901 bool isFileScope
8902 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008903 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008904 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008905
Chris Lattner366727f2007-07-24 16:58:17 +00008906 // FIXME: there are a variety of strange constraints to enforce here, for
8907 // example, it is not possible to goto into a stmt expression apparently.
8908 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008909
Chris Lattner366727f2007-07-24 16:58:17 +00008910 // If there are sub stmts in the compound stmt, take the type of the last one
8911 // as the type of the stmtexpr.
8912 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008913 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008914 if (!Compound->body_empty()) {
8915 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008916 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008917 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008918 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8919 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008920 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008921 }
John Wiegley01296292011-04-08 18:41:53 +00008922 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008923 // Do function/array conversion on the last expression, but not
8924 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008925 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8926 if (LastExpr.isInvalid())
8927 return ExprError();
8928 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008929
John Wiegley01296292011-04-08 18:41:53 +00008930 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8931 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008932 InitializedEntity::InitializeResult(LPLoc,
8933 Ty,
8934 false),
8935 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00008936 LastExpr);
8937 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008938 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008939 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008940 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008941 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008942 else
John Wiegley01296292011-04-08 18:41:53 +00008943 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008944 StmtExprMayBindToTemp = true;
8945 }
8946 }
8947 }
Chris Lattner944d3062008-07-26 19:51:01 +00008948 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008949
Eli Friedmanba961a92009-03-23 00:24:07 +00008950 // FIXME: Check that expression type is complete/non-abstract; statement
8951 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008952 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8953 if (StmtExprMayBindToTemp)
8954 return MaybeBindToTemporary(ResStmtExpr);
8955 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008956}
Steve Naroff78864672007-08-01 22:05:33 +00008957
John McCalldadc5752010-08-24 06:29:42 +00008958ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008959 TypeSourceInfo *TInfo,
8960 OffsetOfComponent *CompPtr,
8961 unsigned NumComponents,
8962 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008963 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008964 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008965 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008966
Chris Lattnerf17bd422007-08-30 17:45:32 +00008967 // We must have at least one component that refers to the type, and the first
8968 // one is known to be a field designator. Verify that the ArgTy represents
8969 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008970 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008971 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8972 << ArgTy << TypeRange);
8973
8974 // Type must be complete per C99 7.17p3 because a declaring a variable
8975 // with an incomplete type would be ill-formed.
8976 if (!Dependent
8977 && RequireCompleteType(BuiltinLoc, ArgTy,
8978 PDiag(diag::err_offsetof_incomplete_type)
8979 << TypeRange))
8980 return ExprError();
8981
Chris Lattner78502cf2007-08-31 21:49:13 +00008982 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8983 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008984 // FIXME: This diagnostic isn't actually visible because the location is in
8985 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008986 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008987 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8988 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008989
8990 bool DidWarnAboutNonPOD = false;
8991 QualType CurrentType = ArgTy;
8992 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8993 llvm::SmallVector<OffsetOfNode, 4> Comps;
8994 llvm::SmallVector<Expr*, 4> Exprs;
8995 for (unsigned i = 0; i != NumComponents; ++i) {
8996 const OffsetOfComponent &OC = CompPtr[i];
8997 if (OC.isBrackets) {
8998 // Offset of an array sub-field. TODO: Should we allow vector elements?
8999 if (!CurrentType->isDependentType()) {
9000 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9001 if(!AT)
9002 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9003 << CurrentType);
9004 CurrentType = AT->getElementType();
9005 } else
9006 CurrentType = Context.DependentTy;
9007
9008 // The expression must be an integral expression.
9009 // FIXME: An integral constant expression?
9010 Expr *Idx = static_cast<Expr*>(OC.U.E);
9011 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9012 !Idx->getType()->isIntegerType())
9013 return ExprError(Diag(Idx->getLocStart(),
9014 diag::err_typecheck_subscript_not_integer)
9015 << Idx->getSourceRange());
9016
9017 // Record this array index.
9018 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9019 Exprs.push_back(Idx);
9020 continue;
9021 }
9022
9023 // Offset of a field.
9024 if (CurrentType->isDependentType()) {
9025 // We have the offset of a field, but we can't look into the dependent
9026 // type. Just record the identifier of the field.
9027 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9028 CurrentType = Context.DependentTy;
9029 continue;
9030 }
9031
9032 // We need to have a complete type to look into.
9033 if (RequireCompleteType(OC.LocStart, CurrentType,
9034 diag::err_offsetof_incomplete_type))
9035 return ExprError();
9036
9037 // Look for the designated field.
9038 const RecordType *RC = CurrentType->getAs<RecordType>();
9039 if (!RC)
9040 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9041 << CurrentType);
9042 RecordDecl *RD = RC->getDecl();
9043
9044 // C++ [lib.support.types]p5:
9045 // The macro offsetof accepts a restricted set of type arguments in this
9046 // International Standard. type shall be a POD structure or a POD union
9047 // (clause 9).
9048 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9049 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009050 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009051 PDiag(diag::warn_offsetof_non_pod_type)
9052 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9053 << CurrentType))
9054 DidWarnAboutNonPOD = true;
9055 }
9056
9057 // Look for the field.
9058 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9059 LookupQualifiedName(R, RD);
9060 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009061 IndirectFieldDecl *IndirectMemberDecl = 0;
9062 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009063 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009064 MemberDecl = IndirectMemberDecl->getAnonField();
9065 }
9066
Douglas Gregor882211c2010-04-28 22:16:22 +00009067 if (!MemberDecl)
9068 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9069 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9070 OC.LocEnd));
9071
Douglas Gregor10982ea2010-04-28 22:36:06 +00009072 // C99 7.17p3:
9073 // (If the specified member is a bit-field, the behavior is undefined.)
9074 //
9075 // We diagnose this as an error.
9076 if (MemberDecl->getBitWidth()) {
9077 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9078 << MemberDecl->getDeclName()
9079 << SourceRange(BuiltinLoc, RParenLoc);
9080 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9081 return ExprError();
9082 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009083
9084 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009085 if (IndirectMemberDecl)
9086 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009087
Douglas Gregord1702062010-04-29 00:18:15 +00009088 // If the member was found in a base class, introduce OffsetOfNodes for
9089 // the base class indirections.
9090 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9091 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009092 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009093 CXXBasePath &Path = Paths.front();
9094 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9095 B != BEnd; ++B)
9096 Comps.push_back(OffsetOfNode(B->Base));
9097 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009098
Francois Pichet783dd6e2010-11-21 06:08:52 +00009099 if (IndirectMemberDecl) {
9100 for (IndirectFieldDecl::chain_iterator FI =
9101 IndirectMemberDecl->chain_begin(),
9102 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9103 assert(isa<FieldDecl>(*FI));
9104 Comps.push_back(OffsetOfNode(OC.LocStart,
9105 cast<FieldDecl>(*FI), OC.LocEnd));
9106 }
9107 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009108 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009109
Douglas Gregor882211c2010-04-28 22:16:22 +00009110 CurrentType = MemberDecl->getType().getNonReferenceType();
9111 }
9112
9113 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9114 TInfo, Comps.data(), Comps.size(),
9115 Exprs.data(), Exprs.size(), RParenLoc));
9116}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009117
John McCalldadc5752010-08-24 06:29:42 +00009118ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009119 SourceLocation BuiltinLoc,
9120 SourceLocation TypeLoc,
9121 ParsedType argty,
9122 OffsetOfComponent *CompPtr,
9123 unsigned NumComponents,
9124 SourceLocation RPLoc) {
9125
Douglas Gregor882211c2010-04-28 22:16:22 +00009126 TypeSourceInfo *ArgTInfo;
9127 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9128 if (ArgTy.isNull())
9129 return ExprError();
9130
Eli Friedman06dcfd92010-08-05 10:15:45 +00009131 if (!ArgTInfo)
9132 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9133
9134 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9135 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009136}
9137
9138
John McCalldadc5752010-08-24 06:29:42 +00009139ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009140 Expr *CondExpr,
9141 Expr *LHSExpr, Expr *RHSExpr,
9142 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009143 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9144
John McCall7decc9e2010-11-18 06:31:45 +00009145 ExprValueKind VK = VK_RValue;
9146 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009147 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009148 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009149 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009150 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009151 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009152 } else {
9153 // The conditional expression is required to be a constant expression.
9154 llvm::APSInt condEval(32);
9155 SourceLocation ExpLoc;
9156 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009157 return ExprError(Diag(ExpLoc,
9158 diag::err_typecheck_choose_expr_requires_constant)
9159 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009160
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009161 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009162 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9163
9164 resType = ActiveExpr->getType();
9165 ValueDependent = ActiveExpr->isValueDependent();
9166 VK = ActiveExpr->getValueKind();
9167 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009168 }
9169
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009170 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009171 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009172 resType->isDependentType(),
9173 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009174}
9175
Steve Naroffc540d662008-09-03 18:15:37 +00009176//===----------------------------------------------------------------------===//
9177// Clang Extensions.
9178//===----------------------------------------------------------------------===//
9179
9180/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009181void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009182 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9183 PushBlockScope(BlockScope, Block);
9184 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009185 if (BlockScope)
9186 PushDeclContext(BlockScope, Block);
9187 else
9188 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009189}
9190
Mike Stump82f071f2009-02-04 22:31:32 +00009191void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009192 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009193 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009194 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009195
John McCall8cb7bdf2010-06-04 23:28:52 +00009196 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009197 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009198
John McCall3882ace2011-01-05 12:14:39 +00009199 // GetTypeForDeclarator always produces a function type for a block
9200 // literal signature. Furthermore, it is always a FunctionProtoType
9201 // unless the function was written with a typedef.
9202 assert(T->isFunctionType() &&
9203 "GetTypeForDeclarator made a non-function block signature");
9204
9205 // Look for an explicit signature in that function type.
9206 FunctionProtoTypeLoc ExplicitSignature;
9207
9208 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9209 if (isa<FunctionProtoTypeLoc>(tmp)) {
9210 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9211
9212 // Check whether that explicit signature was synthesized by
9213 // GetTypeForDeclarator. If so, don't save that as part of the
9214 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009215 if (ExplicitSignature.getLocalRangeBegin() ==
9216 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009217 // This would be much cheaper if we stored TypeLocs instead of
9218 // TypeSourceInfos.
9219 TypeLoc Result = ExplicitSignature.getResultLoc();
9220 unsigned Size = Result.getFullDataSize();
9221 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9222 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9223
9224 ExplicitSignature = FunctionProtoTypeLoc();
9225 }
John McCalla3ccba02010-06-04 11:21:44 +00009226 }
Mike Stump11289f42009-09-09 15:08:12 +00009227
John McCall3882ace2011-01-05 12:14:39 +00009228 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9229 CurBlock->FunctionType = T;
9230
9231 const FunctionType *Fn = T->getAs<FunctionType>();
9232 QualType RetTy = Fn->getResultType();
9233 bool isVariadic =
9234 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9235
John McCall8e346702010-06-04 19:02:56 +00009236 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009237
John McCalla3ccba02010-06-04 11:21:44 +00009238 // Don't allow returning a objc interface by value.
9239 if (RetTy->isObjCObjectType()) {
9240 Diag(ParamInfo.getSourceRange().getBegin(),
9241 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9242 return;
9243 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009244
John McCalla3ccba02010-06-04 11:21:44 +00009245 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009246 // return type. TODO: what should we do with declarators like:
9247 // ^ * { ... }
9248 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009249 if (RetTy != Context.DependentTy)
9250 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009251
John McCalla3ccba02010-06-04 11:21:44 +00009252 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009253 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009254 if (ExplicitSignature) {
9255 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9256 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009257 if (Param->getIdentifier() == 0 &&
9258 !Param->isImplicit() &&
9259 !Param->isInvalidDecl() &&
9260 !getLangOptions().CPlusPlus)
9261 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009262 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009263 }
John McCalla3ccba02010-06-04 11:21:44 +00009264
9265 // Fake up parameter variables if we have a typedef, like
9266 // ^ fntype { ... }
9267 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9268 for (FunctionProtoType::arg_type_iterator
9269 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9270 ParmVarDecl *Param =
9271 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9272 ParamInfo.getSourceRange().getBegin(),
9273 *I);
John McCall8e346702010-06-04 19:02:56 +00009274 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009275 }
Steve Naroffc540d662008-09-03 18:15:37 +00009276 }
John McCalla3ccba02010-06-04 11:21:44 +00009277
John McCall8e346702010-06-04 19:02:56 +00009278 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009279 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009280 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009281 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9282 CurBlock->TheDecl->param_end(),
9283 /*CheckParameterNames=*/false);
9284 }
9285
John McCalla3ccba02010-06-04 11:21:44 +00009286 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009287 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009288
John McCall8e346702010-06-04 19:02:56 +00009289 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009290 Diag(ParamInfo.getAttributes()->getLoc(),
9291 diag::warn_attribute_sentinel_not_variadic) << 1;
9292 // FIXME: remove the attribute.
9293 }
9294
9295 // Put the parameter variables in scope. We can bail out immediately
9296 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009297 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009298 return;
9299
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009300 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009301 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9302 (*AI)->setOwningFunction(CurBlock->TheDecl);
9303
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009304 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009305 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009306 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009307
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009308 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009309 }
John McCallf7b2fb52010-01-22 00:28:27 +00009310 }
Steve Naroffc540d662008-09-03 18:15:37 +00009311}
9312
9313/// ActOnBlockError - If there is an error parsing a block, this callback
9314/// is invoked to pop the information about the block from the action impl.
9315void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009316 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009317 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009318 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009319}
9320
9321/// ActOnBlockStmtExpr - This is called when the body of a block statement
9322/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009323ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009324 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009325 // If blocks are disabled, emit an error.
9326 if (!LangOpts.Blocks)
9327 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009328
Douglas Gregor9a28e842010-03-01 23:15:13 +00009329 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009330
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009331 PopDeclContext();
9332
Steve Naroffc540d662008-09-03 18:15:37 +00009333 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009334 if (!BSI->ReturnType.isNull())
9335 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009336
Mike Stump3bf1ab42009-07-28 22:04:01 +00009337 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009338 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009339
John McCallc63de662011-02-02 13:00:07 +00009340 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009341 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9342 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009343
John McCall8e346702010-06-04 19:02:56 +00009344 // If the user wrote a function type in some form, try to use that.
9345 if (!BSI->FunctionType.isNull()) {
9346 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9347
9348 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9349 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9350
9351 // Turn protoless block types into nullary block types.
9352 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009353 FunctionProtoType::ExtProtoInfo EPI;
9354 EPI.ExtInfo = Ext;
9355 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009356
9357 // Otherwise, if we don't need to change anything about the function type,
9358 // preserve its sugar structure.
9359 } else if (FTy->getResultType() == RetTy &&
9360 (!NoReturn || FTy->getNoReturnAttr())) {
9361 BlockTy = BSI->FunctionType;
9362
9363 // Otherwise, make the minimal modifications to the function type.
9364 } else {
9365 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009366 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9367 EPI.TypeQuals = 0; // FIXME: silently?
9368 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009369 BlockTy = Context.getFunctionType(RetTy,
9370 FPT->arg_type_begin(),
9371 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009372 EPI);
John McCall8e346702010-06-04 19:02:56 +00009373 }
9374
9375 // If we don't have a function type, just build one from nothing.
9376 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009377 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009378 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009379 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009381
John McCall8e346702010-06-04 19:02:56 +00009382 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9383 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009384 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009385
Chris Lattner45542ea2009-04-19 05:28:12 +00009386 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009387 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009388 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009389
Chris Lattner60f84492011-02-17 23:58:47 +00009390 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009391
John McCallc63de662011-02-02 13:00:07 +00009392 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009393
Ted Kremenek1767a272011-02-23 01:51:48 +00009394 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9395 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009396 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009397}
9398
John McCalldadc5752010-08-24 06:29:42 +00009399ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009400 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009401 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009402 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009403 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009404 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009405}
9406
John McCalldadc5752010-08-24 06:29:42 +00009407ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009408 Expr *E, TypeSourceInfo *TInfo,
9409 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009410 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009411
Eli Friedman121ba0c2008-08-09 23:32:40 +00009412 // Get the va_list type
9413 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009414 if (VaListType->isArrayType()) {
9415 // Deal with implicit array decay; for example, on x86-64,
9416 // va_list is an array, but it's supposed to decay to
9417 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009418 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009419 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009420 ExprResult Result = UsualUnaryConversions(E);
9421 if (Result.isInvalid())
9422 return ExprError();
9423 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009424 } else {
9425 // Otherwise, the va_list argument must be an l-value because
9426 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009427 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009428 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009429 return ExprError();
9430 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009431
Douglas Gregorad3150c2009-05-19 23:10:31 +00009432 if (!E->isTypeDependent() &&
9433 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009434 return ExprError(Diag(E->getLocStart(),
9435 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009436 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009437 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009438
Eli Friedmanba961a92009-03-23 00:24:07 +00009439 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009440 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009441
Abramo Bagnara27db2392010-08-10 10:06:15 +00009442 QualType T = TInfo->getType().getNonLValueExprType(Context);
9443 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009444}
9445
John McCalldadc5752010-08-24 06:29:42 +00009446ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009447 // The type of __null will be int or long, depending on the size of
9448 // pointers on the target.
9449 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009450 unsigned pw = Context.Target.getPointerWidth(0);
9451 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009452 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009453 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009454 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009455 else if (pw == Context.Target.getLongLongWidth())
9456 Ty = Context.LongLongTy;
9457 else {
9458 assert(!"I don't know size of pointer!");
9459 Ty = Context.IntTy;
9460 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009461
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009462 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009463}
9464
Alexis Huntc46382e2010-04-28 23:02:27 +00009465static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009466 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009467 if (!SemaRef.getLangOptions().ObjC1)
9468 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009469
Anders Carlssonace5d072009-11-10 04:46:30 +00009470 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9471 if (!PT)
9472 return;
9473
9474 // Check if the destination is of type 'id'.
9475 if (!PT->isObjCIdType()) {
9476 // Check if the destination is the 'NSString' interface.
9477 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9478 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9479 return;
9480 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009481
Anders Carlssonace5d072009-11-10 04:46:30 +00009482 // Strip off any parens and casts.
9483 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9484 if (!SL || SL->isWide())
9485 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009486
Douglas Gregora771f462010-03-31 17:46:05 +00009487 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009488}
9489
Chris Lattner9bad62c2008-01-04 18:04:52 +00009490bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9491 SourceLocation Loc,
9492 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009493 Expr *SrcExpr, AssignmentAction Action,
9494 bool *Complained) {
9495 if (Complained)
9496 *Complained = false;
9497
Chris Lattner9bad62c2008-01-04 18:04:52 +00009498 // Decode the result (notice that AST's are still created for extensions).
9499 bool isInvalid = false;
9500 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009501 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009502
Chris Lattner9bad62c2008-01-04 18:04:52 +00009503 switch (ConvTy) {
9504 default: assert(0 && "Unknown conversion type");
9505 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009506 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009507 DiagKind = diag::ext_typecheck_convert_pointer_int;
9508 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009509 case IntToPointer:
9510 DiagKind = diag::ext_typecheck_convert_int_pointer;
9511 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009512 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009513 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009514 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9515 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009516 case IncompatiblePointerSign:
9517 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9518 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009519 case FunctionVoidPointer:
9520 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9521 break;
John McCall4fff8f62011-02-01 00:10:29 +00009522 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009523 // Perform array-to-pointer decay if necessary.
9524 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9525
John McCall4fff8f62011-02-01 00:10:29 +00009526 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9527 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9528 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9529 DiagKind = diag::err_typecheck_incompatible_address_space;
9530 break;
9531 }
9532
9533 llvm_unreachable("unknown error case for discarding qualifiers!");
9534 // fallthrough
9535 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009536 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009537 // If the qualifiers lost were because we were applying the
9538 // (deprecated) C++ conversion from a string literal to a char*
9539 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9540 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009541 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009542 // bit of refactoring (so that the second argument is an
9543 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009544 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009545 // C++ semantics.
9546 if (getLangOptions().CPlusPlus &&
9547 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9548 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009549 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9550 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009551 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009552 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009553 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009554 case IntToBlockPointer:
9555 DiagKind = diag::err_int_to_block_pointer;
9556 break;
9557 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009558 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009559 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009560 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009561 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009562 // it can give a more specific diagnostic.
9563 DiagKind = diag::warn_incompatible_qualified_id;
9564 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009565 case IncompatibleVectors:
9566 DiagKind = diag::warn_incompatible_vectors;
9567 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009568 case Incompatible:
9569 DiagKind = diag::err_typecheck_convert_incompatible;
9570 isInvalid = true;
9571 break;
9572 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009573
Douglas Gregorc68e1402010-04-09 00:35:39 +00009574 QualType FirstType, SecondType;
9575 switch (Action) {
9576 case AA_Assigning:
9577 case AA_Initializing:
9578 // The destination type comes first.
9579 FirstType = DstType;
9580 SecondType = SrcType;
9581 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009582
Douglas Gregorc68e1402010-04-09 00:35:39 +00009583 case AA_Returning:
9584 case AA_Passing:
9585 case AA_Converting:
9586 case AA_Sending:
9587 case AA_Casting:
9588 // The source type comes first.
9589 FirstType = SrcType;
9590 SecondType = DstType;
9591 break;
9592 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009593
Douglas Gregorc68e1402010-04-09 00:35:39 +00009594 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009595 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009596 if (Complained)
9597 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009598 return isInvalid;
9599}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009600
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009601bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009602 llvm::APSInt ICEResult;
9603 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9604 if (Result)
9605 *Result = ICEResult;
9606 return false;
9607 }
9608
Anders Carlssone54e8a12008-11-30 19:50:32 +00009609 Expr::EvalResult EvalResult;
9610
Mike Stump4e1f26a2009-02-19 03:04:26 +00009611 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009612 EvalResult.HasSideEffects) {
9613 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9614
9615 if (EvalResult.Diag) {
9616 // We only show the note if it's not the usual "invalid subexpression"
9617 // or if it's actually in a subexpression.
9618 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9619 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9620 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9621 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009622
Anders Carlssone54e8a12008-11-30 19:50:32 +00009623 return true;
9624 }
9625
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009626 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9627 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009628
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009629 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009630 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9631 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009632 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009633
Anders Carlssone54e8a12008-11-30 19:50:32 +00009634 if (Result)
9635 *Result = EvalResult.Val.getInt();
9636 return false;
9637}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009638
Douglas Gregorff790f12009-11-26 00:44:06 +00009639void
Mike Stump11289f42009-09-09 15:08:12 +00009640Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009641 ExprEvalContexts.push_back(
9642 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009643}
9644
Mike Stump11289f42009-09-09 15:08:12 +00009645void
Douglas Gregorff790f12009-11-26 00:44:06 +00009646Sema::PopExpressionEvaluationContext() {
9647 // Pop the current expression evaluation context off the stack.
9648 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9649 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009650
Douglas Gregorfab31f42009-12-12 07:57:52 +00009651 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9652 if (Rec.PotentiallyReferenced) {
9653 // Mark any remaining declarations in the current position of the stack
9654 // as "referenced". If they were not meant to be referenced, semantic
9655 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009656 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009657 I = Rec.PotentiallyReferenced->begin(),
9658 IEnd = Rec.PotentiallyReferenced->end();
9659 I != IEnd; ++I)
9660 MarkDeclarationReferenced(I->first, I->second);
9661 }
9662
9663 if (Rec.PotentiallyDiagnosed) {
9664 // Emit any pending diagnostics.
9665 for (PotentiallyEmittedDiagnostics::iterator
9666 I = Rec.PotentiallyDiagnosed->begin(),
9667 IEnd = Rec.PotentiallyDiagnosed->end();
9668 I != IEnd; ++I)
9669 Diag(I->first, I->second);
9670 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009671 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009672
9673 // When are coming out of an unevaluated context, clear out any
9674 // temporaries that we may have created as part of the evaluation of
9675 // the expression in that context: they aren't relevant because they
9676 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009677 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009678 ExprTemporaries.size() > Rec.NumTemporaries)
9679 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9680 ExprTemporaries.end());
9681
9682 // Destroy the popped expression evaluation record.
9683 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009684}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009685
9686/// \brief Note that the given declaration was referenced in the source code.
9687///
9688/// This routine should be invoke whenever a given declaration is referenced
9689/// in the source code, and where that reference occurred. If this declaration
9690/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9691/// C99 6.9p3), then the declaration will be marked as used.
9692///
9693/// \param Loc the location where the declaration was referenced.
9694///
9695/// \param D the declaration that has been referenced by the source code.
9696void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9697 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009698
Douglas Gregorebada0772010-06-17 23:14:26 +00009699 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009700 return;
Mike Stump11289f42009-09-09 15:08:12 +00009701
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009702 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9703 // template or not. The reason for this is that unevaluated expressions
9704 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9705 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009706 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009707 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009708 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009709 return;
9710 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009711
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009712 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9713 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009714
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009715 // Do not mark anything as "used" within a dependent context; wait for
9716 // an instantiation.
9717 if (CurContext->isDependentContext())
9718 return;
Mike Stump11289f42009-09-09 15:08:12 +00009719
Douglas Gregorff790f12009-11-26 00:44:06 +00009720 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009721 case Unevaluated:
9722 // We are in an expression that is not potentially evaluated; do nothing.
9723 return;
Mike Stump11289f42009-09-09 15:08:12 +00009724
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009725 case PotentiallyEvaluated:
9726 // We are in a potentially-evaluated expression, so this declaration is
9727 // "used"; handle this below.
9728 break;
Mike Stump11289f42009-09-09 15:08:12 +00009729
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009730 case PotentiallyPotentiallyEvaluated:
9731 // We are in an expression that may be potentially evaluated; queue this
9732 // declaration reference until we know whether the expression is
9733 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009734 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009735 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009736
9737 case PotentiallyEvaluatedIfUsed:
9738 // Referenced declarations will only be used if the construct in the
9739 // containing expression is used.
9740 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009741 }
Mike Stump11289f42009-09-09 15:08:12 +00009742
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009743 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009744 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009745 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009746 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009747 if (Constructor->getParent()->hasTrivialConstructor())
9748 return;
9749 if (!Constructor->isUsed(false))
9750 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009751 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009752 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009753 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009754 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9755 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009756
Douglas Gregor88d292c2010-05-13 16:44:06 +00009757 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009758 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009759 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009760 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009761 if (Destructor->isVirtual())
9762 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009763 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9764 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9765 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009766 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009767 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009768 } else if (MethodDecl->isVirtual())
9769 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009770 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009771 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009772 // Recursive functions should be marked when used from another function.
9773 if (CurContext == Function) return;
9774
Mike Stump11289f42009-09-09 15:08:12 +00009775 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009776 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009777 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009778 bool AlreadyInstantiated = false;
9779 if (FunctionTemplateSpecializationInfo *SpecInfo
9780 = Function->getTemplateSpecializationInfo()) {
9781 if (SpecInfo->getPointOfInstantiation().isInvalid())
9782 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009783 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009784 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009785 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009786 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009787 = Function->getMemberSpecializationInfo()) {
9788 if (MSInfo->getPointOfInstantiation().isInvalid())
9789 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009790 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009791 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009792 AlreadyInstantiated = true;
9793 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009794
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009795 if (!AlreadyInstantiated) {
9796 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9797 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9798 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9799 Loc));
9800 else
Chandler Carruth54080172010-08-25 08:44:16 +00009801 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009802 }
John McCall83779672011-02-19 02:53:41 +00009803 } else {
9804 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009805 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9806 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009807 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009808 MarkDeclarationReferenced(Loc, *i);
9809 }
John McCall83779672011-02-19 02:53:41 +00009810 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009811
John McCall83779672011-02-19 02:53:41 +00009812 // Keep track of used but undefined functions.
9813 if (!Function->isPure() && !Function->hasBody() &&
9814 Function->getLinkage() != ExternalLinkage) {
9815 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9816 if (old.isInvalid()) old = Loc;
9817 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009818
John McCall83779672011-02-19 02:53:41 +00009819 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009820 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009821 }
Mike Stump11289f42009-09-09 15:08:12 +00009822
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009823 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009824 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009825 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009826 Var->getInstantiatedFromStaticDataMember()) {
9827 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9828 assert(MSInfo && "Missing member specialization information?");
9829 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9830 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9831 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009832 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009833 }
9834 }
Mike Stump11289f42009-09-09 15:08:12 +00009835
John McCall15dd4042011-02-21 19:25:48 +00009836 // Keep track of used but undefined variables. We make a hole in
9837 // the warning for static const data members with in-line
9838 // initializers.
John McCall83779672011-02-19 02:53:41 +00009839 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009840 && Var->getLinkage() != ExternalLinkage
9841 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009842 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9843 if (old.isInvalid()) old = Loc;
9844 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009845
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009846 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009847 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009848 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009849}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009850
Douglas Gregor5597ab42010-05-07 23:12:07 +00009851namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009852 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009853 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009854 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009855 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9856 Sema &S;
9857 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009858
Douglas Gregor5597ab42010-05-07 23:12:07 +00009859 public:
9860 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009861
Douglas Gregor5597ab42010-05-07 23:12:07 +00009862 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009863
9864 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9865 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009866 };
9867}
9868
Chandler Carruthaf80f662010-06-09 08:17:30 +00009869bool MarkReferencedDecls::TraverseTemplateArgument(
9870 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009871 if (Arg.getKind() == TemplateArgument::Declaration) {
9872 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9873 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009874
9875 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009876}
9877
Chandler Carruthaf80f662010-06-09 08:17:30 +00009878bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009879 if (ClassTemplateSpecializationDecl *Spec
9880 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9881 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009882 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009883 }
9884
Chandler Carruthc65667c2010-06-10 10:31:57 +00009885 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009886}
9887
9888void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9889 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009890 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009891}
9892
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009893namespace {
9894 /// \brief Helper class that marks all of the declarations referenced by
9895 /// potentially-evaluated subexpressions as "referenced".
9896 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9897 Sema &S;
9898
9899 public:
9900 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9901
9902 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9903
9904 void VisitDeclRefExpr(DeclRefExpr *E) {
9905 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9906 }
9907
9908 void VisitMemberExpr(MemberExpr *E) {
9909 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009910 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009911 }
9912
9913 void VisitCXXNewExpr(CXXNewExpr *E) {
9914 if (E->getConstructor())
9915 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9916 if (E->getOperatorNew())
9917 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9918 if (E->getOperatorDelete())
9919 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009920 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009921 }
9922
9923 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9924 if (E->getOperatorDelete())
9925 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009926 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9927 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9928 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9929 S.MarkDeclarationReferenced(E->getLocStart(),
9930 S.LookupDestructor(Record));
9931 }
9932
Douglas Gregor32b3de52010-09-11 23:32:50 +00009933 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009934 }
9935
9936 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9937 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009938 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009939 }
9940
9941 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9942 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9943 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009944
9945 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9946 Visit(E->getExpr());
9947 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009948 };
9949}
9950
9951/// \brief Mark any declarations that appear within this expression or any
9952/// potentially-evaluated subexpressions as "referenced".
9953void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9954 EvaluatedExprMarker(*this).Visit(E);
9955}
9956
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009957/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9958/// of the program being compiled.
9959///
9960/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009961/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009962/// possibility that the code will actually be executable. Code in sizeof()
9963/// expressions, code used only during overload resolution, etc., are not
9964/// potentially evaluated. This routine will suppress such diagnostics or,
9965/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009966/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009967/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009968///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009969/// This routine should be used for all diagnostics that describe the run-time
9970/// behavior of a program, such as passing a non-POD value through an ellipsis.
9971/// Failure to do so will likely result in spurious diagnostics or failures
9972/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009973bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009974 const PartialDiagnostic &PD) {
9975 switch (ExprEvalContexts.back().Context ) {
9976 case Unevaluated:
9977 // The argument will never be evaluated, so don't complain.
9978 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009979
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009980 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009981 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009982 if (stmt && getCurFunctionOrMethodDecl()) {
9983 FunctionScopes.back()->PossiblyUnreachableDiags.
9984 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9985 }
9986 else
9987 Diag(Loc, PD);
9988
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009989 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009990
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009991 case PotentiallyPotentiallyEvaluated:
9992 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9993 break;
9994 }
9995
9996 return false;
9997}
9998
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009999bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10000 CallExpr *CE, FunctionDecl *FD) {
10001 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10002 return false;
10003
10004 PartialDiagnostic Note =
10005 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10006 << FD->getDeclName() : PDiag();
10007 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010008
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010009 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010010 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010011 PDiag(diag::err_call_function_incomplete_return)
10012 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010013 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010014 << CE->getSourceRange(),
10015 std::make_pair(NoteLoc, Note)))
10016 return true;
10017
10018 return false;
10019}
10020
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010021// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010022// will prevent this condition from triggering, which is what we want.
10023void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10024 SourceLocation Loc;
10025
John McCall0506e4a2009-11-11 02:41:58 +000010026 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010027 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010028
John McCalld5707ab2009-10-12 21:59:07 +000010029 if (isa<BinaryOperator>(E)) {
10030 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010031 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010032 return;
10033
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010034 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10035
John McCallb0e419e2009-11-12 00:06:05 +000010036 // Greylist some idioms by putting them into a warning subcategory.
10037 if (ObjCMessageExpr *ME
10038 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10039 Selector Sel = ME->getSelector();
10040
John McCallb0e419e2009-11-12 00:06:05 +000010041 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010042 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010043 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10044
10045 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010046 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010047 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10048 }
John McCall0506e4a2009-11-11 02:41:58 +000010049
John McCalld5707ab2009-10-12 21:59:07 +000010050 Loc = Op->getOperatorLoc();
10051 } else if (isa<CXXOperatorCallExpr>(E)) {
10052 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010053 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010054 return;
10055
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010056 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010057 Loc = Op->getOperatorLoc();
10058 } else {
10059 // Not an assignment.
10060 return;
10061 }
10062
John McCalld5707ab2009-10-12 21:59:07 +000010063 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +000010064 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010065
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010066 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010067
10068 if (IsOrAssign)
10069 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10070 << FixItHint::CreateReplacement(Loc, "!=");
10071 else
10072 Diag(Loc, diag::note_condition_assign_to_comparison)
10073 << FixItHint::CreateReplacement(Loc, "==");
10074
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010075 Diag(Loc, diag::note_condition_assign_silence)
10076 << FixItHint::CreateInsertion(Open, "(")
10077 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +000010078}
10079
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010080/// \brief Redundant parentheses over an equality comparison can indicate
10081/// that the user intended an assignment used as condition.
10082void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010083 // Don't warn if the parens came from a macro.
10084 SourceLocation parenLoc = parenE->getLocStart();
10085 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10086 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010087 // Don't warn for dependent expressions.
10088 if (parenE->isTypeDependent())
10089 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010090
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010091 Expr *E = parenE->IgnoreParens();
10092
10093 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010094 if (opE->getOpcode() == BO_EQ &&
10095 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10096 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010097 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010098
Ted Kremenekae022092011-02-02 02:20:30 +000010099 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10100 Diag(Loc, diag::note_equality_comparison_to_assign)
10101 << FixItHint::CreateReplacement(Loc, "=");
10102 Diag(Loc, diag::note_equality_comparison_silence)
10103 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10104 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010105 }
10106}
10107
John Wiegley01296292011-04-08 18:41:53 +000010108ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010109 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010110 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10111 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010112
10113 if (!E->isTypeDependent()) {
John Wiegley01296292011-04-08 18:41:53 +000010114 if (E->isBoundMemberFunction(Context)) {
10115 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010116 << E->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +000010117 return ExprError();
10118 }
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010119
John McCall34376a62010-12-04 03:47:34 +000010120 if (getLangOptions().CPlusPlus)
10121 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10122
John Wiegley01296292011-04-08 18:41:53 +000010123 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10124 if (ERes.isInvalid())
10125 return ExprError();
10126 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010127
10128 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010129 if (!T->isScalarType()) { // C99 6.8.4.1p1
10130 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10131 << T << E->getSourceRange();
10132 return ExprError();
10133 }
John McCalld5707ab2009-10-12 21:59:07 +000010134 }
10135
John Wiegley01296292011-04-08 18:41:53 +000010136 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010137}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010138
John McCalldadc5752010-08-24 06:29:42 +000010139ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10140 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010141 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010142 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010143
10144 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010145}
John McCall36e7fe32010-10-12 00:20:44 +000010146
John McCall31996342011-04-07 08:22:57 +000010147namespace {
10148 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010149 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010150
10151 Sema &S;
10152
10153 /// The current destination type.
10154 QualType DestType;
10155
10156 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10157 : S(S), DestType(castType) {}
10158
John McCall39439732011-04-09 22:50:59 +000010159 ExprResult VisitStmt(Stmt *S) {
John McCall31996342011-04-07 08:22:57 +000010160 llvm_unreachable("unexpected expression kind!");
John McCall39439732011-04-09 22:50:59 +000010161 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010162 }
10163
John McCall39439732011-04-09 22:50:59 +000010164 ExprResult VisitCallExpr(CallExpr *call) {
10165 Expr *callee = call->getCallee();
John McCall31996342011-04-07 08:22:57 +000010166
John McCall39439732011-04-09 22:50:59 +000010167 bool wasBlock;
10168 QualType type = callee->getType();
10169 if (const PointerType *ptr = type->getAs<PointerType>()) {
10170 type = ptr->getPointeeType();
10171 wasBlock = false;
10172 } else {
10173 type = type->castAs<BlockPointerType>()->getPointeeType();
10174 wasBlock = true;
10175 }
10176 const FunctionType *fnType = type->castAs<FunctionType>();
John McCall31996342011-04-07 08:22:57 +000010177
John McCall39439732011-04-09 22:50:59 +000010178 // Verify that this is a legal result type of a function.
10179 if (DestType->isArrayType() || DestType->isFunctionType()) {
10180 unsigned diagID = diag::err_func_returning_array_function;
10181 if (wasBlock) diagID = diag::err_block_returning_array_function;
John McCall31996342011-04-07 08:22:57 +000010182
John McCall39439732011-04-09 22:50:59 +000010183 S.Diag(call->getExprLoc(), diagID)
10184 << DestType->isFunctionType() << DestType;
10185 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010186 }
10187
John McCall39439732011-04-09 22:50:59 +000010188 // Otherwise, go ahead and set DestType as the call's result.
10189 call->setType(DestType.getNonLValueExprType(S.Context));
10190 call->setValueKind(Expr::getValueKindForType(DestType));
10191 assert(call->getObjectKind() == OK_Ordinary);
John McCall31996342011-04-07 08:22:57 +000010192
John McCall39439732011-04-09 22:50:59 +000010193 // Rebuild the function type, replacing the result type with DestType.
10194 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10195 DestType = S.Context.getFunctionType(DestType,
10196 proto->arg_type_begin(),
10197 proto->getNumArgs(),
10198 proto->getExtProtoInfo());
10199 else
10200 DestType = S.Context.getFunctionNoProtoType(DestType,
10201 fnType->getExtInfo());
John McCall31996342011-04-07 08:22:57 +000010202
John McCall39439732011-04-09 22:50:59 +000010203 // Rebuild the appropriate pointer-to-function type.
10204 if (wasBlock)
10205 DestType = S.Context.getBlockPointerType(DestType);
10206 else
10207 DestType = S.Context.getPointerType(DestType);
10208
10209 // Finally, we can recurse.
10210 ExprResult calleeResult = Visit(callee);
10211 if (!calleeResult.isUsable()) return ExprError();
10212 call->setCallee(calleeResult.take());
10213
10214 // Bind a temporary if necessary.
10215 return S.MaybeBindToTemporary(call);
John McCall31996342011-04-07 08:22:57 +000010216 }
10217
John McCall39439732011-04-09 22:50:59 +000010218 /// Rebuild an expression which simply semantically wraps another
10219 /// expression which it shares the type and value kind of.
10220 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10221 ExprResult subResult = Visit(expr->getSubExpr());
10222 if (!subResult.isUsable()) return ExprError();
10223 Expr *subExpr = subResult.take();
10224 expr->setSubExpr(subExpr);
10225 expr->setType(subExpr->getType());
10226 expr->setValueKind(subExpr->getValueKind());
10227 assert(expr->getObjectKind() == OK_Ordinary);
10228 return expr;
10229 }
John McCall31996342011-04-07 08:22:57 +000010230
John McCall39439732011-04-09 22:50:59 +000010231 ExprResult VisitParenExpr(ParenExpr *paren) {
10232 return rebuildSugarExpr(paren);
10233 }
10234
10235 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10236 return rebuildSugarExpr(op);
10237 }
10238
10239 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice) {
10240 // Rebuild an inner resolution by stripping it and propagating
10241 // the new type down.
10242 if (ice->getCastKind() == CK_ResolveUnknownAnyType)
10243 return Visit(ice->getSubExpr());
10244
10245 // The only other case we should be able to get here is a
10246 // function-to-pointer decay.
10247 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
10248 ice->setType(DestType);
10249 assert(ice->getValueKind() == VK_RValue);
10250 assert(ice->getObjectKind() == OK_Ordinary);
10251
10252 // Rebuild the sub-expression as the pointee (function) type.
10253 DestType = DestType->castAs<PointerType>()->getPointeeType();
10254
10255 ExprResult result = Visit(ice->getSubExpr());
10256 if (!result.isUsable()) return ExprError();
10257
10258 ice->setSubExpr(result.take());
10259 return S.Owned(ice);
10260 }
10261
10262 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10263 ExprValueKind valueKind = VK_LValue;
10264 if (S.getLangOptions().CPlusPlus) {
10265 // FIXME: if the value was resolved as a reference type, we
10266 // should really remember that somehow, or else we'll be
10267 // missing a load.
10268 DestType = DestType.getNonReferenceType();
10269 } else if (DestType->isFunctionType()) {
10270 valueKind = VK_RValue;
10271 }
10272
10273 return S.Owned(ImplicitCastExpr::Create(S.Context, DestType,
10274 CK_ResolveUnknownAnyType,
10275 ref, 0, valueKind));
John McCall31996342011-04-07 08:22:57 +000010276 }
10277 };
10278}
10279
10280/// Check a cast of an unknown-any type. We intentionally only
10281/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010282ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10283 Expr *castExpr, CastKind &castKind,
10284 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010285 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010286 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10287 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010288
John McCall39439732011-04-09 22:50:59 +000010289 castExpr = result.take();
10290 VK = castExpr->getValueKind();
10291 castKind = CK_NoOp;
10292
10293 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010294}
10295
10296static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10297 Expr *orig = e;
10298 while (true) {
10299 e = e->IgnoreParenImpCasts();
10300 if (CallExpr *call = dyn_cast<CallExpr>(e))
10301 e = call->getCallee();
10302 else
10303 break;
10304 }
10305
10306 assert(isa<DeclRefExpr>(e) && "unexpected form of unknown-any expression");
10307 DeclRefExpr *ref = cast<DeclRefExpr>(e);
10308 S.Diag(ref->getLocation(), diag::err_bad_use_of_unknown_any)
10309 << ref->getDecl() << orig->getSourceRange();
10310
10311 // Never recoverable.
10312 return ExprError();
10313}
10314
John McCall36e7fe32010-10-12 00:20:44 +000010315/// Check for operands with placeholder types and complain if found.
10316/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010317ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010318 // Placeholder types are always *exactly* the appropriate builtin type.
10319 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010320
John McCall31996342011-04-07 08:22:57 +000010321 // Overloaded expressions.
10322 if (type == Context.OverloadTy)
10323 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010324 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010325 QualType(),
10326 diag::err_ovl_unresolvable);
10327
10328 // Expressions of unknown type.
10329 if (type == Context.UnknownAnyTy)
10330 return diagnoseUnknownAnyExpr(*this, E);
10331
10332 assert(!type->isPlaceholderType());
10333 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010334}