blob: e73708981891909ced354075ad64906ef61e88b2 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
218/// UsualUnaryConversions - Performs various conversions that are common to most
219/// operators (C99 6.3). The conversions of array and function types are
220/// sometimes surpressed. For example, the array->pointer conversion doesn't
221/// apply if the array is an argument to the sizeof or address (&) operators.
222/// In these instances, this routine should *not* be called.
223Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
224 QualType Ty = Expr->getType();
225 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
226
Douglas Gregor70b307e2009-05-01 20:41:21 +0000227 // C99 6.3.1.1p2:
228 //
229 // The following may be used in an expression wherever an int or
230 // unsigned int may be used:
231 // - an object or expression with an integer type whose integer
232 // conversion rank is less than or equal to the rank of int
233 // and unsigned int.
234 // - A bit-field of type _Bool, int, signed int, or unsigned int.
235 //
236 // If an int can represent all values of the original type, the
237 // value is converted to an int; otherwise, it is converted to an
238 // unsigned int. These are called the integer promotions. All
239 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000240 QualType PTy = Context.isPromotableBitField(Expr);
241 if (!PTy.isNull()) {
242 ImpCastExprToType(Expr, PTy);
243 return Expr;
244 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000245 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000246 QualType PT = Context.getPromotedIntegerType(Ty);
247 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000248 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000249 }
250
Douglas Gregor70b307e2009-05-01 20:41:21 +0000251 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return Expr;
253}
254
Chris Lattner9305c3d2008-07-25 22:25:12 +0000255/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
256/// do not have a prototype. Arguments that have type float are promoted to
257/// double. All other argument types are converted by UsualUnaryConversions().
258void Sema::DefaultArgumentPromotion(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
261
262 // If this is a 'float' (CVR qualified or typedef) promote to double.
263 if (const BuiltinType *BT = Ty->getAsBuiltinType())
264 if (BT->getKind() == BuiltinType::Float)
265 return ImpCastExprToType(Expr, Context.DoubleTy);
266
267 UsualUnaryConversions(Expr);
268}
269
Chris Lattner81f00ed2009-04-12 08:11:20 +0000270/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
271/// will warn if the resulting type is not a POD type, and rejects ObjC
272/// interfaces passed by value. This returns true if the argument type is
273/// completely illegal.
274bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000275 DefaultArgumentPromotion(Expr);
276
Chris Lattner81f00ed2009-04-12 08:11:20 +0000277 if (Expr->getType()->isObjCInterfaceType()) {
278 Diag(Expr->getLocStart(),
279 diag::err_cannot_pass_objc_interface_to_vararg)
280 << Expr->getType() << CT;
281 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000282 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000283
284 if (!Expr->getType()->isPODType())
285 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
286 << Expr->getType() << CT;
287
288 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000289}
290
291
Chris Lattner299b8842008-07-25 21:10:04 +0000292/// UsualArithmeticConversions - Performs various conversions that are common to
293/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
294/// routine returns the first non-arithmetic type found. The client is
295/// responsible for emitting appropriate error diagnostics.
296/// FIXME: verify the conversion rules for "complex int" are consistent with
297/// GCC.
298QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
299 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000300 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000301 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000302
303 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000304
Chris Lattner299b8842008-07-25 21:10:04 +0000305 // For conversion purposes, we ignore any qualifiers.
306 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000307 QualType lhs =
308 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
309 QualType rhs =
310 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000311
312 // If both types are identical, no conversion is needed.
313 if (lhs == rhs)
314 return lhs;
315
316 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
317 // The caller can deal with this (e.g. pointer + int).
318 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
319 return lhs;
320
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000321 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000322 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000323 if (!LHSBitfieldPromoteTy.isNull())
324 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000325 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000326 if (!RHSBitfieldPromoteTy.isNull())
327 rhs = RHSBitfieldPromoteTy;
328
Eli Friedman6ae7d112009-08-19 07:44:53 +0000329 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000330 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000331 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000332 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000333 return destType;
334}
335
Chris Lattner299b8842008-07-25 21:10:04 +0000336//===----------------------------------------------------------------------===//
337// Semantic Analysis for various Expression Types
338//===----------------------------------------------------------------------===//
339
340
Steve Naroff87d58b42007-09-16 03:34:24 +0000341/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
343/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
344/// multiple tokens. However, the common case is that StringToks points to one
345/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000346///
347Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000348Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000349 assert(NumStringToks && "Must have at least one string!");
350
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000351 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000352 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000353 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000354
355 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
356 for (unsigned i = 0; i != NumStringToks; ++i)
357 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000358
Chris Lattnera6dcce32008-02-11 00:02:17 +0000359 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000360 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000361 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000362
363 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
364 if (getLangOptions().CPlusPlus)
365 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000366
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367 // Get an array type for the string, according to C99 6.4.5. This includes
368 // the nul terminator character as well as the string length for pascal
369 // strings.
370 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000371 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000372 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000373
Chris Lattner4b009652007-07-25 00:24:17 +0000374 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000375 return Owned(StringLiteral::Create(Context, Literal.GetString(),
376 Literal.GetStringLength(),
377 Literal.AnyWide, StrTy,
378 &StringTokLocs[0],
379 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000380}
381
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000382/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
383/// CurBlock to VD should cause it to be snapshotted (as we do for auto
384/// variables defined outside the block) or false if this is not needed (e.g.
385/// for values inside the block or for globals).
386///
Chris Lattner0b464252009-04-21 22:26:47 +0000387/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
388/// up-to-date.
389///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000390static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
391 ValueDecl *VD) {
392 // If the value is defined inside the block, we couldn't snapshot it even if
393 // we wanted to.
394 if (CurBlock->TheDecl == VD->getDeclContext())
395 return false;
396
397 // If this is an enum constant or function, it is constant, don't snapshot.
398 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
399 return false;
400
401 // If this is a reference to an extern, static, or global variable, no need to
402 // snapshot it.
403 // FIXME: What about 'const' variables in C++?
404 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000405 if (!Var->hasLocalStorage())
406 return false;
407
408 // Blocks that have these can't be constant.
409 CurBlock->hasBlockDeclRefExprs = true;
410
411 // If we have nested blocks, the decl may be declared in an outer block (in
412 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
413 // be defined outside all of the current blocks (in which case the blocks do
414 // all get the bit). Walk the nesting chain.
415 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
416 NextBlock = NextBlock->PrevBlockInfo) {
417 // If we found the defining block for the variable, don't mark the block as
418 // having a reference outside it.
419 if (NextBlock->TheDecl == VD->getDeclContext())
420 break;
421
422 // Otherwise, the DeclRef from the inner block causes the outer one to need
423 // a snapshot as well.
424 NextBlock->hasBlockDeclRefExprs = true;
425 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000426
427 return true;
428}
429
430
431
Steve Naroff0acc9c92007-09-15 18:49:24 +0000432/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000433/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000434/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000435/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000436/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000437Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
438 IdentifierInfo &II,
439 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000440 const CXXScopeSpec *SS,
441 bool isAddressOfOperand) {
442 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000443 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000444}
445
Douglas Gregor566782a2009-01-06 05:10:23 +0000446/// BuildDeclRefExpr - Build either a DeclRefExpr or a
447/// QualifiedDeclRefExpr based on whether or not SS is a
448/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000449Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000450Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
451 bool TypeDependent, bool ValueDependent,
452 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000453 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
454 Diag(Loc,
455 diag::err_auto_variable_cannot_appear_in_own_initializer)
456 << D->getDeclName();
457 return ExprError();
458 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000459
460 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
461 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
462 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
463 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
464 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
465 << D->getIdentifier() << FD->getDeclName();
466 Diag(D->getLocation(), diag::note_local_variable_declared_here)
467 << D->getIdentifier();
468 return ExprError();
469 }
470 }
471 }
472 }
473
Douglas Gregor98189262009-06-19 23:52:42 +0000474 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000475
476 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000477 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000478 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
479 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000480 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000481 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000482 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
483
484 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000485}
486
Douglas Gregor723d3332009-01-07 00:43:41 +0000487/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
488/// variable corresponding to the anonymous union or struct whose type
489/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000490static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
491 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 assert(Record->isAnonymousStructOrUnion() &&
493 "Record must be an anonymous struct or union!");
494
Mike Stumpe127ae32009-05-16 07:39:55 +0000495 // FIXME: Once Decls are directly linked together, this will be an O(1)
496 // operation rather than a slow walk through DeclContext's vector (which
497 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000498 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000499 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
500 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 D != DEnd; ++D) {
502 if (*D == Record) {
503 // The object for the anonymous struct/union directly
504 // follows its type in the list of declarations.
505 ++D;
506 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000507 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000508 return *D;
509 }
510 }
511
512 assert(false && "Missing object for anonymous record");
513 return 0;
514}
515
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000516/// \brief Given a field that represents a member of an anonymous
517/// struct/union, build the path from that field's context to the
518/// actual member.
519///
520/// Construct the sequence of field member references we'll have to
521/// perform to get to the field in the anonymous union/struct. The
522/// list of members is built from the field outward, so traverse it
523/// backwards to go from an object in the current context to the field
524/// we found.
525///
526/// \returns The variable from which the field access should begin,
527/// for an anonymous struct/union that is not a member of another
528/// class. Otherwise, returns NULL.
529VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
530 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000531 assert(Field->getDeclContext()->isRecord() &&
532 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
533 && "Field must be stored inside an anonymous struct or union");
534
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000535 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000536 VarDecl *BaseObject = 0;
537 DeclContext *Ctx = Field->getDeclContext();
538 do {
539 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000540 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000541 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000542 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 else {
544 BaseObject = cast<VarDecl>(AnonObject);
545 break;
546 }
547 Ctx = Ctx->getParent();
548 } while (Ctx->isRecord() &&
549 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000550
551 return BaseObject;
552}
553
554Sema::OwningExprResult
555Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
556 FieldDecl *Field,
557 Expr *BaseObjectExpr,
558 SourceLocation OpLoc) {
559 llvm::SmallVector<FieldDecl *, 4> AnonFields;
560 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
561 AnonFields);
562
Douglas Gregor723d3332009-01-07 00:43:41 +0000563 // Build the expression that refers to the base object, from
564 // which we will build a sequence of member references to each
565 // of the anonymous union objects and, eventually, the field we
566 // found via name lookup.
567 bool BaseObjectIsPointer = false;
568 unsigned ExtraQuals = 0;
569 if (BaseObject) {
570 // BaseObject is an anonymous struct/union variable (and is,
571 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000572 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000573 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000574 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000575 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000576 ExtraQuals
577 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
578 } else if (BaseObjectExpr) {
579 // The caller provided the base object expression. Determine
580 // whether its a pointer and whether it adds any qualifiers to the
581 // anonymous struct/union fields we're looking into.
582 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000583 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000584 BaseObjectIsPointer = true;
585 ObjectType = ObjectPtr->getPointeeType();
586 }
587 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
588 } else {
589 // We've found a member of an anonymous struct/union that is
590 // inside a non-anonymous struct/union, so in a well-formed
591 // program our base object expression is "this".
592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
593 if (!MD->isStatic()) {
594 QualType AnonFieldType
595 = Context.getTagDeclType(
596 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
597 QualType ThisType = Context.getTagDeclType(MD->getParent());
598 if ((Context.getCanonicalType(AnonFieldType)
599 == Context.getCanonicalType(ThisType)) ||
600 IsDerivedFrom(ThisType, AnonFieldType)) {
601 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000602 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000603 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000604 BaseObjectIsPointer = true;
605 }
606 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000607 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
608 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000609 }
610 ExtraQuals = MD->getTypeQualifiers();
611 }
612
613 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
615 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000616 }
617
618 // Build the implicit member references to the field of the
619 // anonymous struct/union.
620 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000621 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000622 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
623 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
624 FI != FIEnd; ++FI) {
625 QualType MemberType = (*FI)->getType();
626 if (!(*FI)->isMutable()) {
627 unsigned combinedQualifiers
628 = MemberType.getCVRQualifiers() | ExtraQuals;
629 MemberType = MemberType.getQualifiedType(combinedQualifiers);
630 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000631 if (BaseAddrSpace != MemberType.getAddressSpace())
632 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000633 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000634 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000635 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
636 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000637 BaseObjectIsPointer = false;
638 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000639 }
640
Sebastian Redlcd883f72009-01-18 18:53:16 +0000641 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000642}
643
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000644/// ActOnDeclarationNameExpr - The parser has read some kind of name
645/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
646/// performs lookup on that name and returns an expression that refers
647/// to that name. This routine isn't directly called from the parser,
648/// because the parser doesn't know about DeclarationName. Rather,
649/// this routine is called by ActOnIdentifierExpr,
650/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
651/// which form the DeclarationName from the corresponding syntactic
652/// forms.
653///
654/// HasTrailingLParen indicates whether this identifier is used in a
655/// function call context. LookupCtx is only used for a C++
656/// qualified-id (foo::bar) to indicate the class or namespace that
657/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000658///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000659/// isAddressOfOperand means that this expression is the direct operand
660/// of an address-of operator. This matters because this is the only
661/// situation where a qualified name referencing a non-static member may
662/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000663Sema::OwningExprResult
664Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
665 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000666 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000667 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000668 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000669 if (SS && SS->isInvalid())
670 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000671
672 // C++ [temp.dep.expr]p3:
673 // An id-expression is type-dependent if it contains:
674 // -- a nested-name-specifier that contains a class-name that
675 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000676 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000677 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000678 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
679 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000680 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
681 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000682 }
683
Douglas Gregor411889e2009-02-13 23:20:09 +0000684 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
685 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000686
Sebastian Redlcd883f72009-01-18 18:53:16 +0000687 if (Lookup.isAmbiguous()) {
688 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
689 SS && SS->isSet() ? SS->getRange()
690 : SourceRange());
691 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000692 }
693
694 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000695
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000696 // If this reference is in an Objective-C method, then ivar lookup happens as
697 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000698 IdentifierInfo *II = Name.getAsIdentifierInfo();
699 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000700 // There are two cases to handle here. 1) scoped lookup could have failed,
701 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000702 // found a decl, but that decl is outside the current instance method (i.e.
703 // a global variable). In these two cases, we do a lookup for an ivar with
704 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000705 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000706 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000707 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000708 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000709 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000710 if (DiagnoseUseOfDecl(IV, Loc))
711 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000712
713 // If we're referencing an invalid decl, just return this as a silent
714 // error node. The error diagnostic was already emitted on the decl.
715 if (IV->isInvalidDecl())
716 return ExprError();
717
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000718 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
719 // If a class method attemps to use a free standing ivar, this is
720 // an error.
721 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
722 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
723 << IV->getDeclName());
724 // If a class method uses a global variable, even if an ivar with
725 // same name exists, use the global.
726 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000727 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
728 ClassDeclared != IFace)
729 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000730 // FIXME: This should use a new expr for a direct reference, don't
731 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000732 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000733 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
734 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000735 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000736 return Owned(new (Context)
737 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000738 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000739 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000740 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000741 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000742 // We should warn if a local variable hides an ivar.
743 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000744 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000745 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000746 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
747 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000748 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000749 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000750 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000751 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000752 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000753 QualType T;
754
755 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000756 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
757 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000758 else
759 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000760 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000761 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000762 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000763
Douglas Gregoraa57e862009-02-18 21:56:37 +0000764 // Determine whether this name might be a candidate for
765 // argument-dependent lookup.
766 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
767 HasTrailingLParen;
768
769 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000770 // We've seen something of the form
771 //
772 // identifier(
773 //
774 // and we did not find any entity by the name
775 // "identifier". However, this identifier is still subject to
776 // argument-dependent lookup, so keep track of the name.
777 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
778 Context.OverloadTy,
779 Loc));
780 }
781
Chris Lattner4b009652007-07-25 00:24:17 +0000782 if (D == 0) {
783 // Otherwise, this could be an implicitly declared function reference (legal
784 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000785 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000786 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000787 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000788 else {
789 // If this name wasn't predeclared and if this is not a function call,
790 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000791 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000792 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
793 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000794 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
795 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000796 return ExprError(Diag(Loc, diag::err_undeclared_use)
797 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000798 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000800 }
801 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000802
803 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
804 // Warn about constructs like:
805 // if (void *X = foo()) { ... } else { X }.
806 // In the else block, the pointer is always false.
807
808 // FIXME: In a template instantiation, we don't have scope
809 // information to check this property.
810 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
811 Scope *CheckS = S;
812 while (CheckS) {
813 if (CheckS->isWithinElse() &&
814 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
815 if (Var->getType()->isBooleanType())
816 ExprError(Diag(Loc, diag::warn_value_always_false)
817 << Var->getDeclName());
818 else
819 ExprError(Diag(Loc, diag::warn_value_always_zero)
820 << Var->getDeclName());
821 break;
822 }
823
824 // Move up one more control parent to check again.
825 CheckS = CheckS->getControlParent();
826 if (CheckS)
827 CheckS = CheckS->getParent();
828 }
829 }
830 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
831 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
832 // C99 DR 316 says that, if a function type comes from a
833 // function definition (without a prototype), that type is only
834 // used for checking compatibility. Therefore, when referencing
835 // the function, we pretend that we don't have the full function
836 // type.
837 if (DiagnoseUseOfDecl(Func, Loc))
838 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000839
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000840 QualType T = Func->getType();
841 QualType NoProtoType = T;
842 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
843 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
844 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
845 }
846 }
847
848 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
849}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000850/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000851bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000852Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
853 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
854 if (CXXRecordDecl *RD =
855 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
856 QualType DestType =
857 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000858 if (DestType->isDependentType() || From->getType()->isDependentType())
859 return false;
860 QualType FromRecordType = From->getType();
861 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000862 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000863 DestType = Context.getPointerType(DestType);
864 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000865 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000866 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
867 CheckDerivedToBaseConversion(FromRecordType,
868 DestRecordType,
869 From->getSourceRange().getBegin(),
870 From->getSourceRange()))
871 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000872 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
873 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000874 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000875 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000876}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000877
Douglas Gregore399ad42009-08-26 22:36:53 +0000878/// \brief Build a MemberExpr or CXXQualifiedMemberExpr, as appropriate.
879static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
880 const CXXScopeSpec *SS, NamedDecl *Member,
881 SourceLocation Loc, QualType Ty) {
882 if (SS && SS->isSet())
883 return new (C) CXXQualifiedMemberExpr(Base, isArrow,
884 (NestedNameSpecifier *)SS->getScopeRep(),
885 SS->getRange(),
886 Member, Loc, Ty);
887
888 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
889}
890
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000891/// \brief Complete semantic analysis for a reference to the given declaration.
892Sema::OwningExprResult
893Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
894 bool HasTrailingLParen,
895 const CXXScopeSpec *SS,
896 bool isAddressOfOperand) {
897 assert(D && "Cannot refer to a NULL declaration");
898 DeclarationName Name = D->getDeclName();
899
Sebastian Redl0c9da212009-02-03 20:19:35 +0000900 // If this is an expression of the form &Class::member, don't build an
901 // implicit member ref, because we want a pointer to the member in general,
902 // not any specific instance's member.
903 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000904 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000905 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000906 QualType DType;
907 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
908 DType = FD->getType().getNonReferenceType();
909 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
910 DType = Method->getType();
911 } else if (isa<OverloadedFunctionDecl>(D)) {
912 DType = Context.OverloadTy;
913 }
914 // Could be an inner type. That's diagnosed below, so ignore it here.
915 if (!DType.isNull()) {
916 // The pointer is type- and value-dependent if it points into something
917 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000918 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000919 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000920 }
921 }
922 }
923
Douglas Gregor723d3332009-01-07 00:43:41 +0000924 // We may have found a field within an anonymous union or struct
925 // (C++ [class.union]).
926 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
927 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
928 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000929
Douglas Gregor3257fb52008-12-22 05:46:06 +0000930 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
931 if (!MD->isStatic()) {
932 // C++ [class.mfct.nonstatic]p2:
933 // [...] if name lookup (3.4.1) resolves the name in the
934 // id-expression to a nonstatic nontype member of class X or of
935 // a base class of X, the id-expression is transformed into a
936 // class member access expression (5.2.5) using (*this) (9.3.2)
937 // as the postfix-expression to the left of the '.' operator.
938 DeclContext *Ctx = 0;
939 QualType MemberType;
940 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
941 Ctx = FD->getDeclContext();
942 MemberType = FD->getType();
943
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000944 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000945 MemberType = RefType->getPointeeType();
946 else if (!FD->isMutable()) {
947 unsigned combinedQualifiers
948 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
949 MemberType = MemberType.getQualifiedType(combinedQualifiers);
950 }
951 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
952 if (!Method->isStatic()) {
953 Ctx = Method->getParent();
954 MemberType = Method->getType();
955 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000956 } else if (FunctionTemplateDecl *FunTmpl
957 = dyn_cast<FunctionTemplateDecl>(D)) {
958 if (CXXMethodDecl *Method
959 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
960 if (!Method->isStatic()) {
961 Ctx = Method->getParent();
962 MemberType = Context.OverloadTy;
963 }
964 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000965 } else if (OverloadedFunctionDecl *Ovl
966 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000967 // FIXME: We need an abstraction for iterating over one or more function
968 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000969 for (OverloadedFunctionDecl::function_iterator
970 Func = Ovl->function_begin(),
971 FuncEnd = Ovl->function_end();
972 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000973 CXXMethodDecl *DMethod = 0;
974 if (FunctionTemplateDecl *FunTmpl
975 = dyn_cast<FunctionTemplateDecl>(*Func))
976 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
977 else
978 DMethod = dyn_cast<CXXMethodDecl>(*Func);
979
980 if (DMethod && !DMethod->isStatic()) {
981 Ctx = DMethod->getDeclContext();
982 MemberType = Context.OverloadTy;
983 break;
984 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000985 }
986 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000987
988 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000989 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
990 QualType ThisType = Context.getTagDeclType(MD->getParent());
991 if ((Context.getCanonicalType(CtxType)
992 == Context.getCanonicalType(ThisType)) ||
993 IsDerivedFrom(ThisType, CtxType)) {
994 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000995 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000996 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +0000997 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000998 if (PerformObjectMemberConversion(This, D))
999 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001000 if (DiagnoseUseOfDecl(D, Loc))
1001 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001002 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1003 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001004 }
1005 }
1006 }
1007 }
1008
Douglas Gregor8acb7272008-12-11 16:49:14 +00001009 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001010 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1011 if (MD->isStatic())
1012 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001013 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1014 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001015 }
1016
Douglas Gregor3257fb52008-12-22 05:46:06 +00001017 // Any other ways we could have found the field in a well-formed
1018 // program would have been turned into implicit member expressions
1019 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1021 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001022 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001023
Chris Lattner4b009652007-07-25 00:24:17 +00001024 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001026 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001027 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001028 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001030
Steve Naroffd6163f32008-09-05 22:11:13 +00001031 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001032 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001033 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1034 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001035 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001036 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1037 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001038 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
Douglas Gregoraa57e862009-02-18 21:56:37 +00001040 // Check whether this declaration can be used. Note that we suppress
1041 // this check when we're going to perform argument-dependent lookup
1042 // on this function name, because this might not be the function
1043 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001044 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1045 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001046 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1047 return ExprError();
1048
Steve Naroffd6163f32008-09-05 22:11:13 +00001049 // Only create DeclRefExpr's for valid Decl's.
1050 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001051 return ExprError();
1052
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001053 // If the identifier reference is inside a block, and it refers to a value
1054 // that is outside the block, create a BlockDeclRefExpr instead of a
1055 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1056 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001057 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001058 // We do not do this for things like enum constants, global variables, etc,
1059 // as they do not get snapshotted.
1060 //
1061 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001062 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001063 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001064 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001065 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001066 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001067 // This is to record that a 'const' was actually synthesize and added.
1068 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001069 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001070
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001071 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001072 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1073 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001074 }
1075 // If this reference is not in a block or if the referenced variable is
1076 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001077
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001078 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001079 bool ValueDependent = false;
1080 if (getLangOptions().CPlusPlus) {
1081 // C++ [temp.dep.expr]p3:
1082 // An id-expression is type-dependent if it contains:
1083 // - an identifier that was declared with a dependent type,
1084 if (VD->getType()->isDependentType())
1085 TypeDependent = true;
1086 // - FIXME: a template-id that is dependent,
1087 // - a conversion-function-id that specifies a dependent type,
1088 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1089 Name.getCXXNameType()->isDependentType())
1090 TypeDependent = true;
1091 // - a nested-name-specifier that contains a class-name that
1092 // names a dependent type.
1093 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001094 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001095 DC; DC = DC->getParent()) {
1096 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001097 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001098 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1099 if (Context.getTypeDeclType(Record)->isDependentType()) {
1100 TypeDependent = true;
1101 break;
1102 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001103 }
1104 }
1105 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001106
Douglas Gregora5d84612008-12-10 20:57:37 +00001107 // C++ [temp.dep.constexpr]p2:
1108 //
1109 // An identifier is value-dependent if it is:
1110 // - a name declared with a dependent type,
1111 if (TypeDependent)
1112 ValueDependent = true;
1113 // - the name of a non-type template parameter,
1114 else if (isa<NonTypeTemplateParmDecl>(VD))
1115 ValueDependent = true;
1116 // - a constant with integral or enumeration type and is
1117 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001118 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1119 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1120 Dcl->getInit()) {
1121 ValueDependent = Dcl->getInit()->isValueDependent();
1122 }
1123 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001124 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001125
Anders Carlsson4571d812009-06-24 00:10:43 +00001126 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1127 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001128}
1129
Sebastian Redlcd883f72009-01-18 18:53:16 +00001130Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1131 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001132 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001133
Chris Lattner4b009652007-07-25 00:24:17 +00001134 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001135 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001136 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1137 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1138 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001139 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001140
Chris Lattner7e637512008-01-12 08:14:25 +00001141 // Pre-defined identifiers are of type char[x], where x is the length of the
1142 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001143 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001144 if (FunctionDecl *FD = getCurFunctionDecl())
1145 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001146 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1147 Length = MD->getSynthesizedMethodSize();
1148 else {
1149 Diag(Loc, diag::ext_predef_outside_function);
1150 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1151 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1152 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001153
1154
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001155 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001156 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001157 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001158 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001159}
1160
Sebastian Redlcd883f72009-01-18 18:53:16 +00001161Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001162 llvm::SmallString<16> CharBuffer;
1163 CharBuffer.resize(Tok.getLength());
1164 const char *ThisTokBegin = &CharBuffer[0];
1165 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1168 Tok.getLocation(), PP);
1169 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001171
1172 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1173
Sebastian Redl75324932009-01-20 22:23:13 +00001174 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1175 Literal.isWide(),
1176 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001177}
1178
Sebastian Redlcd883f72009-01-18 18:53:16 +00001179Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1180 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001181 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1182 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001183 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001184 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001185 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001186 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001187 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001188
Chris Lattner4b009652007-07-25 00:24:17 +00001189 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001190 // Add padding so that NumericLiteralParser can overread by one character.
1191 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001192 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001193
Chris Lattner4b009652007-07-25 00:24:17 +00001194 // Get the spelling of the token, which eliminates trigraphs, etc.
1195 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1198 Tok.getLocation(), PP);
1199 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001200 return ExprError();
1201
Chris Lattner1de66eb2007-08-26 03:42:43 +00001202 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001203
Chris Lattner1de66eb2007-08-26 03:42:43 +00001204 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001205 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001206 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001207 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001208 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001209 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001210 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001211 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001212
1213 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1214
Ted Kremenekddedbe22007-11-29 00:56:49 +00001215 // isExact will be set by GetFloatValue().
1216 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001217 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1218 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001219
Chris Lattner1de66eb2007-08-26 03:42:43 +00001220 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001221 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001222 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001223 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001224
Neil Booth7421e9c2007-08-29 22:00:19 +00001225 // long long is a C99 feature.
1226 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001227 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001228 Diag(Tok.getLocation(), diag::ext_longlong);
1229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001231 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001232
Chris Lattner4b009652007-07-25 00:24:17 +00001233 if (Literal.GetIntegerValue(ResultVal)) {
1234 // If this value didn't fit into uintmax_t, warn and force to ull.
1235 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001236 Ty = Context.UnsignedLongLongTy;
1237 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001238 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001239 } else {
1240 // If this value fits into a ULL, try to figure out what else it fits into
1241 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001242
Chris Lattner4b009652007-07-25 00:24:17 +00001243 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1244 // be an unsigned int.
1245 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1246
1247 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001248 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001249 if (!Literal.isLong && !Literal.isLongLong) {
1250 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001251 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001252
Chris Lattner4b009652007-07-25 00:24:17 +00001253 // Does it fit in a unsigned int?
1254 if (ResultVal.isIntN(IntSize)) {
1255 // Does it fit in a signed int?
1256 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001257 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001258 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001259 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001260 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001261 }
Chris Lattner4b009652007-07-25 00:24:17 +00001262 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001265 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001266 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001267
Chris Lattner4b009652007-07-25 00:24:17 +00001268 // Does it fit in a unsigned long?
1269 if (ResultVal.isIntN(LongSize)) {
1270 // Does it fit in a signed long?
1271 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001272 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001273 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001274 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001275 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001276 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001277 }
1278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001280 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001281 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001282
Chris Lattner4b009652007-07-25 00:24:17 +00001283 // Does it fit in a unsigned long long?
1284 if (ResultVal.isIntN(LongLongSize)) {
1285 // Does it fit in a signed long long?
1286 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001287 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001288 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001289 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001290 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001291 }
1292 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001293
Chris Lattner4b009652007-07-25 00:24:17 +00001294 // If we still couldn't decide a type, we probably have something that
1295 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001296 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001297 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001298 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001299 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001300 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001301
Chris Lattnere4068872008-05-09 05:59:00 +00001302 if (ResultVal.getBitWidth() != Width)
1303 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001304 }
Sebastian Redl75324932009-01-20 22:23:13 +00001305 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001306 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001307
Chris Lattner1de66eb2007-08-26 03:42:43 +00001308 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1309 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001310 Res = new (Context) ImaginaryLiteral(Res,
1311 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001312
1313 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001314}
1315
Sebastian Redlcd883f72009-01-18 18:53:16 +00001316Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1317 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001318 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001319 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001320 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001321}
1322
1323/// The UsualUnaryConversions() function is *not* called by this routine.
1324/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001325bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001326 SourceLocation OpLoc,
1327 const SourceRange &ExprRange,
1328 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001329 if (exprType->isDependentType())
1330 return false;
1331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001333 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001334 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001335 if (isSizeof)
1336 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1337 return false;
1338 }
1339
Chris Lattner95933c12009-04-24 00:30:45 +00001340 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001341 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001342 Diag(OpLoc, diag::ext_sizeof_void_type)
1343 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001344 return false;
1345 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001346
Chris Lattner95933c12009-04-24 00:30:45 +00001347 if (RequireCompleteType(OpLoc, exprType,
1348 isSizeof ? diag::err_sizeof_incomplete_type :
1349 diag::err_alignof_incomplete_type,
1350 ExprRange))
1351 return true;
1352
1353 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001354 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001355 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001356 << exprType << isSizeof << ExprRange;
1357 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001358 }
1359
Chris Lattner95933c12009-04-24 00:30:45 +00001360 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001361}
1362
Chris Lattner8d9f7962009-01-24 20:17:12 +00001363bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1364 const SourceRange &ExprRange) {
1365 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001366
Chris Lattner8d9f7962009-01-24 20:17:12 +00001367 // alignof decl is always ok.
1368 if (isa<DeclRefExpr>(E))
1369 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001370
1371 // Cannot know anything else if the expression is dependent.
1372 if (E->isTypeDependent())
1373 return false;
1374
Douglas Gregor531434b2009-05-02 02:18:30 +00001375 if (E->getBitField()) {
1376 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1377 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001378 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001379
1380 // Alignment of a field access is always okay, so long as it isn't a
1381 // bit-field.
1382 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001383 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001384 return false;
1385
Chris Lattner8d9f7962009-01-24 20:17:12 +00001386 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1387}
1388
Douglas Gregor396f1142009-03-13 21:01:28 +00001389/// \brief Build a sizeof or alignof expression given a type operand.
1390Action::OwningExprResult
1391Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1392 bool isSizeOf, SourceRange R) {
1393 if (T.isNull())
1394 return ExprError();
1395
1396 if (!T->isDependentType() &&
1397 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1398 return ExprError();
1399
1400 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1401 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1402 Context.getSizeType(), OpLoc,
1403 R.getEnd()));
1404}
1405
1406/// \brief Build a sizeof or alignof expression given an expression
1407/// operand.
1408Action::OwningExprResult
1409Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1410 bool isSizeOf, SourceRange R) {
1411 // Verify that the operand is valid.
1412 bool isInvalid = false;
1413 if (E->isTypeDependent()) {
1414 // Delay type-checking for type-dependent expressions.
1415 } else if (!isSizeOf) {
1416 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001417 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001418 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1419 isInvalid = true;
1420 } else {
1421 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1422 }
1423
1424 if (isInvalid)
1425 return ExprError();
1426
1427 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1428 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1429 Context.getSizeType(), OpLoc,
1430 R.getEnd()));
1431}
1432
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001433/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1434/// the same for @c alignof and @c __alignof
1435/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001436Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001437Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1438 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001440 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001441
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001442 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001443 // FIXME: Preserve type source info.
1444 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001445 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1446 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001447
Douglas Gregor396f1142009-03-13 21:01:28 +00001448 // Get the end location.
1449 Expr *ArgEx = (Expr *)TyOrEx;
1450 Action::OwningExprResult Result
1451 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1452
1453 if (Result.isInvalid())
1454 DeleteExpr(ArgEx);
1455
1456 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001457}
1458
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001459QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001460 if (V->isTypeDependent())
1461 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001462
Chris Lattnera16e42d2007-08-26 05:39:26 +00001463 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001464 if (const ComplexType *CT = V->getType()->getAsComplexType())
1465 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001466
1467 // Otherwise they pass through real integer and floating point types here.
1468 if (V->getType()->isArithmeticType())
1469 return V->getType();
1470
1471 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001472 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1473 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001474 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001475}
1476
1477
Chris Lattner4b009652007-07-25 00:24:17 +00001478
Sebastian Redl8b769972009-01-19 00:08:26 +00001479Action::OwningExprResult
1480Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1481 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001482 // Since this might be a postfix expression, get rid of ParenListExprs.
1483 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001484 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001485
Chris Lattner4b009652007-07-25 00:24:17 +00001486 UnaryOperator::Opcode Opc;
1487 switch (Kind) {
1488 default: assert(0 && "Unknown unary op!");
1489 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1490 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1491 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001492
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001493 if (getLangOptions().CPlusPlus &&
1494 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1495 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001496 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001497 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1498
1499 // C++ [over.inc]p1:
1500 //
1501 // [...] If the function is a member function with one
1502 // parameter (which shall be of type int) or a non-member
1503 // function with two parameters (the second of which shall be
1504 // of type int), it defines the postfix increment operator ++
1505 // for objects of that type. When the postfix increment is
1506 // called as a result of using the ++ operator, the int
1507 // argument will have value zero.
1508 Expr *Args[2] = {
1509 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001510 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1511 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001512 };
1513
1514 // Build the candidate set for overloading
1515 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001516 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001517
1518 // Perform overload resolution.
1519 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001520 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001521 case OR_Success: {
1522 // We found a built-in operator or an overloaded operator.
1523 FunctionDecl *FnDecl = Best->Function;
1524
1525 if (FnDecl) {
1526 // We matched an overloaded operator. Build a call to that
1527 // operator.
1528
1529 // Convert the arguments.
1530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1531 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001532 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001533 } else {
1534 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001535 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001536 FnDecl->getParamDecl(0)->getType(),
1537 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001538 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001539 }
1540
1541 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001543 = FnDecl->getType()->getAsFunctionType()->getResultType();
1544 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001545
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001546 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001547 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001548 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001549 UsualUnaryConversions(FnExpr);
1550
Sebastian Redl8b769972009-01-19 00:08:26 +00001551 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001552 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001553 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1554 Args, 2, ResultTy,
1555 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001556 } else {
1557 // We matched a built-in operator. Convert the arguments, then
1558 // break out so that we will build the appropriate built-in
1559 // operator node.
1560 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1561 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001562 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001563
1564 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001566 }
1567
1568 case OR_No_Viable_Function:
1569 // No viable function; fall through to handling this as a
1570 // built-in operator, which will produce an error message for us.
1571 break;
1572
1573 case OR_Ambiguous:
1574 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1575 << UnaryOperator::getOpcodeStr(Opc)
1576 << Arg->getSourceRange();
1577 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001578 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001579
1580 case OR_Deleted:
1581 Diag(OpLoc, diag::err_ovl_deleted_oper)
1582 << Best->Function->isDeleted()
1583 << UnaryOperator::getOpcodeStr(Opc)
1584 << Arg->getSourceRange();
1585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1586 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001587 }
1588
1589 // Either we found no viable overloaded operator or we matched a
1590 // built-in operator. In either case, fall through to trying to
1591 // build a built-in operation.
1592 }
1593
Eli Friedman94d30952009-07-22 23:24:42 +00001594 Input.release();
1595 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001596 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001597}
1598
Sebastian Redl8b769972009-01-19 00:08:26 +00001599Action::OwningExprResult
1600Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1601 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001602 // Since this might be a postfix expression, get rid of ParenListExprs.
1603 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1604
Sebastian Redl8b769972009-01-19 00:08:26 +00001605 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1606 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001607
Douglas Gregor80723c52008-11-19 17:17:41 +00001608 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001609 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1610 Base.release();
1611 Idx.release();
1612 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1613 Context.DependentTy, RLoc));
1614 }
1615
1616 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001617 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001618 LHSExp->getType()->isEnumeralType() ||
1619 RHSExp->getType()->isRecordType() ||
1620 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001621 // Add the appropriate overloaded operators (C++ [over.match.oper])
1622 // to the candidate set.
1623 OverloadCandidateSet CandidateSet;
1624 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001625 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1626 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001627
Douglas Gregor80723c52008-11-19 17:17:41 +00001628 // Perform overload resolution.
1629 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001630 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001631 case OR_Success: {
1632 // We found a built-in operator or an overloaded operator.
1633 FunctionDecl *FnDecl = Best->Function;
1634
1635 if (FnDecl) {
1636 // We matched an overloaded operator. Build a call to that
1637 // operator.
1638
1639 // Convert the arguments.
1640 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1641 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1642 PerformCopyInitialization(RHSExp,
1643 FnDecl->getParamDecl(0)->getType(),
1644 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001645 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001646 } else {
1647 // Convert the arguments.
1648 if (PerformCopyInitialization(LHSExp,
1649 FnDecl->getParamDecl(0)->getType(),
1650 "passing") ||
1651 PerformCopyInitialization(RHSExp,
1652 FnDecl->getParamDecl(1)->getType(),
1653 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001654 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001655 }
1656
1657 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001658 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001659 = FnDecl->getType()->getAsFunctionType()->getResultType();
1660 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001661
Douglas Gregor80723c52008-11-19 17:17:41 +00001662 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001663 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1664 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001665 UsualUnaryConversions(FnExpr);
1666
Sebastian Redl8b769972009-01-19 00:08:26 +00001667 Base.release();
1668 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001669 Args[0] = LHSExp;
1670 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001671 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1672 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001673 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001674 } else {
1675 // We matched a built-in operator. Convert the arguments, then
1676 // break out so that we will build the appropriate built-in
1677 // operator node.
1678 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1679 "passing") ||
1680 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1681 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001682 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001683
1684 break;
1685 }
1686 }
1687
1688 case OR_No_Viable_Function:
1689 // No viable function; fall through to handling this as a
1690 // built-in operator, which will produce an error message for us.
1691 break;
1692
1693 case OR_Ambiguous:
1694 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1695 << "[]"
1696 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1697 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001698 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001699
1700 case OR_Deleted:
1701 Diag(LLoc, diag::err_ovl_deleted_oper)
1702 << Best->Function->isDeleted()
1703 << "[]"
1704 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1706 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001707 }
1708
1709 // Either we found no viable overloaded operator or we matched a
1710 // built-in operator. In either case, fall through to trying to
1711 // build a built-in operation.
1712 }
1713
Chris Lattner4b009652007-07-25 00:24:17 +00001714 // Perform default conversions.
1715 DefaultFunctionArrayConversion(LHSExp);
1716 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001717
Chris Lattner4b009652007-07-25 00:24:17 +00001718 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1719
1720 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001721 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001722 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001723 // and index from the expression types.
1724 Expr *BaseExpr, *IndexExpr;
1725 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001726 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1727 BaseExpr = LHSExp;
1728 IndexExpr = RHSExp;
1729 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001730 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001731 BaseExpr = LHSExp;
1732 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001733 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001734 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001735 // Handle the uncommon case of "123[Ptr]".
1736 BaseExpr = RHSExp;
1737 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001738 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001739 } else if (const ObjCObjectPointerType *PTy =
1740 LHSTy->getAsObjCObjectPointerType()) {
1741 BaseExpr = LHSExp;
1742 IndexExpr = RHSExp;
1743 ResultType = PTy->getPointeeType();
1744 } else if (const ObjCObjectPointerType *PTy =
1745 RHSTy->getAsObjCObjectPointerType()) {
1746 // Handle the uncommon case of "123[Ptr]".
1747 BaseExpr = RHSExp;
1748 IndexExpr = LHSExp;
1749 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001750 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1751 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001752 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001753
Chris Lattner4b009652007-07-25 00:24:17 +00001754 // FIXME: need to deal with const...
1755 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001756 } else if (LHSTy->isArrayType()) {
1757 // If we see an array that wasn't promoted by
1758 // DefaultFunctionArrayConversion, it must be an array that
1759 // wasn't promoted because of the C90 rule that doesn't
1760 // allow promoting non-lvalue arrays. Warn, then
1761 // force the promotion here.
1762 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1763 LHSExp->getSourceRange();
1764 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1765 LHSTy = LHSExp->getType();
1766
1767 BaseExpr = LHSExp;
1768 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001769 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001770 } else if (RHSTy->isArrayType()) {
1771 // Same as previous, except for 123[f().a] case
1772 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1773 RHSExp->getSourceRange();
1774 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1775 RHSTy = RHSExp->getType();
1776
1777 BaseExpr = RHSExp;
1778 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001779 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001780 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001781 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1782 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 }
Chris Lattner4b009652007-07-25 00:24:17 +00001784 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001785 if (!(IndexExpr->getType()->isIntegerType() &&
1786 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001787 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1788 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001789
Douglas Gregor05e28f62009-03-24 19:52:54 +00001790 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1791 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1792 // type. Note that Functions are not objects, and that (in C99 parlance)
1793 // incomplete types are not object types.
1794 if (ResultType->isFunctionType()) {
1795 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1796 << ResultType << BaseExpr->getSourceRange();
1797 return ExprError();
1798 }
Chris Lattner95933c12009-04-24 00:30:45 +00001799
Douglas Gregor05e28f62009-03-24 19:52:54 +00001800 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001801 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001802 BaseExpr->getSourceRange()))
1803 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001804
1805 // Diagnose bad cases where we step over interface counts.
1806 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1807 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1808 << ResultType << BaseExpr->getSourceRange();
1809 return ExprError();
1810 }
1811
Sebastian Redl8b769972009-01-19 00:08:26 +00001812 Base.release();
1813 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001814 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001815 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001816}
1817
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001818QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001819CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001820 const IdentifierInfo *CompName,
1821 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001822 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001823
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001824 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001825 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001826
Mike Stump9afab102009-02-19 03:04:26 +00001827 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001828 // special names that indicate a subset of exactly half the elements are
1829 // to be selected.
1830 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001831
Nate Begeman1486b502009-01-18 01:47:54 +00001832 // This flag determines whether or not CompName has an 's' char prefix,
1833 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001834 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001835
1836 // Check that we've found one of the special components, or that the component
1837 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001838 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001839 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1840 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001841 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001842 do
1843 compStr++;
1844 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001845 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001846 do
1847 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001848 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001849 }
Nate Begeman1486b502009-01-18 01:47:54 +00001850
Mike Stump9afab102009-02-19 03:04:26 +00001851 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001852 // We didn't get to the end of the string. This means the component names
1853 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001854 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1855 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001856 return QualType();
1857 }
Mike Stump9afab102009-02-19 03:04:26 +00001858
Nate Begeman1486b502009-01-18 01:47:54 +00001859 // Ensure no component accessor exceeds the width of the vector type it
1860 // operates on.
1861 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001862 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001863
1864 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001865 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001866
1867 while (*compStr) {
1868 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1869 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1870 << baseType << SourceRange(CompLoc);
1871 return QualType();
1872 }
1873 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001874 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001875
Nate Begeman1486b502009-01-18 01:47:54 +00001876 // If this is a halving swizzle, verify that the base type has an even
1877 // number of elements.
1878 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001879 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001880 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001881 return QualType();
1882 }
Mike Stump9afab102009-02-19 03:04:26 +00001883
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001884 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001885 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001886 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001887 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001888 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001889 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001890 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001891 if (HexSwizzle)
1892 CompSize--;
1893
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001894 if (CompSize == 1)
1895 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001896
Nate Begemanaf6ed502008-04-18 23:10:10 +00001897 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001898 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001899 // diagostics look bad. We want extended vector types to appear built-in.
1900 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1901 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1902 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001903 }
1904 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001905}
1906
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001907static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001908 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001909 const Selector &Sel,
1910 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001911
Anders Carlsson9935ab92009-08-26 18:25:21 +00001912 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001913 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001914 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001915 return OMD;
1916
1917 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1918 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001919 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1920 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001921 return D;
1922 }
1923 return 0;
1924}
1925
Steve Naroffc75c1a82009-06-17 22:40:22 +00001926static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001927 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001928 const Selector &Sel,
1929 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001930 // Check protocols on qualified interfaces.
1931 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001932 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001933 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001934 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001935 GDecl = PD;
1936 break;
1937 }
1938 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001939 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001940 GDecl = OMD;
1941 break;
1942 }
1943 }
1944 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001945 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001946 E = QIdTy->qual_end(); I != E; ++I) {
1947 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001948 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001949 if (GDecl)
1950 return GDecl;
1951 }
1952 }
1953 return GDecl;
1954}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001955
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001956/// FindMethodInNestedImplementations - Look up a method in current and
1957/// all base class implementations.
1958///
1959ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1960 const ObjCInterfaceDecl *IFace,
1961 const Selector &Sel) {
1962 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001963 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001964 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001965
1966 if (!Method && IFace->getSuperClass())
1967 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1968 return Method;
1969}
Douglas Gregore399ad42009-08-26 22:36:53 +00001970
Anders Carlsson9935ab92009-08-26 18:25:21 +00001971Action::OwningExprResult
1972Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001973 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001974 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001975 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001976 if (SS && SS->isInvalid())
1977 return ExprError();
1978
Nate Begemane85f43d2009-08-10 23:49:36 +00001979 // Since this might be a postfix expression, get rid of ParenListExprs.
1980 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1981
Anders Carlssonc154a722009-05-01 19:30:39 +00001982 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001983 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001984
Steve Naroff137e11d2007-12-16 21:42:28 +00001985 // Perform default conversions.
1986 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001987
Steve Naroff2cb66382007-07-26 03:11:44 +00001988 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001989 // If this is an Objective-C pseudo-builtin and a definition is provided then
1990 // use that.
1991 if (BaseType->isObjCIdType()) {
1992 // We have an 'id' type. Rather than fall through, we check if this
1993 // is a reference to 'isa'.
1994 if (BaseType != Context.ObjCIdRedefinitionType) {
1995 BaseType = Context.ObjCIdRedefinitionType;
1996 ImpCastExprToType(BaseExpr, BaseType);
1997 }
1998 } else if (BaseType->isObjCClassType() &&
1999 BaseType != Context.ObjCClassRedefinitionType) {
2000 BaseType = Context.ObjCClassRedefinitionType;
2001 ImpCastExprToType(BaseExpr, BaseType);
2002 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002003 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002004
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002005 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2006 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002007 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002008 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002009 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2010 BaseExpr, true,
2011 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002012 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002013 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002014 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002015 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002016 else if (BaseType->isObjCObjectPointerType())
2017 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002018 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002019 return ExprError(Diag(MemberLoc,
2020 diag::err_typecheck_member_reference_arrow)
2021 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002022 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002023 if (BaseType->isDependentType()) {
2024 // Require that the base type isn't a pointer type
2025 // (so we'll report an error for)
2026 // T* t;
2027 // t.f;
2028 //
2029 // In Obj-C++, however, the above expression is valid, since it could be
2030 // accessing the 'f' property if T is an Obj-C interface. The extra check
2031 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002032 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002033
2034 if (!PT || (getLangOptions().ObjC1 &&
2035 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002036 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2037 BaseExpr, false,
2038 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002039 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002040 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002041 }
Chris Lattner4b009652007-07-25 00:24:17 +00002042 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002043
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002044 // Handle field access to simple records. This also handles access to fields
2045 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002046 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002047 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002048 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002049 diag::err_typecheck_incomplete_tag,
2050 BaseExpr->getSourceRange()))
2051 return ExprError();
2052
Douglas Gregorda61ad22009-08-06 03:17:00 +00002053 DeclContext *DC = RDecl;
2054 if (SS && SS->isSet()) {
2055 // If the member name was a qualified-id, look into the
2056 // nested-name-specifier.
2057 DC = computeDeclContext(*SS, false);
2058
2059 // FIXME: If DC is not computable, we should build a
2060 // CXXUnresolvedMemberExpr.
2061 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2062 }
2063
Steve Naroff2cb66382007-07-26 03:11:44 +00002064 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002065 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002066 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002067
Douglas Gregor12431cb2009-08-06 05:28:30 +00002068 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002069 QualType BaseTypeCanon
2070 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2071 QualType MemberTypeCanon
2072 = Context.getCanonicalType(
2073 Context.getTypeDeclType(
2074 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2075
2076 if (BaseTypeCanon != MemberTypeCanon &&
2077 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2078 return ExprError(Diag(SS->getBeginLoc(),
2079 diag::err_not_direct_base_or_virtual)
2080 << MemberTypeCanon << BaseTypeCanon);
2081 }
2082
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002083 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002084 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002085 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002086 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002087 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2088 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002089 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002090 }
2091
2092 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002093
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002094 // If the decl being referenced had an error, return an error for this
2095 // sub-expr without emitting another error, in order to avoid cascading
2096 // error cases.
2097 if (MemberDecl->isInvalidDecl())
2098 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002099
Douglas Gregoraa57e862009-02-18 21:56:37 +00002100 // Check the use of this field
2101 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2102 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002103
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002104 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002105 // We may have found a field within an anonymous union or struct
2106 // (C++ [class.union]).
2107 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002108 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002109 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002110
Douglas Gregor82d44772008-12-20 23:49:58 +00002111 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002112 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002113 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002114 MemberType = Ref->getPointeeType();
2115 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002116 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002117 unsigned combinedQualifiers =
2118 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002119 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002120 combinedQualifiers &= ~QualType::Const;
2121 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002122 if (BaseAddrSpace != MemberType.getAddressSpace())
2123 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002124 }
Eli Friedman76b49832008-02-06 22:48:16 +00002125
Douglas Gregorcad27f62009-06-22 23:06:13 +00002126 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002127 if (PerformObjectMemberConversion(BaseExpr, FD))
2128 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002129 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2130 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002131 }
2132
Douglas Gregorcad27f62009-06-22 23:06:13 +00002133 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2134 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002135 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2136 Var, MemberLoc,
2137 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002138 }
2139 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2140 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002141 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2142 MemberFn, MemberLoc,
2143 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002144 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002145 if (FunctionTemplateDecl *FunTmpl
2146 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2147 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002148 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2149 FunTmpl, MemberLoc,
2150 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002151 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002152 if (OverloadedFunctionDecl *Ovl
2153 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregore399ad42009-08-26 22:36:53 +00002154 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2155 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002156 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2157 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002158 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2159 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002160 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002161 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002162 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002163 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002164
Douglas Gregor82d44772008-12-20 23:49:58 +00002165 // We found a declaration kind that we didn't expect. This is a
2166 // generic error message that tells the user that she can't refer
2167 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002168 return ExprError(Diag(MemberLoc,
2169 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002170 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002171 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002172
Steve Naroff329ec222009-07-10 23:34:53 +00002173 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002174 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002175 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002176 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2177 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002178 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2179 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2180 ObjCMethodDecl *Getter;
2181 // FIXME: need to also look locally in the implementation.
2182 if ((Getter = IFace->lookupClassMethod(Sel))) {
2183 // Check the use of this method.
2184 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2185 return ExprError();
2186 }
2187 // If we found a getter then this may be a valid dot-reference, we
2188 // will look for the matching setter, in case it is needed.
2189 Selector SetterSel =
2190 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002191 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002192 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2193 if (!Setter) {
2194 // If this reference is in an @implementation, also check for 'private'
2195 // methods.
2196 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2197 }
2198 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002199 if (!Setter)
2200 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002201
2202 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2203 return ExprError();
2204
2205 if (Getter || Setter) {
2206 QualType PType;
2207
2208 if (Getter)
2209 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002210 else
2211 // Get the expression type from Setter's incoming parameter.
2212 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002213 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002214 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002215 Setter, MemberLoc, BaseExpr));
2216 }
2217 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002218 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002219 }
2220 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002221 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2222 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002223 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2224 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2225 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2226 const ObjCInterfaceType *IFaceT =
2227 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002228 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002229 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2230
Steve Naroff4e743962009-07-16 00:25:06 +00002231 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2232 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002233 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002234
2235 if (IV) {
2236 // If the decl being referenced had an error, return an error for this
2237 // sub-expr without emitting another error, in order to avoid cascading
2238 // error cases.
2239 if (IV->isInvalidDecl())
2240 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002241
Steve Naroff4e743962009-07-16 00:25:06 +00002242 // Check whether we can reference this field.
2243 if (DiagnoseUseOfDecl(IV, MemberLoc))
2244 return ExprError();
2245 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2246 IV->getAccessControl() != ObjCIvarDecl::Package) {
2247 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2248 if (ObjCMethodDecl *MD = getCurMethodDecl())
2249 ClassOfMethodDecl = MD->getClassInterface();
2250 else if (ObjCImpDecl && getCurFunctionDecl()) {
2251 // Case of a c-function declared inside an objc implementation.
2252 // FIXME: For a c-style function nested inside an objc implementation
2253 // class, there is no implementation context available, so we pass
2254 // down the context as argument to this routine. Ideally, this context
2255 // need be passed down in the AST node and somehow calculated from the
2256 // AST for a function decl.
2257 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2258 if (ObjCImplementationDecl *IMPD =
2259 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2260 ClassOfMethodDecl = IMPD->getClassInterface();
2261 else if (ObjCCategoryImplDecl* CatImplClass =
2262 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2263 ClassOfMethodDecl = CatImplClass->getClassInterface();
2264 }
2265
2266 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2267 if (ClassDeclared != IDecl ||
2268 ClassOfMethodDecl != ClassDeclared)
2269 Diag(MemberLoc, diag::error_private_ivar_access)
2270 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002271 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2272 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002273 Diag(MemberLoc, diag::error_protected_ivar_access)
2274 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002275 }
Steve Naroff4e743962009-07-16 00:25:06 +00002276
2277 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2278 MemberLoc, BaseExpr,
2279 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002280 }
Steve Naroff4e743962009-07-16 00:25:06 +00002281 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002282 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002283 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002284 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002285 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002286 // Handle properties on 'id' and qualified "id".
2287 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2288 BaseType->isObjCQualifiedIdType())) {
2289 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002290 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002291
Steve Naroff329ec222009-07-10 23:34:53 +00002292 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002293 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002294 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2295 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2296 // Check the use of this declaration
2297 if (DiagnoseUseOfDecl(PD, MemberLoc))
2298 return ExprError();
2299
2300 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2301 MemberLoc, BaseExpr));
2302 }
2303 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2304 // Check the use of this method.
2305 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2306 return ExprError();
2307
2308 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2309 OMD->getResultType(),
2310 OMD, OpLoc, MemberLoc,
2311 NULL, 0));
2312 }
2313 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002314
Steve Naroff329ec222009-07-10 23:34:53 +00002315 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002316 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002317 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002318 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2319 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002320 const ObjCObjectPointerType *OPT;
2321 if (OpKind == tok::period &&
2322 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2323 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2324 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002325 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002326
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002327 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002328 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002329 // Check whether we can reference this property.
2330 if (DiagnoseUseOfDecl(PD, MemberLoc))
2331 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002332 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002333 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002334 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002335 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2336 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002337 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002338 MemberLoc, BaseExpr));
2339 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002340 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002341 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2342 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002343 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002344 // Check whether we can reference this property.
2345 if (DiagnoseUseOfDecl(PD, MemberLoc))
2346 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002347
Steve Naroff774e4152009-01-21 00:14:39 +00002348 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002349 MemberLoc, BaseExpr));
2350 }
Steve Naroff329ec222009-07-10 23:34:53 +00002351 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2352 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002353 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002354 // Check whether we can reference this property.
2355 if (DiagnoseUseOfDecl(PD, MemberLoc))
2356 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002357
Steve Naroff329ec222009-07-10 23:34:53 +00002358 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2359 MemberLoc, BaseExpr));
2360 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002361 // If that failed, look for an "implicit" property by seeing if the nullary
2362 // selector is implemented.
2363
2364 // FIXME: The logic for looking up nullary and unary selectors should be
2365 // shared with the code in ActOnInstanceMessage.
2366
Anders Carlsson9935ab92009-08-26 18:25:21 +00002367 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002368 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002369
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002370 // If this reference is in an @implementation, check for 'private' methods.
2371 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002372 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002373
Steve Naroff04151f32008-10-22 19:16:27 +00002374 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002375 if (!Getter)
2376 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002377 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002378 // Check if we can reference this property.
2379 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2380 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002381 }
2382 // If we found a getter then this may be a valid dot-reference, we
2383 // will look for the matching setter, in case it is needed.
2384 Selector SetterSel =
2385 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002386 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002387 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002388 if (!Setter) {
2389 // If this reference is in an @implementation, also check for 'private'
2390 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002391 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002392 }
2393 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002394 if (!Setter)
2395 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002396
Steve Naroffdede0c92009-03-11 13:48:17 +00002397 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2398 return ExprError();
2399
2400 if (Getter || Setter) {
2401 QualType PType;
2402
2403 if (Getter)
2404 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002405 else
2406 // Get the expression type from Setter's incoming parameter.
2407 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002408 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002409 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002410 Setter, MemberLoc, BaseExpr));
2411 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002412 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002413 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002414 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002415
Steve Naroff29d293b2009-07-24 17:54:45 +00002416 // Handle the following exceptional case (*Obj).isa.
2417 if (OpKind == tok::period &&
2418 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002419 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002420 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2421 Context.getObjCIdType()));
2422
Chris Lattnera57cf472008-07-21 04:28:12 +00002423 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002424 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002425 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002426 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2427 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002428 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002429 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002430 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002431 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002432
Douglas Gregor762da552009-03-27 06:00:30 +00002433 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2434 << BaseType << BaseExpr->getSourceRange();
2435
2436 // If the user is trying to apply -> or . to a function or function
2437 // pointer, it's probably because they forgot parentheses to call
2438 // the function. Suggest the addition of those parentheses.
2439 if (BaseType == Context.OverloadTy ||
2440 BaseType->isFunctionType() ||
2441 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002442 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002443 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2444 Diag(Loc, diag::note_member_reference_needs_call)
2445 << CodeModificationHint::CreateInsertion(Loc, "()");
2446 }
2447
2448 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002449}
2450
Anders Carlsson9935ab92009-08-26 18:25:21 +00002451Action::OwningExprResult
2452Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2453 tok::TokenKind OpKind, SourceLocation MemberLoc,
2454 IdentifierInfo &Member,
2455 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2456 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2457 DeclarationName(&Member), ObjCImpDecl, SS);
2458}
2459
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002460Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2461 FunctionDecl *FD,
2462 ParmVarDecl *Param) {
2463 if (Param->hasUnparsedDefaultArg()) {
2464 Diag (CallLoc,
2465 diag::err_use_of_default_argument_to_function_declared_later) <<
2466 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2467 Diag(UnparsedDefaultArgLocs[Param],
2468 diag::note_default_argument_declared_here);
2469 } else {
2470 if (Param->hasUninstantiatedDefaultArg()) {
2471 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2472
2473 // Instantiate the expression.
2474 const TemplateArgumentList &ArgList = getTemplateInstantiationArgs(FD);
2475
2476 // FIXME: We should really make a new InstantiatingTemplate ctor
2477 // that has a better message - right now we're just piggy-backing
2478 // off the "default template argument" error message.
2479 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
2480 ArgList.getFlatArgumentList(),
2481 ArgList.flat_size());
2482
John McCall0ba26ee2009-08-25 22:02:44 +00002483 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002484 if (Result.isInvalid())
2485 return ExprError();
2486
2487 if (SetParamDefaultArgument(Param, move(Result),
2488 /*FIXME:EqualLoc*/
2489 UninstExpr->getSourceRange().getBegin()))
2490 return ExprError();
2491 }
2492
2493 Expr *DefaultExpr = Param->getDefaultArg();
2494
2495 // If the default expression creates temporaries, we need to
2496 // push them to the current stack of expression temporaries so they'll
2497 // be properly destroyed.
2498 if (CXXExprWithTemporaries *E
2499 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2500 assert(!E->shouldDestroyTemporaries() &&
2501 "Can't destroy temporaries in a default argument expr!");
2502 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2503 ExprTemporaries.push_back(E->getTemporary(I));
2504 }
2505 }
2506
2507 // We already type-checked the argument, so we know it works.
2508 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2509}
2510
Douglas Gregor3257fb52008-12-22 05:46:06 +00002511/// ConvertArgumentsForCall - Converts the arguments specified in
2512/// Args/NumArgs to the parameter types of the function FDecl with
2513/// function prototype Proto. Call is the call expression itself, and
2514/// Fn is the function expression. For a C++ member function, this
2515/// routine does not attempt to convert the object argument. Returns
2516/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002517bool
2518Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002519 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002520 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002521 Expr **Args, unsigned NumArgs,
2522 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002523 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002524 // assignment, to the types of the corresponding parameter, ...
2525 unsigned NumArgsInProto = Proto->getNumArgs();
2526 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002527 bool Invalid = false;
2528
Douglas Gregor3257fb52008-12-22 05:46:06 +00002529 // If too few arguments are available (and we don't have default
2530 // arguments for the remaining parameters), don't make the call.
2531 if (NumArgs < NumArgsInProto) {
2532 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2533 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2534 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2535 // Use default arguments for missing arguments
2536 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002537 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002538 }
2539
2540 // If too many are passed and not variadic, error on the extras and drop
2541 // them.
2542 if (NumArgs > NumArgsInProto) {
2543 if (!Proto->isVariadic()) {
2544 Diag(Args[NumArgsInProto]->getLocStart(),
2545 diag::err_typecheck_call_too_many_args)
2546 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2547 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2548 Args[NumArgs-1]->getLocEnd());
2549 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002550 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002551 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002552 }
2553 NumArgsToCheck = NumArgsInProto;
2554 }
Mike Stump9afab102009-02-19 03:04:26 +00002555
Douglas Gregor3257fb52008-12-22 05:46:06 +00002556 // Continue to check argument types (even if we have too few/many args).
2557 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2558 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002559
Douglas Gregor3257fb52008-12-22 05:46:06 +00002560 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002561 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002562 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002563
Eli Friedman83dec9e2009-03-22 22:00:50 +00002564 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2565 ProtoArgType,
2566 diag::err_call_incomplete_argument,
2567 Arg->getSourceRange()))
2568 return true;
2569
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002570 // Pass the argument.
2571 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2572 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002573 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002574 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002575
2576 OwningExprResult ArgExpr =
2577 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2578 FDecl, Param);
2579 if (ArgExpr.isInvalid())
2580 return true;
2581
2582 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002583 }
2584
Douglas Gregor3257fb52008-12-22 05:46:06 +00002585 Call->setArg(i, Arg);
2586 }
Mike Stump9afab102009-02-19 03:04:26 +00002587
Douglas Gregor3257fb52008-12-22 05:46:06 +00002588 // If this is a variadic call, handle args passed through "...".
2589 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002590 VariadicCallType CallType = VariadicFunction;
2591 if (Fn->getType()->isBlockPointerType())
2592 CallType = VariadicBlock; // Block
2593 else if (isa<MemberExpr>(Fn))
2594 CallType = VariadicMethod;
2595
Douglas Gregor3257fb52008-12-22 05:46:06 +00002596 // Promote the arguments (C99 6.5.2.2p7).
2597 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2598 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002599 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002600 Call->setArg(i, Arg);
2601 }
2602 }
2603
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002604 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002605}
2606
Steve Naroff87d58b42007-09-16 03:34:24 +00002607/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002608/// This provides the location of the left/right parens and a list of comma
2609/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002610Action::OwningExprResult
2611Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2612 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002613 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002614 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002615
2616 // Since this might be a postfix expression, get rid of ParenListExprs.
2617 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2618
Anders Carlssonc154a722009-05-01 19:30:39 +00002619 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002620 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002621 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002622 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002623 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002624 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002625
Douglas Gregor3257fb52008-12-22 05:46:06 +00002626 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002627 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002628 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002629 // FIXME: Will need to cache the results of name lookup (including ADL) in
2630 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002631 bool Dependent = false;
2632 if (Fn->isTypeDependent())
2633 Dependent = true;
2634 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2635 Dependent = true;
2636
2637 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002638 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002639 Context.DependentTy, RParenLoc));
2640
2641 // Determine whether this is a call to an object (C++ [over.call.object]).
2642 if (Fn->getType()->isRecordType())
2643 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2644 CommaLocs, RParenLoc));
2645
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002646 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002647 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2648 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2649 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2650 isa<CXXMethodDecl>(MemDecl) ||
2651 (isa<FunctionTemplateDecl>(MemDecl) &&
2652 isa<CXXMethodDecl>(
2653 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002654 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2655 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002656 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002657 }
2658
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002659 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002660 // Also, in C++, keep track of whether we should perform argument-dependent
2661 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002662 Expr *FnExpr = Fn;
2663 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002664 bool HasExplicitTemplateArgs = 0;
2665 const TemplateArgument *ExplicitTemplateArgs = 0;
2666 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002667 while (true) {
2668 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2669 FnExpr = IcExpr->getSubExpr();
2670 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002671 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002672 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002673 ADL = false;
2674 FnExpr = PExpr->getSubExpr();
2675 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002676 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002677 == UnaryOperator::AddrOf) {
2678 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002679 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002680 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2681 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002682 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002683 break;
Mike Stump9afab102009-02-19 03:04:26 +00002684 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002685 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2686 UnqualifiedName = DepName->getName();
2687 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002688 } else if (TemplateIdRefExpr *TemplateIdRef
2689 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2690 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002691 if (!NDecl)
2692 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002693 HasExplicitTemplateArgs = true;
2694 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2695 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2696
2697 // C++ [temp.arg.explicit]p6:
2698 // [Note: For simple function names, argument dependent lookup (3.4.2)
2699 // applies even when the function name is not visible within the
2700 // scope of the call. This is because the call still has the syntactic
2701 // form of a function call (3.4.1). But when a function template with
2702 // explicit template arguments is used, the call does not have the
2703 // correct syntactic form unless there is a function template with
2704 // that name visible at the point of the call. If no such name is
2705 // visible, the call is not syntactically well-formed and
2706 // argument-dependent lookup does not apply. If some such name is
2707 // visible, argument dependent lookup applies and additional function
2708 // templates may be found in other namespaces.
2709 //
2710 // The summary of this paragraph is that, if we get to this point and the
2711 // template-id was not a qualified name, then argument-dependent lookup
2712 // is still possible.
2713 if (TemplateIdRef->getQualifier())
2714 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002715 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002716 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002717 // Any kind of name that does not refer to a declaration (or
2718 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2719 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002720 break;
2721 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002722 }
Mike Stump9afab102009-02-19 03:04:26 +00002723
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002724 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002725 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002726 if (NDecl) {
2727 FDecl = dyn_cast<FunctionDecl>(NDecl);
2728 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002729 FDecl = FunctionTemplate->getTemplatedDecl();
2730 else
Douglas Gregor28857752009-06-30 22:34:41 +00002731 FDecl = dyn_cast<FunctionDecl>(NDecl);
2732 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002733 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002734
Douglas Gregorb60eb752009-06-25 22:08:12 +00002735 if (Ovl || FunctionTemplate ||
2736 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002737 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002738 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002739 ADL = false;
2740
Douglas Gregorfcb19192009-02-11 23:02:49 +00002741 // We don't perform ADL in C.
2742 if (!getLangOptions().CPlusPlus)
2743 ADL = false;
2744
Douglas Gregorb60eb752009-06-25 22:08:12 +00002745 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002746 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2747 HasExplicitTemplateArgs,
2748 ExplicitTemplateArgs,
2749 NumExplicitTemplateArgs,
2750 LParenLoc, Args, NumArgs, CommaLocs,
2751 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002752 if (!FDecl)
2753 return ExprError();
2754
2755 // Update Fn to refer to the actual function selected.
2756 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002757 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002758 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002759 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2760 QDRExpr->getLocation(),
2761 false, false,
2762 QDRExpr->getQualifierRange(),
2763 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002764 else
Mike Stump9afab102009-02-19 03:04:26 +00002765 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002766 Fn->getSourceRange().getBegin());
2767 Fn->Destroy(Context);
2768 Fn = NewFn;
2769 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002770 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002771
2772 // Promote the function operand.
2773 UsualUnaryConversions(Fn);
2774
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002775 // Make the call expr early, before semantic checks. This guarantees cleanup
2776 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002777 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2778 Args, NumArgs,
2779 Context.BoolTy,
2780 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002781
Steve Naroffd6163f32008-09-05 22:11:13 +00002782 const FunctionType *FuncT;
2783 if (!Fn->getType()->isBlockPointerType()) {
2784 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2785 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002786 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002787 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002788 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2789 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002790 FuncT = PT->getPointeeType()->getAsFunctionType();
2791 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002792 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002793 getAsFunctionType();
2794 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002795 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002796 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2797 << Fn->getType() << Fn->getSourceRange());
2798
Eli Friedman83dec9e2009-03-22 22:00:50 +00002799 // Check for a valid return type
2800 if (!FuncT->getResultType()->isVoidType() &&
2801 RequireCompleteType(Fn->getSourceRange().getBegin(),
2802 FuncT->getResultType(),
2803 diag::err_call_incomplete_return,
2804 TheCall->getSourceRange()))
2805 return ExprError();
2806
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002807 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002808 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002809
Douglas Gregor4fa58902009-02-26 23:50:07 +00002810 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002811 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002812 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002813 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002814 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002815 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002816
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002817 if (FDecl) {
2818 // Check if we have too few/too many template arguments, based
2819 // on our knowledge of the function definition.
2820 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002821 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002822 const FunctionProtoType *Proto =
2823 Def->getType()->getAsFunctionProtoType();
2824 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2825 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2826 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2827 }
2828 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002829 }
2830
Steve Naroffdb65e052007-08-28 23:30:39 +00002831 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002832 for (unsigned i = 0; i != NumArgs; i++) {
2833 Expr *Arg = Args[i];
2834 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002835 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2836 Arg->getType(),
2837 diag::err_call_incomplete_argument,
2838 Arg->getSourceRange()))
2839 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002840 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002841 }
Chris Lattner4b009652007-07-25 00:24:17 +00002842 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002843
Douglas Gregor3257fb52008-12-22 05:46:06 +00002844 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2845 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002846 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2847 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002848
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002849 // Check for sentinels
2850 if (NDecl)
2851 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002852
Chris Lattner2e64c072007-08-10 20:18:51 +00002853 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002854 if (FDecl) {
2855 if (CheckFunctionCall(FDecl, TheCall.get()))
2856 return ExprError();
2857
2858 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2859 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2860 } else if (NDecl) {
2861 if (CheckBlockCall(NDecl, TheCall.get()))
2862 return ExprError();
2863 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002864
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002865 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002866}
2867
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002868Action::OwningExprResult
2869Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2870 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002871 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002872 //FIXME: Preserve type source info.
2873 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002874 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002875 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002876 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002877
Eli Friedman8c2173d2008-05-20 05:22:08 +00002878 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002879 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002880 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2881 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002882 } else if (!literalType->isDependentType() &&
2883 RequireCompleteType(LParenLoc, literalType,
2884 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002885 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002886 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002887
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002888 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002889 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002890 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002891
Chris Lattnere5cb5862008-12-04 23:50:19 +00002892 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002893 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002894 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002895 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002896 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002897 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002898 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002899 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002900}
2901
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002902Action::OwningExprResult
2903Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002904 SourceLocation RBraceLoc) {
2905 unsigned NumInit = initlist.size();
2906 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002907
Steve Naroff0acc9c92007-09-15 18:49:24 +00002908 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002909 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002910
Mike Stump9afab102009-02-19 03:04:26 +00002911 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002912 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002913 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002914 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002915}
2916
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002917/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002918bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002919 CastExpr::CastKind& Kind,
2920 CXXMethodDecl *& ConversionDecl,
2921 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002922 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002923 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2924 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002925
Eli Friedman01e0f652009-08-15 19:02:19 +00002926 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002927
2928 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2929 // type needs to be scalar.
2930 if (castType->isVoidType()) {
2931 // Cast to void allows any expr type.
2932 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002933 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2934 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2935 (castType->isStructureType() || castType->isUnionType())) {
2936 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002937 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002938 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2939 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002940 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002941 } else if (castType->isUnionType()) {
2942 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002943 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002944 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002945 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002946 Field != FieldEnd; ++Field) {
2947 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2948 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2949 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2950 << castExpr->getSourceRange();
2951 break;
2952 }
2953 }
2954 if (Field == FieldEnd)
2955 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2956 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002957 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002958 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002959 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002960 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002961 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002962 }
Mike Stump9afab102009-02-19 03:04:26 +00002963 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002964 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002965 return Diag(castExpr->getLocStart(),
2966 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002967 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002968 } else if (castType->isExtVectorType()) {
2969 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002970 return true;
2971 } else if (castType->isVectorType()) {
2972 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2973 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002974 } else if (castExpr->getType()->isVectorType()) {
2975 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2976 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002977 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002978 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002979 } else if (!castType->isArithmeticType()) {
2980 QualType castExprType = castExpr->getType();
2981 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2982 return Diag(castExpr->getLocStart(),
2983 diag::err_cast_pointer_from_non_pointer_int)
2984 << castExprType << castExpr->getSourceRange();
2985 } else if (!castExpr->getType()->isArithmeticType()) {
2986 if (!castType->isIntegralType() && castType->isArithmeticType())
2987 return Diag(castExpr->getLocStart(),
2988 diag::err_cast_pointer_to_non_pointer_int)
2989 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002990 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002991 if (isa<ObjCSelectorExpr>(castExpr))
2992 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002993 return false;
2994}
2995
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002996bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002997 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002998
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002999 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003000 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003001 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003002 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003003 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003004 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003005 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003006 } else
3007 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003008 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003009 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003010
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003011 return false;
3012}
3013
Nate Begemanbd42e022009-06-26 00:50:28 +00003014bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3015 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3016
Nate Begeman9e063702009-06-27 22:05:55 +00003017 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3018 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003019 if (SrcTy->isVectorType()) {
3020 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3021 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3022 << DestTy << SrcTy << R;
3023 return false;
3024 }
3025
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003026 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003027 // conversion will take place first from scalar to elt type, and then
3028 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003029 if (SrcTy->isPointerType())
3030 return Diag(R.getBegin(),
3031 diag::err_invalid_conversion_between_vector_and_scalar)
3032 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003033 return false;
3034}
3035
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003036Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003037Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003038 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003039 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3040
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003041 assert((Ty != 0) && (Op.get() != 0) &&
3042 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003043
Nate Begemane85f43d2009-08-10 23:49:36 +00003044 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003045 //FIXME: Preserve type source info.
3046 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003047
3048 // If the Expr being casted is a ParenListExpr, handle it specially.
3049 if (isa<ParenListExpr>(castExpr))
3050 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003051 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003052 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003053 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003054 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003055
3056 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003057 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003058 Kind, castExpr, castType,
3059 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003060}
3061
Nate Begemane85f43d2009-08-10 23:49:36 +00003062/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3063/// of comma binary operators.
3064Action::OwningExprResult
3065Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3066 Expr *expr = EA.takeAs<Expr>();
3067 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3068 if (!E)
3069 return Owned(expr);
3070
3071 OwningExprResult Result(*this, E->getExpr(0));
3072
3073 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3074 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3075 Owned(E->getExpr(i)));
3076
3077 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3078}
3079
3080Action::OwningExprResult
3081Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3082 SourceLocation RParenLoc, ExprArg Op,
3083 QualType Ty) {
3084 ParenListExpr *PE = (ParenListExpr *)Op.get();
3085
3086 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3087 // then handle it as such.
3088 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3089 if (PE->getNumExprs() == 0) {
3090 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3091 return ExprError();
3092 }
3093
3094 llvm::SmallVector<Expr *, 8> initExprs;
3095 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3096 initExprs.push_back(PE->getExpr(i));
3097
3098 // FIXME: This means that pretty-printing the final AST will produce curly
3099 // braces instead of the original commas.
3100 Op.release();
3101 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3102 initExprs.size(), RParenLoc);
3103 E->setType(Ty);
3104 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3105 Owned(E));
3106 } else {
3107 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3108 // sequence of BinOp comma operators.
3109 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3110 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3111 }
3112}
3113
3114Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3115 SourceLocation R,
3116 MultiExprArg Val) {
3117 unsigned nexprs = Val.size();
3118 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3119 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3120 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3121 return Owned(expr);
3122}
3123
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003124/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3125/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003126/// C99 6.5.15
3127QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3128 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003129 // C++ is sufficiently different to merit its own checker.
3130 if (getLangOptions().CPlusPlus)
3131 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3132
Chris Lattnere2897262009-02-18 04:28:32 +00003133 UsualUnaryConversions(Cond);
3134 UsualUnaryConversions(LHS);
3135 UsualUnaryConversions(RHS);
3136 QualType CondTy = Cond->getType();
3137 QualType LHSTy = LHS->getType();
3138 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003139
3140 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003141 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3142 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3143 << CondTy;
3144 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003145 }
Mike Stump9afab102009-02-19 03:04:26 +00003146
Chris Lattner992ae932008-01-06 22:42:25 +00003147 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003148 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3149 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003150
Chris Lattner992ae932008-01-06 22:42:25 +00003151 // If both operands have arithmetic type, do the usual arithmetic conversions
3152 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003153 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3154 UsualArithmeticConversions(LHS, RHS);
3155 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003156 }
Mike Stump9afab102009-02-19 03:04:26 +00003157
Chris Lattner992ae932008-01-06 22:42:25 +00003158 // If both operands are the same structure or union type, the result is that
3159 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003160 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3161 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003162 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003163 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003164 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003165 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003166 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003167 }
Mike Stump9afab102009-02-19 03:04:26 +00003168
Chris Lattner992ae932008-01-06 22:42:25 +00003169 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003170 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003171 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3172 if (!LHSTy->isVoidType())
3173 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3174 << RHS->getSourceRange();
3175 if (!RHSTy->isVoidType())
3176 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3177 << LHS->getSourceRange();
3178 ImpCastExprToType(LHS, Context.VoidTy);
3179 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003180 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003181 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003182 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3183 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003184 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003185 RHS->isNullPointerConstant(Context)) {
3186 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3187 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003188 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003189 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003190 LHS->isNullPointerConstant(Context)) {
3191 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3192 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003193 }
David Chisnall44663db2009-08-17 16:35:33 +00003194 // Handle things like Class and struct objc_class*. Here we case the result
3195 // to the pseudo-builtin, because that will be implicitly cast back to the
3196 // redefinition type if an attempt is made to access its fields.
3197 if (LHSTy->isObjCClassType() &&
3198 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3199 ImpCastExprToType(RHS, LHSTy);
3200 return LHSTy;
3201 }
3202 if (RHSTy->isObjCClassType() &&
3203 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3204 ImpCastExprToType(LHS, RHSTy);
3205 return RHSTy;
3206 }
3207 // And the same for struct objc_object* / id
3208 if (LHSTy->isObjCIdType() &&
3209 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3210 ImpCastExprToType(RHS, LHSTy);
3211 return LHSTy;
3212 }
3213 if (RHSTy->isObjCIdType() &&
3214 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3215 ImpCastExprToType(LHS, RHSTy);
3216 return RHSTy;
3217 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003218 // Handle block pointer types.
3219 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3220 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3221 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3222 QualType destType = Context.getPointerType(Context.VoidTy);
3223 ImpCastExprToType(LHS, destType);
3224 ImpCastExprToType(RHS, destType);
3225 return destType;
3226 }
3227 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3228 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3229 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003230 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003231 // We have 2 block pointer types.
3232 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3233 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003234 return LHSTy;
3235 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003236 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003237 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3238 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003239
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003240 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3241 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003242 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3243 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3244 // In this situation, we assume void* type. No especially good
3245 // reason, but this is what gcc does, and we do have to pick
3246 // to get a consistent AST.
3247 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3248 ImpCastExprToType(LHS, incompatTy);
3249 ImpCastExprToType(RHS, incompatTy);
3250 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003251 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003252 // The block pointer types are compatible.
3253 ImpCastExprToType(LHS, LHSTy);
3254 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003255 return LHSTy;
3256 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003257 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003258 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003259
3260 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3261 // Two identical object pointer types are always compatible.
3262 return LHSTy;
3263 }
Steve Naroff329ec222009-07-10 23:34:53 +00003264 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3265 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003266 QualType compositeType = LHSTy;
3267
3268 // If both operands are interfaces and either operand can be
3269 // assigned to the other, use that type as the composite
3270 // type. This allows
3271 // xxx ? (A*) a : (B*) b
3272 // where B is a subclass of A.
3273 //
3274 // Additionally, as for assignment, if either type is 'id'
3275 // allow silent coercion. Finally, if the types are
3276 // incompatible then make sure to use 'id' as the composite
3277 // type so the result is acceptable for sending messages to.
3278
3279 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3280 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003281 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003282 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003283 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003284 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003285 } else if ((LHSTy->isObjCQualifiedIdType() ||
3286 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003287 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003288 // Need to handle "id<xx>" explicitly.
3289 // GCC allows qualified id and any Objective-C type to devolve to
3290 // id. Currently localizing to here until clear this should be
3291 // part of ObjCQualifiedIdTypesAreCompatible.
3292 compositeType = Context.getObjCIdType();
3293 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003294 compositeType = Context.getObjCIdType();
3295 } else {
3296 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3297 << LHSTy << RHSTy
3298 << LHS->getSourceRange() << RHS->getSourceRange();
3299 QualType incompatTy = Context.getObjCIdType();
3300 ImpCastExprToType(LHS, incompatTy);
3301 ImpCastExprToType(RHS, incompatTy);
3302 return incompatTy;
3303 }
3304 // The object pointer types are compatible.
3305 ImpCastExprToType(LHS, compositeType);
3306 ImpCastExprToType(RHS, compositeType);
3307 return compositeType;
3308 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003309 // Check Objective-C object pointer types and 'void *'
3310 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003311 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003312 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3313 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3314 QualType destType = Context.getPointerType(destPointee);
3315 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3316 ImpCastExprToType(RHS, destType); // promote to void*
3317 return destType;
3318 }
3319 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3320 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003321 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003322 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3323 QualType destType = Context.getPointerType(destPointee);
3324 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3325 ImpCastExprToType(LHS, destType); // promote to void*
3326 return destType;
3327 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003328 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3329 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3330 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003331 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3332 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003333
3334 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3335 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3336 // Figure out necessary qualifiers (C99 6.5.15p6)
3337 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3338 QualType destType = Context.getPointerType(destPointee);
3339 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3340 ImpCastExprToType(RHS, destType); // promote to void*
3341 return destType;
3342 }
3343 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3344 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3345 QualType destType = Context.getPointerType(destPointee);
3346 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3347 ImpCastExprToType(RHS, destType); // promote to void*
3348 return destType;
3349 }
3350
3351 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3352 // Two identical pointer types are always compatible.
3353 return LHSTy;
3354 }
3355 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3356 rhptee.getUnqualifiedType())) {
3357 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3358 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3359 // In this situation, we assume void* type. No especially good
3360 // reason, but this is what gcc does, and we do have to pick
3361 // to get a consistent AST.
3362 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3363 ImpCastExprToType(LHS, incompatTy);
3364 ImpCastExprToType(RHS, incompatTy);
3365 return incompatTy;
3366 }
3367 // The pointer types are compatible.
3368 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3369 // differently qualified versions of compatible types, the result type is
3370 // a pointer to an appropriately qualified version of the *composite*
3371 // type.
3372 // FIXME: Need to calculate the composite type.
3373 // FIXME: Need to add qualifiers
3374 ImpCastExprToType(LHS, LHSTy);
3375 ImpCastExprToType(RHS, LHSTy);
3376 return LHSTy;
3377 }
3378
3379 // GCC compatibility: soften pointer/integer mismatch.
3380 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3381 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3382 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3383 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3384 return RHSTy;
3385 }
3386 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3387 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3388 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3389 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3390 return LHSTy;
3391 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003392
Chris Lattner992ae932008-01-06 22:42:25 +00003393 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003394 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3395 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003396 return QualType();
3397}
3398
Steve Naroff87d58b42007-09-16 03:34:24 +00003399/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003400/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003401Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3402 SourceLocation ColonLoc,
3403 ExprArg Cond, ExprArg LHS,
3404 ExprArg RHS) {
3405 Expr *CondExpr = (Expr *) Cond.get();
3406 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003407
3408 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3409 // was the condition.
3410 bool isLHSNull = LHSExpr == 0;
3411 if (isLHSNull)
3412 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003413
3414 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003415 RHSExpr, QuestionLoc);
3416 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003417 return ExprError();
3418
3419 Cond.release();
3420 LHS.release();
3421 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003422 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003423 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003424 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003425}
3426
Chris Lattner4b009652007-07-25 00:24:17 +00003427// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003428// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003429// routine is it effectively iqnores the qualifiers on the top level pointee.
3430// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3431// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003432Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003433Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3434 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003435
David Chisnall44663db2009-08-17 16:35:33 +00003436 if ((lhsType->isObjCClassType() &&
3437 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3438 (rhsType->isObjCClassType() &&
3439 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3440 return Compatible;
3441 }
3442
Chris Lattner4b009652007-07-25 00:24:17 +00003443 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003444 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3445 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003446
Chris Lattner4b009652007-07-25 00:24:17 +00003447 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003448 lhptee = Context.getCanonicalType(lhptee);
3449 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003450
Chris Lattner005ed752008-01-04 18:04:52 +00003451 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003452
3453 // C99 6.5.16.1p1: This following citation is common to constraints
3454 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3455 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003456 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003457 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003458 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003459
Mike Stump9afab102009-02-19 03:04:26 +00003460 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3461 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003462 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003463 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003464 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003465 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003466
Chris Lattner4ca3d772008-01-03 22:56:36 +00003467 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003468 assert(rhptee->isFunctionType());
3469 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003470 }
Mike Stump9afab102009-02-19 03:04:26 +00003471
Chris Lattner4ca3d772008-01-03 22:56:36 +00003472 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003473 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003474 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003475
3476 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003477 assert(lhptee->isFunctionType());
3478 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003479 }
Mike Stump9afab102009-02-19 03:04:26 +00003480 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003481 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003482 lhptee = lhptee.getUnqualifiedType();
3483 rhptee = rhptee.getUnqualifiedType();
3484 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3485 // Check if the pointee types are compatible ignoring the sign.
3486 // We explicitly check for char so that we catch "char" vs
3487 // "unsigned char" on systems where "char" is unsigned.
3488 if (lhptee->isCharType()) {
3489 lhptee = Context.UnsignedCharTy;
3490 } else if (lhptee->isSignedIntegerType()) {
3491 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3492 }
3493 if (rhptee->isCharType()) {
3494 rhptee = Context.UnsignedCharTy;
3495 } else if (rhptee->isSignedIntegerType()) {
3496 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3497 }
3498 if (lhptee == rhptee) {
3499 // Types are compatible ignoring the sign. Qualifier incompatibility
3500 // takes priority over sign incompatibility because the sign
3501 // warning can be disabled.
3502 if (ConvTy != Compatible)
3503 return ConvTy;
3504 return IncompatiblePointerSign;
3505 }
3506 // General pointer incompatibility takes priority over qualifiers.
3507 return IncompatiblePointer;
3508 }
Chris Lattner005ed752008-01-04 18:04:52 +00003509 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003510}
3511
Steve Naroff3454b6c2008-09-04 15:10:53 +00003512/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3513/// block pointer types are compatible or whether a block and normal pointer
3514/// are compatible. It is more restrict than comparing two function pointer
3515// types.
Mike Stump9afab102009-02-19 03:04:26 +00003516Sema::AssignConvertType
3517Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003518 QualType rhsType) {
3519 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003520
Steve Naroff3454b6c2008-09-04 15:10:53 +00003521 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003522 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3523 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003524
Steve Naroff3454b6c2008-09-04 15:10:53 +00003525 // make sure we operate on the canonical type
3526 lhptee = Context.getCanonicalType(lhptee);
3527 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003528
Steve Naroff3454b6c2008-09-04 15:10:53 +00003529 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003530
Steve Naroff3454b6c2008-09-04 15:10:53 +00003531 // For blocks we enforce that qualifiers are identical.
3532 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3533 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003534
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003535 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003536 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003537 return ConvTy;
3538}
3539
Mike Stump9afab102009-02-19 03:04:26 +00003540/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3541/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003542/// pointers. Here are some objectionable examples that GCC considers warnings:
3543///
3544/// int a, *pint;
3545/// short *pshort;
3546/// struct foo *pfoo;
3547///
3548/// pint = pshort; // warning: assignment from incompatible pointer type
3549/// a = pint; // warning: assignment makes integer from pointer without a cast
3550/// pint = a; // warning: assignment makes pointer from integer without a cast
3551/// pint = pfoo; // warning: assignment from incompatible pointer type
3552///
3553/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003554/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003555///
Chris Lattner005ed752008-01-04 18:04:52 +00003556Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003557Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003558 // Get canonical types. We're not formatting these types, just comparing
3559 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003560 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3561 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003562
3563 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003564 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003565
David Chisnall44663db2009-08-17 16:35:33 +00003566 if ((lhsType->isObjCClassType() &&
3567 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3568 (rhsType->isObjCClassType() &&
3569 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3570 return Compatible;
3571 }
3572
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003573 // If the left-hand side is a reference type, then we are in a
3574 // (rare!) case where we've allowed the use of references in C,
3575 // e.g., as a parameter type in a built-in function. In this case,
3576 // just make sure that the type referenced is compatible with the
3577 // right-hand side type. The caller is responsible for adjusting
3578 // lhsType so that the resulting expression does not have reference
3579 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003580 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003581 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003582 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003583 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003584 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003585 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3586 // to the same ExtVector type.
3587 if (lhsType->isExtVectorType()) {
3588 if (rhsType->isExtVectorType())
3589 return lhsType == rhsType ? Compatible : Incompatible;
3590 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3591 return Compatible;
3592 }
3593
Nate Begemanc5f0f652008-07-14 18:02:46 +00003594 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003595 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003596 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003597 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003598 if (getLangOptions().LaxVectorConversions &&
3599 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003600 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003601 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003602 }
3603 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003604 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003605
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003606 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003607 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003608
Chris Lattner390564e2008-04-07 06:49:41 +00003609 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003610 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003611 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003612
Chris Lattner390564e2008-04-07 06:49:41 +00003613 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003614 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003615
Steve Naroff8194a542009-07-20 17:56:53 +00003616 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003617 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003618 if (lhsType->isVoidPointerType()) // an exception to the rule.
3619 return Compatible;
3620 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003621 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003622 if (rhsType->getAs<BlockPointerType>()) {
3623 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003624 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003625
3626 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003627 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003628 return Compatible;
3629 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003630 return Incompatible;
3631 }
3632
3633 if (isa<BlockPointerType>(lhsType)) {
3634 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003635 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003636
Steve Naroffa982c712008-09-29 18:10:17 +00003637 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003638 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003639 return Compatible;
3640
Steve Naroff3454b6c2008-09-04 15:10:53 +00003641 if (rhsType->isBlockPointerType())
3642 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003643
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003644 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003645 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003646 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003647 }
Chris Lattner1853da22008-01-04 23:18:45 +00003648 return Incompatible;
3649 }
3650
Steve Naroff329ec222009-07-10 23:34:53 +00003651 if (isa<ObjCObjectPointerType>(lhsType)) {
3652 if (rhsType->isIntegerType())
3653 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003654
3655 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003656 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003657 if (rhsType->isVoidPointerType()) // an exception to the rule.
3658 return Compatible;
3659 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003660 }
3661 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003662 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3663 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003664 if (Context.typesAreCompatible(lhsType, rhsType))
3665 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003666 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3667 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003668 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003669 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003670 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003671 if (RHSPT->getPointeeType()->isVoidType())
3672 return Compatible;
3673 }
3674 // Treat block pointers as objects.
3675 if (rhsType->isBlockPointerType())
3676 return Compatible;
3677 return Incompatible;
3678 }
Chris Lattner390564e2008-04-07 06:49:41 +00003679 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003680 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003681 if (lhsType == Context.BoolTy)
3682 return Compatible;
3683
3684 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003685 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003686
Mike Stump9afab102009-02-19 03:04:26 +00003687 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003688 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003689
3690 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003691 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003692 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003693 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003694 }
Steve Naroff329ec222009-07-10 23:34:53 +00003695 if (isa<ObjCObjectPointerType>(rhsType)) {
3696 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3697 if (lhsType == Context.BoolTy)
3698 return Compatible;
3699
3700 if (lhsType->isIntegerType())
3701 return PointerToInt;
3702
Steve Naroff8194a542009-07-20 17:56:53 +00003703 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003704 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003705 if (lhsType->isVoidPointerType()) // an exception to the rule.
3706 return Compatible;
3707 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003708 }
3709 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003710 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003711 return Compatible;
3712 return Incompatible;
3713 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003714
Chris Lattner1853da22008-01-04 23:18:45 +00003715 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003716 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003717 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003718 }
3719 return Incompatible;
3720}
3721
Douglas Gregor144b06c2009-04-29 22:16:16 +00003722/// \brief Constructs a transparent union from an expression that is
3723/// used to initialize the transparent union.
3724static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3725 QualType UnionType, FieldDecl *Field) {
3726 // Build an initializer list that designates the appropriate member
3727 // of the transparent union.
3728 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3729 &E, 1,
3730 SourceLocation());
3731 Initializer->setType(UnionType);
3732 Initializer->setInitializedFieldInUnion(Field);
3733
3734 // Build a compound literal constructing a value of the transparent
3735 // union type from this initializer list.
3736 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3737 false);
3738}
3739
3740Sema::AssignConvertType
3741Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3742 QualType FromType = rExpr->getType();
3743
3744 // If the ArgType is a Union type, we want to handle a potential
3745 // transparent_union GCC extension.
3746 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003747 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003748 return Incompatible;
3749
3750 // The field to initialize within the transparent union.
3751 RecordDecl *UD = UT->getDecl();
3752 FieldDecl *InitField = 0;
3753 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003754 for (RecordDecl::field_iterator it = UD->field_begin(),
3755 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003756 it != itend; ++it) {
3757 if (it->getType()->isPointerType()) {
3758 // If the transparent union contains a pointer type, we allow:
3759 // 1) void pointer
3760 // 2) null pointer constant
3761 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003762 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003763 ImpCastExprToType(rExpr, it->getType());
3764 InitField = *it;
3765 break;
3766 }
3767
3768 if (rExpr->isNullPointerConstant(Context)) {
3769 ImpCastExprToType(rExpr, it->getType());
3770 InitField = *it;
3771 break;
3772 }
3773 }
3774
3775 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3776 == Compatible) {
3777 InitField = *it;
3778 break;
3779 }
3780 }
3781
3782 if (!InitField)
3783 return Incompatible;
3784
3785 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3786 return Compatible;
3787}
3788
Chris Lattner005ed752008-01-04 18:04:52 +00003789Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003790Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003791 if (getLangOptions().CPlusPlus) {
3792 if (!lhsType->isRecordType()) {
3793 // C++ 5.17p3: If the left operand is not of class type, the
3794 // expression is implicitly converted (C++ 4) to the
3795 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003796 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3797 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003798 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003799 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003800 }
3801
3802 // FIXME: Currently, we fall through and treat C++ classes like C
3803 // structures.
3804 }
3805
Steve Naroffcdee22d2007-11-27 17:58:44 +00003806 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3807 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003808 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003809 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003810 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003811 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003812 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003813 return Compatible;
3814 }
Mike Stump9afab102009-02-19 03:04:26 +00003815
Chris Lattner5f505bf2007-10-16 02:55:40 +00003816 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003817 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003818 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003819 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003820 //
Mike Stump9afab102009-02-19 03:04:26 +00003821 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003822 if (!lhsType->isReferenceType())
3823 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003824
Chris Lattner005ed752008-01-04 18:04:52 +00003825 Sema::AssignConvertType result =
3826 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003827
Steve Naroff0f32f432007-08-24 22:33:52 +00003828 // C99 6.5.16.1p2: The value of the right operand is converted to the
3829 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003830 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3831 // so that we can use references in built-in functions even in C.
3832 // The getNonReferenceType() call makes sure that the resulting expression
3833 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003834 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003835 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003836 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003837}
3838
Chris Lattner1eafdea2008-11-18 01:30:42 +00003839QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003840 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003841 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003842 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003843 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003844}
3845
Mike Stump9afab102009-02-19 03:04:26 +00003846inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003847 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003848 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003849 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003850 QualType lhsType =
3851 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3852 QualType rhsType =
3853 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003854
Nate Begemanc5f0f652008-07-14 18:02:46 +00003855 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003856 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003857 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003858
Nate Begemanc5f0f652008-07-14 18:02:46 +00003859 // Handle the case of a vector & extvector type of the same size and element
3860 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003861 if (getLangOptions().LaxVectorConversions) {
3862 // FIXME: Should we warn here?
3863 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003864 if (const VectorType *RV = rhsType->getAsVectorType())
3865 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003866 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003867 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003868 }
3869 }
3870 }
Mike Stump9afab102009-02-19 03:04:26 +00003871
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003872 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3873 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3874 bool swapped = false;
3875 if (rhsType->isExtVectorType()) {
3876 swapped = true;
3877 std::swap(rex, lex);
3878 std::swap(rhsType, lhsType);
3879 }
3880
Nate Begemanf1695892009-06-28 19:12:57 +00003881 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003882 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3883 QualType EltTy = LV->getElementType();
3884 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3885 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003886 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003887 if (swapped) std::swap(rex, lex);
3888 return lhsType;
3889 }
3890 }
3891 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3892 rhsType->isRealFloatingType()) {
3893 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003894 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003895 if (swapped) std::swap(rex, lex);
3896 return lhsType;
3897 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003898 }
3899 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003900
Nate Begemanf1695892009-06-28 19:12:57 +00003901 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003902 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003903 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003904 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003905 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003906}
3907
Chris Lattner4b009652007-07-25 00:24:17 +00003908inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003909 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003910{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003911 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003912 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003913
Steve Naroff8f708362007-08-24 19:07:16 +00003914 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003915
Chris Lattner4b009652007-07-25 00:24:17 +00003916 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003917 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003918 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003919}
3920
3921inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003922 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003923{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3925 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3926 return CheckVectorOperands(Loc, lex, rex);
3927 return InvalidOperands(Loc, lex, rex);
3928 }
Chris Lattner4b009652007-07-25 00:24:17 +00003929
Steve Naroff8f708362007-08-24 19:07:16 +00003930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003931
Chris Lattner4b009652007-07-25 00:24:17 +00003932 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003933 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003934 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003935}
3936
3937inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003938 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003939{
Eli Friedman3cd92882009-03-28 01:22:36 +00003940 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3941 QualType compType = CheckVectorOperands(Loc, lex, rex);
3942 if (CompLHSTy) *CompLHSTy = compType;
3943 return compType;
3944 }
Chris Lattner4b009652007-07-25 00:24:17 +00003945
Eli Friedman3cd92882009-03-28 01:22:36 +00003946 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003947
Chris Lattner4b009652007-07-25 00:24:17 +00003948 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003949 if (lex->getType()->isArithmeticType() &&
3950 rex->getType()->isArithmeticType()) {
3951 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003952 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003953 }
Chris Lattner4b009652007-07-25 00:24:17 +00003954
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003955 // Put any potential pointer into PExp
3956 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003957 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003958 std::swap(PExp, IExp);
3959
Steve Naroff79ae19a2009-07-14 18:25:06 +00003960 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003961
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003962 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003963 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003964
Chris Lattner184f92d2009-04-24 23:50:08 +00003965 // Check for arithmetic on pointers to incomplete types.
3966 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003967 if (getLangOptions().CPlusPlus) {
3968 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003969 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003970 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003971 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003972
3973 // GNU extension: arithmetic on pointer to void
3974 Diag(Loc, diag::ext_gnu_void_ptr)
3975 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003976 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003977 if (getLangOptions().CPlusPlus) {
3978 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3979 << lex->getType() << lex->getSourceRange();
3980 return QualType();
3981 }
3982
3983 // GNU extension: arithmetic on pointer to function
3984 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3985 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003986 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003987 // Check if we require a complete type.
3988 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003989 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003990 PExp->getType()->isObjCObjectPointerType()) &&
3991 RequireCompleteType(Loc, PointeeTy,
3992 diag::err_typecheck_arithmetic_incomplete_type,
3993 PExp->getSourceRange(), SourceRange(),
3994 PExp->getType()))
3995 return QualType();
3996 }
Chris Lattner184f92d2009-04-24 23:50:08 +00003997 // Diagnose bad cases where we step over interface counts.
3998 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3999 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4000 << PointeeTy << PExp->getSourceRange();
4001 return QualType();
4002 }
4003
Eli Friedman3cd92882009-03-28 01:22:36 +00004004 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004005 QualType LHSTy = Context.isPromotableBitField(lex);
4006 if (LHSTy.isNull()) {
4007 LHSTy = lex->getType();
4008 if (LHSTy->isPromotableIntegerType())
4009 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004010 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004011 *CompLHSTy = LHSTy;
4012 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004013 return PExp->getType();
4014 }
4015 }
4016
Chris Lattner1eafdea2008-11-18 01:30:42 +00004017 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004018}
4019
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004020// C99 6.5.6
4021QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004022 SourceLocation Loc, QualType* CompLHSTy) {
4023 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4024 QualType compType = CheckVectorOperands(Loc, lex, rex);
4025 if (CompLHSTy) *CompLHSTy = compType;
4026 return compType;
4027 }
Mike Stump9afab102009-02-19 03:04:26 +00004028
Eli Friedman3cd92882009-03-28 01:22:36 +00004029 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004030
Chris Lattnerf6da2912007-12-09 21:53:25 +00004031 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004032
Chris Lattnerf6da2912007-12-09 21:53:25 +00004033 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004034 if (lex->getType()->isArithmeticType()
4035 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004036 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004037 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004038 }
Steve Naroff329ec222009-07-10 23:34:53 +00004039
Chris Lattnerf6da2912007-12-09 21:53:25 +00004040 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004041 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004042 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004043
Douglas Gregor05e28f62009-03-24 19:52:54 +00004044 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004045
Douglas Gregor05e28f62009-03-24 19:52:54 +00004046 bool ComplainAboutVoid = false;
4047 Expr *ComplainAboutFunc = 0;
4048 if (lpointee->isVoidType()) {
4049 if (getLangOptions().CPlusPlus) {
4050 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4051 << lex->getSourceRange() << rex->getSourceRange();
4052 return QualType();
4053 }
4054
4055 // GNU C extension: arithmetic on pointer to void
4056 ComplainAboutVoid = true;
4057 } else if (lpointee->isFunctionType()) {
4058 if (getLangOptions().CPlusPlus) {
4059 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004060 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004061 return QualType();
4062 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004063
4064 // GNU C extension: arithmetic on pointer to function
4065 ComplainAboutFunc = lex;
4066 } else if (!lpointee->isDependentType() &&
4067 RequireCompleteType(Loc, lpointee,
4068 diag::err_typecheck_sub_ptr_object,
4069 lex->getSourceRange(),
4070 SourceRange(),
4071 lex->getType()))
4072 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004073
Chris Lattner184f92d2009-04-24 23:50:08 +00004074 // Diagnose bad cases where we step over interface counts.
4075 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4076 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4077 << lpointee << lex->getSourceRange();
4078 return QualType();
4079 }
4080
Chris Lattnerf6da2912007-12-09 21:53:25 +00004081 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004082 if (rex->getType()->isIntegerType()) {
4083 if (ComplainAboutVoid)
4084 Diag(Loc, diag::ext_gnu_void_ptr)
4085 << lex->getSourceRange() << rex->getSourceRange();
4086 if (ComplainAboutFunc)
4087 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4088 << ComplainAboutFunc->getType()
4089 << ComplainAboutFunc->getSourceRange();
4090
Eli Friedman3cd92882009-03-28 01:22:36 +00004091 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004092 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004093 }
Mike Stump9afab102009-02-19 03:04:26 +00004094
Chris Lattnerf6da2912007-12-09 21:53:25 +00004095 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004096 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004097 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004098
Douglas Gregor05e28f62009-03-24 19:52:54 +00004099 // RHS must be a completely-type object type.
4100 // Handle the GNU void* extension.
4101 if (rpointee->isVoidType()) {
4102 if (getLangOptions().CPlusPlus) {
4103 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4104 << lex->getSourceRange() << rex->getSourceRange();
4105 return QualType();
4106 }
Mike Stump9afab102009-02-19 03:04:26 +00004107
Douglas Gregor05e28f62009-03-24 19:52:54 +00004108 ComplainAboutVoid = true;
4109 } else if (rpointee->isFunctionType()) {
4110 if (getLangOptions().CPlusPlus) {
4111 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004112 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004113 return QualType();
4114 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004115
4116 // GNU extension: arithmetic on pointer to function
4117 if (!ComplainAboutFunc)
4118 ComplainAboutFunc = rex;
4119 } else if (!rpointee->isDependentType() &&
4120 RequireCompleteType(Loc, rpointee,
4121 diag::err_typecheck_sub_ptr_object,
4122 rex->getSourceRange(),
4123 SourceRange(),
4124 rex->getType()))
4125 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004126
Eli Friedman143ddc92009-05-16 13:54:38 +00004127 if (getLangOptions().CPlusPlus) {
4128 // Pointee types must be the same: C++ [expr.add]
4129 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4130 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4131 << lex->getType() << rex->getType()
4132 << lex->getSourceRange() << rex->getSourceRange();
4133 return QualType();
4134 }
4135 } else {
4136 // Pointee types must be compatible C99 6.5.6p3
4137 if (!Context.typesAreCompatible(
4138 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4139 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4140 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4141 << lex->getType() << rex->getType()
4142 << lex->getSourceRange() << rex->getSourceRange();
4143 return QualType();
4144 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004145 }
Mike Stump9afab102009-02-19 03:04:26 +00004146
Douglas Gregor05e28f62009-03-24 19:52:54 +00004147 if (ComplainAboutVoid)
4148 Diag(Loc, diag::ext_gnu_void_ptr)
4149 << lex->getSourceRange() << rex->getSourceRange();
4150 if (ComplainAboutFunc)
4151 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4152 << ComplainAboutFunc->getType()
4153 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004154
4155 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004156 return Context.getPointerDiffType();
4157 }
4158 }
Mike Stump9afab102009-02-19 03:04:26 +00004159
Chris Lattner1eafdea2008-11-18 01:30:42 +00004160 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004161}
4162
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004163// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004164QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004165 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004166 // C99 6.5.7p2: Each of the operands shall have integer type.
4167 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004168 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004169
Chris Lattner2c8bff72007-12-12 05:47:28 +00004170 // Shifts don't perform usual arithmetic conversions, they just do integer
4171 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004172 QualType LHSTy = Context.isPromotableBitField(lex);
4173 if (LHSTy.isNull()) {
4174 LHSTy = lex->getType();
4175 if (LHSTy->isPromotableIntegerType())
4176 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004177 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004178 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004179 ImpCastExprToType(lex, LHSTy);
4180
Chris Lattner2c8bff72007-12-12 05:47:28 +00004181 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004182
Ryan Flynnf109fff2009-08-07 16:20:20 +00004183 // Sanity-check shift operands
4184 llvm::APSInt Right;
4185 // Check right/shifter operand
4186 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004187 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004188 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4189 else {
4190 llvm::APInt LeftBits(Right.getBitWidth(),
4191 Context.getTypeSize(lex->getType()));
4192 if (Right.uge(LeftBits))
4193 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4194 }
4195 }
4196
Chris Lattner2c8bff72007-12-12 05:47:28 +00004197 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004198 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004199}
4200
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004201// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004202QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004203 unsigned OpaqueOpc, bool isRelational) {
4204 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4205
Nate Begemanc5f0f652008-07-14 18:02:46 +00004206 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004207 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004208
Chris Lattner254f3bc2007-08-26 01:18:55 +00004209 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004210 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4211 UsualArithmeticConversions(lex, rex);
4212 else {
4213 UsualUnaryConversions(lex);
4214 UsualUnaryConversions(rex);
4215 }
Chris Lattner4b009652007-07-25 00:24:17 +00004216 QualType lType = lex->getType();
4217 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004218
Mike Stumpea3d74e2009-05-07 18:43:07 +00004219 if (!lType->isFloatingType()
4220 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004221 // For non-floating point types, check for self-comparisons of the form
4222 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4223 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004224 // NOTE: Don't warn about comparisons of enum constants. These can arise
4225 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004226 Expr *LHSStripped = lex->IgnoreParens();
4227 Expr *RHSStripped = rex->IgnoreParens();
4228 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4229 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004230 if (DRL->getDecl() == DRR->getDecl() &&
4231 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004232 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004233
4234 if (isa<CastExpr>(LHSStripped))
4235 LHSStripped = LHSStripped->IgnoreParenCasts();
4236 if (isa<CastExpr>(RHSStripped))
4237 RHSStripped = RHSStripped->IgnoreParenCasts();
4238
4239 // Warn about comparisons against a string constant (unless the other
4240 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004241 Expr *literalString = 0;
4242 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004243 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004244 !RHSStripped->isNullPointerConstant(Context)) {
4245 literalString = lex;
4246 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004247 } else if ((isa<StringLiteral>(RHSStripped) ||
4248 isa<ObjCEncodeExpr>(RHSStripped)) &&
4249 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004250 literalString = rex;
4251 literalStringStripped = RHSStripped;
4252 }
4253
4254 if (literalString) {
4255 std::string resultComparison;
4256 switch (Opc) {
4257 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4258 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4259 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4260 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4261 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4262 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4263 default: assert(false && "Invalid comparison operator");
4264 }
4265 Diag(Loc, diag::warn_stringcompare)
4266 << isa<ObjCEncodeExpr>(literalStringStripped)
4267 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004268 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4269 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4270 "strcmp(")
4271 << CodeModificationHint::CreateInsertion(
4272 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004273 resultComparison);
4274 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004275 }
Mike Stump9afab102009-02-19 03:04:26 +00004276
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004277 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004278 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004279
Chris Lattner254f3bc2007-08-26 01:18:55 +00004280 if (isRelational) {
4281 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004282 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004283 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004284 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004285 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004286 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004287 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004288 }
Mike Stump9afab102009-02-19 03:04:26 +00004289
Chris Lattner254f3bc2007-08-26 01:18:55 +00004290 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004291 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004292 }
Mike Stump9afab102009-02-19 03:04:26 +00004293
Chris Lattner22be8422007-08-26 01:10:14 +00004294 bool LHSIsNull = lex->isNullPointerConstant(Context);
4295 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004296
Chris Lattner254f3bc2007-08-26 01:18:55 +00004297 // All of the following pointer related warnings are GCC extensions, except
4298 // when handling null pointer constants. One day, we can consider making them
4299 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004300 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004301 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004302 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004303 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004304 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004305
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004306 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004307 if (LCanPointeeTy == RCanPointeeTy)
4308 return ResultTy;
4309
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004310 // C++ [expr.rel]p2:
4311 // [...] Pointer conversions (4.10) and qualification
4312 // conversions (4.4) are performed on pointer operands (or on
4313 // a pointer operand and a null pointer constant) to bring
4314 // them to their composite pointer type. [...]
4315 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004316 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004317 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004318 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004319 if (T.isNull()) {
4320 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4321 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4322 return QualType();
4323 }
4324
4325 ImpCastExprToType(lex, T);
4326 ImpCastExprToType(rex, T);
4327 return ResultTy;
4328 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004329 // C99 6.5.9p2 and C99 6.5.8p2
4330 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4331 RCanPointeeTy.getUnqualifiedType())) {
4332 // Valid unless a relational comparison of function pointers
4333 if (isRelational && LCanPointeeTy->isFunctionType()) {
4334 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4335 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4336 }
4337 } else if (!isRelational &&
4338 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4339 // Valid unless comparison between non-null pointer and function pointer
4340 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4341 && !LHSIsNull && !RHSIsNull) {
4342 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4343 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4344 }
4345 } else {
4346 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004347 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004348 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004349 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004350 if (LCanPointeeTy != RCanPointeeTy)
4351 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004352 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004353 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004354
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004355 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004356 // Comparison of pointers with null pointer constants and equality
4357 // comparisons of member pointers to null pointer constants.
4358 if (RHSIsNull &&
4359 (lType->isPointerType() ||
4360 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004361 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004362 return ResultTy;
4363 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004364 if (LHSIsNull &&
4365 (rType->isPointerType() ||
4366 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004367 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004368 return ResultTy;
4369 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004370
4371 // Comparison of member pointers.
4372 if (!isRelational &&
4373 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4374 // C++ [expr.eq]p2:
4375 // In addition, pointers to members can be compared, or a pointer to
4376 // member and a null pointer constant. Pointer to member conversions
4377 // (4.11) and qualification conversions (4.4) are performed to bring
4378 // them to a common type. If one operand is a null pointer constant,
4379 // the common type is the type of the other operand. Otherwise, the
4380 // common type is a pointer to member type similar (4.4) to the type
4381 // of one of the operands, with a cv-qualification signature (4.4)
4382 // that is the union of the cv-qualification signatures of the operand
4383 // types.
4384 QualType T = FindCompositePointerType(lex, rex);
4385 if (T.isNull()) {
4386 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4387 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4388 return QualType();
4389 }
4390
4391 ImpCastExprToType(lex, T);
4392 ImpCastExprToType(rex, T);
4393 return ResultTy;
4394 }
4395
4396 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004397 if (lType->isNullPtrType() && rType->isNullPtrType())
4398 return ResultTy;
4399 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004400
Steve Naroff3454b6c2008-09-04 15:10:53 +00004401 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004402 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004403 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4404 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004405
Steve Naroff3454b6c2008-09-04 15:10:53 +00004406 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004407 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004408 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004409 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004410 }
4411 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004412 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004413 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004414 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004415 if (!isRelational
4416 && ((lType->isBlockPointerType() && rType->isPointerType())
4417 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004418 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004419 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004420 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004421 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004422 ->getPointeeType()->isVoidType())))
4423 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4424 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004425 }
4426 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004427 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004428 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004429
Steve Naroff329ec222009-07-10 23:34:53 +00004430 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004431 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004432 const PointerType *LPT = lType->getAs<PointerType>();
4433 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004434 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004435 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004436 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004437 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004438
Steve Naroff030fcda2008-11-17 19:49:16 +00004439 if (!LPtrToVoid && !RPtrToVoid &&
4440 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004441 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004442 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004443 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004444 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004445 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004446 }
Steve Naroff329ec222009-07-10 23:34:53 +00004447 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004448 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004449 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4450 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004451 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004452 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004453 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004454 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004455 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004456 unsigned DiagID = 0;
4457 if (RHSIsNull) {
4458 if (isRelational)
4459 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4460 } else if (isRelational)
4461 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4462 else
4463 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4464
4465 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004466 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004467 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004468 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004469 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004470 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004471 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004472 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004473 unsigned DiagID = 0;
4474 if (LHSIsNull) {
4475 if (isRelational)
4476 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4477 } else if (isRelational)
4478 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4479 else
4480 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004481
Chris Lattner124569f2009-08-23 00:03:44 +00004482 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004483 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004484 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004485 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004486 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004487 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004488 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004489 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004490 if (!isRelational && RHSIsNull
4491 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004492 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004493 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004494 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004495 if (!isRelational && LHSIsNull
4496 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004497 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004498 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004499 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004500 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004501}
4502
Nate Begemanc5f0f652008-07-14 18:02:46 +00004503/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004504/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004505/// like a scalar comparison, a vector comparison produces a vector of integer
4506/// types.
4507QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004508 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004509 bool isRelational) {
4510 // Check to make sure we're operating on vectors of the same type and width,
4511 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004512 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004513 if (vType.isNull())
4514 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004515
Nate Begemanc5f0f652008-07-14 18:02:46 +00004516 QualType lType = lex->getType();
4517 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004518
Nate Begemanc5f0f652008-07-14 18:02:46 +00004519 // For non-floating point types, check for self-comparisons of the form
4520 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4521 // often indicate logic errors in the program.
4522 if (!lType->isFloatingType()) {
4523 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4524 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4525 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004526 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004527 }
Mike Stump9afab102009-02-19 03:04:26 +00004528
Nate Begemanc5f0f652008-07-14 18:02:46 +00004529 // Check for comparisons of floating point operands using != and ==.
4530 if (!isRelational && lType->isFloatingType()) {
4531 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004532 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004533 }
Mike Stump9afab102009-02-19 03:04:26 +00004534
Nate Begemanc5f0f652008-07-14 18:02:46 +00004535 // Return the type for the comparison, which is the same as vector type for
4536 // integer vectors, or an integer type of identical size and number of
4537 // elements for floating point vectors.
4538 if (lType->isIntegerType())
4539 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004540
Nate Begemanc5f0f652008-07-14 18:02:46 +00004541 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004542 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004543 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004544 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004545 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004546 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4547
Mike Stump9afab102009-02-19 03:04:26 +00004548 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004549 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004550 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4551}
4552
Chris Lattner4b009652007-07-25 00:24:17 +00004553inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004554 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004555{
4556 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004557 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004558
Steve Naroff8f708362007-08-24 19:07:16 +00004559 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004560
Chris Lattner4b009652007-07-25 00:24:17 +00004561 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004562 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004563 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004564}
4565
4566inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004567 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004568{
4569 UsualUnaryConversions(lex);
4570 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004571
Eli Friedmanbea3f842008-05-13 20:16:47 +00004572 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004573 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004574 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004575}
4576
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004577/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4578/// is a read-only property; return true if so. A readonly property expression
4579/// depends on various declarations and thus must be treated specially.
4580///
Mike Stump9afab102009-02-19 03:04:26 +00004581static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004582{
4583 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4584 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4585 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4586 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004587 if (const ObjCObjectPointerType *OPT =
4588 BaseType->getAsObjCInterfacePointerType())
4589 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4590 if (S.isPropertyReadonly(PDecl, IFace))
4591 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004592 }
4593 }
4594 return false;
4595}
4596
Chris Lattner4c2642c2008-11-18 01:22:49 +00004597/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4598/// emit an error and return true. If so, return false.
4599static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004600 SourceLocation OrigLoc = Loc;
4601 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4602 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004603 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4604 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004605 if (IsLV == Expr::MLV_Valid)
4606 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004607
Chris Lattner4c2642c2008-11-18 01:22:49 +00004608 unsigned Diag = 0;
4609 bool NeedType = false;
4610 switch (IsLV) { // C99 6.5.16p2
4611 default: assert(0 && "Unknown result from isModifiableLvalue!");
4612 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004613 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004614 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4615 NeedType = true;
4616 break;
Mike Stump9afab102009-02-19 03:04:26 +00004617 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004618 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4619 NeedType = true;
4620 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004621 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004622 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4623 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004624 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004625 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4626 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004627 case Expr::MLV_IncompleteType:
4628 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004629 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004630 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4631 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004632 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004633 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4634 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004635 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004636 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4637 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004638 case Expr::MLV_ReadonlyProperty:
4639 Diag = diag::error_readonly_property_assignment;
4640 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004641 case Expr::MLV_NoSetterProperty:
4642 Diag = diag::error_nosetter_property_assignment;
4643 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004644 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004645
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004646 SourceRange Assign;
4647 if (Loc != OrigLoc)
4648 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004649 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004650 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004651 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004652 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004653 return true;
4654}
4655
4656
4657
4658// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004659QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4660 SourceLocation Loc,
4661 QualType CompoundType) {
4662 // Verify that LHS is a modifiable lvalue, and emit error if not.
4663 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004664 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004665
4666 QualType LHSType = LHS->getType();
4667 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004668
Chris Lattner005ed752008-01-04 18:04:52 +00004669 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004670 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004671 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004672 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004673 // Special case of NSObject attributes on c-style pointer types.
4674 if (ConvTy == IncompatiblePointer &&
4675 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004676 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004677 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004678 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004679 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004680
Chris Lattner34c85082008-08-21 18:04:13 +00004681 // If the RHS is a unary plus or minus, check to see if they = and + are
4682 // right next to each other. If so, the user may have typo'd "x =+ 4"
4683 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004684 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004685 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4686 RHSCheck = ICE->getSubExpr();
4687 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4688 if ((UO->getOpcode() == UnaryOperator::Plus ||
4689 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004690 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004691 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004692 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4693 // And there is a space or other character before the subexpr of the
4694 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004695 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4696 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004697 Diag(Loc, diag::warn_not_compound_assign)
4698 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4699 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004700 }
Chris Lattner34c85082008-08-21 18:04:13 +00004701 }
4702 } else {
4703 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004704 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004705 }
Chris Lattner005ed752008-01-04 18:04:52 +00004706
Chris Lattner1eafdea2008-11-18 01:30:42 +00004707 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4708 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004709 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004710
Chris Lattner4b009652007-07-25 00:24:17 +00004711 // C99 6.5.16p3: The type of an assignment expression is the type of the
4712 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004713 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004714 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4715 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004716 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004717 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004718 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004719}
4720
Chris Lattner1eafdea2008-11-18 01:30:42 +00004721// C99 6.5.17
4722QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004723 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004724 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004725
4726 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4727 // incomplete in C++).
4728
Chris Lattner1eafdea2008-11-18 01:30:42 +00004729 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004730}
4731
4732/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4733/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004734QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4735 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004736 if (Op->isTypeDependent())
4737 return Context.DependentTy;
4738
Chris Lattnere65182c2008-11-21 07:05:48 +00004739 QualType ResType = Op->getType();
4740 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004741
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004742 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4743 // Decrement of bool is not allowed.
4744 if (!isInc) {
4745 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4746 return QualType();
4747 }
4748 // Increment of bool sets it to true, but is deprecated.
4749 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4750 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004751 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004752 } else if (ResType->isAnyPointerType()) {
4753 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004754
Chris Lattnere65182c2008-11-21 07:05:48 +00004755 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004756 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004757 if (getLangOptions().CPlusPlus) {
4758 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4759 << Op->getSourceRange();
4760 return QualType();
4761 }
4762
4763 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004764 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004765 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004766 if (getLangOptions().CPlusPlus) {
4767 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4768 << Op->getType() << Op->getSourceRange();
4769 return QualType();
4770 }
4771
4772 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004773 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004774 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004775 diag::err_typecheck_arithmetic_incomplete_type,
4776 Op->getSourceRange(), SourceRange(),
4777 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004778 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004779 // Diagnose bad cases where we step over interface counts.
4780 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4781 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4782 << PointeeTy << Op->getSourceRange();
4783 return QualType();
4784 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004785 } else if (ResType->isComplexType()) {
4786 // C99 does not support ++/-- on complex types, we allow as an extension.
4787 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004788 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004789 } else {
4790 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004791 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004792 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004793 }
Mike Stump9afab102009-02-19 03:04:26 +00004794 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004795 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004796 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004797 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004798 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004799}
4800
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004801/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004802/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004803/// where the declaration is needed for type checking. We only need to
4804/// handle cases when the expression references a function designator
4805/// or is an lvalue. Here are some examples:
4806/// - &(x) => x
4807/// - &*****f => f for f a function designator.
4808/// - &s.xx => s
4809/// - &s.zz[1].yy -> s, if zz is an array
4810/// - *(x + 1) -> x, if x is an array
4811/// - &"123"[2] -> 0
4812/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004813static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004814 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004815 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004816 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004817 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004818 case Stmt::MemberExprClass:
Douglas Gregore399ad42009-08-26 22:36:53 +00004819 case Stmt::CXXQualifiedMemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004820 // If this is an arrow operator, the address is an offset from
4821 // the base's value, so the object the base refers to is
4822 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004823 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004824 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004825 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004826 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004827 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004828 // FIXME: This code shouldn't be necessary! We should catch the implicit
4829 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004830 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4831 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4832 if (ICE->getSubExpr()->getType()->isArrayType())
4833 return getPrimaryDecl(ICE->getSubExpr());
4834 }
4835 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004836 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004837 case Stmt::UnaryOperatorClass: {
4838 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004839
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004840 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004841 case UnaryOperator::Real:
4842 case UnaryOperator::Imag:
4843 case UnaryOperator::Extension:
4844 return getPrimaryDecl(UO->getSubExpr());
4845 default:
4846 return 0;
4847 }
4848 }
Chris Lattner4b009652007-07-25 00:24:17 +00004849 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004850 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004851 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004852 // If the result of an implicit cast is an l-value, we care about
4853 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004854 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004855 default:
4856 return 0;
4857 }
4858}
4859
4860/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004861/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004862/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004863/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004864/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004865/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004866/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004867QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004868 // Make sure to ignore parentheses in subsequent checks
4869 op = op->IgnoreParens();
4870
Douglas Gregore6be68a2008-12-17 22:52:20 +00004871 if (op->isTypeDependent())
4872 return Context.DependentTy;
4873
Steve Naroff9c6c3592008-01-13 17:10:08 +00004874 if (getLangOptions().C99) {
4875 // Implement C99-only parts of addressof rules.
4876 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4877 if (uOp->getOpcode() == UnaryOperator::Deref)
4878 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4879 // (assuming the deref expression is valid).
4880 return uOp->getSubExpr()->getType();
4881 }
4882 // Technically, there should be a check for array subscript
4883 // expressions here, but the result of one is always an lvalue anyway.
4884 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004885 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004886 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004887
Eli Friedman14ab4c42009-05-16 23:27:50 +00004888 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4889 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004890 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004891 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004892 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004893 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4894 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004895 return QualType();
4896 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004897 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004898 // The operand cannot be a bit-field
4899 Diag(OpLoc, diag::err_typecheck_address_of)
4900 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004901 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004902 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4903 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004904 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004905 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004906 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004907 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004908 } else if (isa<ObjCPropertyRefExpr>(op)) {
4909 // cannot take address of a property expression.
4910 Diag(OpLoc, diag::err_typecheck_address_of)
4911 << "property expression" << op->getSourceRange();
4912 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004913 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004914 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004915 // with the register storage-class specifier.
4916 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4917 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004918 Diag(OpLoc, diag::err_typecheck_address_of)
4919 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004920 return QualType();
4921 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004922 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4923 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004924 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004925 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004926 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004927 // Could be a pointer to member, though, if there is an explicit
4928 // scope qualifier for the class.
4929 if (isa<QualifiedDeclRefExpr>(op)) {
4930 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004931 if (Ctx && Ctx->isRecord()) {
4932 if (FD->getType()->isReferenceType()) {
4933 Diag(OpLoc,
4934 diag::err_cannot_form_pointer_to_member_of_reference_type)
4935 << FD->getDeclName() << FD->getType();
4936 return QualType();
4937 }
4938
Sebastian Redl0c9da212009-02-03 20:19:35 +00004939 return Context.getMemberPointerType(op->getType(),
4940 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004941 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004942 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004943 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004944 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004945 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004946 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4947 return Context.getMemberPointerType(op->getType(),
4948 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4949 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004950 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004951 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004952
Eli Friedman14ab4c42009-05-16 23:27:50 +00004953 if (lval == Expr::LV_IncompleteVoidType) {
4954 // Taking the address of a void variable is technically illegal, but we
4955 // allow it in cases which are otherwise valid.
4956 // Example: "extern void x; void* y = &x;".
4957 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4958 }
4959
Chris Lattner4b009652007-07-25 00:24:17 +00004960 // If the operand has type "type", the result has type "pointer to type".
4961 return Context.getPointerType(op->getType());
4962}
4963
Chris Lattnerda5c0872008-11-23 09:13:29 +00004964QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004965 if (Op->isTypeDependent())
4966 return Context.DependentTy;
4967
Chris Lattnerda5c0872008-11-23 09:13:29 +00004968 UsualUnaryConversions(Op);
4969 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004970
Chris Lattnerda5c0872008-11-23 09:13:29 +00004971 // Note that per both C89 and C99, this is always legal, even if ptype is an
4972 // incomplete type or void. It would be possible to warn about dereferencing
4973 // a void pointer, but it's completely well-defined, and such a warning is
4974 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004975 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004976 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004977
Steve Naroff329ec222009-07-10 23:34:53 +00004978 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4979 return OPT->getPointeeType();
4980
Chris Lattner77d52da2008-11-20 06:06:08 +00004981 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004982 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004983 return QualType();
4984}
4985
4986static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4987 tok::TokenKind Kind) {
4988 BinaryOperator::Opcode Opc;
4989 switch (Kind) {
4990 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004991 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4992 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004993 case tok::star: Opc = BinaryOperator::Mul; break;
4994 case tok::slash: Opc = BinaryOperator::Div; break;
4995 case tok::percent: Opc = BinaryOperator::Rem; break;
4996 case tok::plus: Opc = BinaryOperator::Add; break;
4997 case tok::minus: Opc = BinaryOperator::Sub; break;
4998 case tok::lessless: Opc = BinaryOperator::Shl; break;
4999 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5000 case tok::lessequal: Opc = BinaryOperator::LE; break;
5001 case tok::less: Opc = BinaryOperator::LT; break;
5002 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5003 case tok::greater: Opc = BinaryOperator::GT; break;
5004 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5005 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5006 case tok::amp: Opc = BinaryOperator::And; break;
5007 case tok::caret: Opc = BinaryOperator::Xor; break;
5008 case tok::pipe: Opc = BinaryOperator::Or; break;
5009 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5010 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5011 case tok::equal: Opc = BinaryOperator::Assign; break;
5012 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5013 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5014 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5015 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5016 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5017 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5018 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5019 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5020 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5021 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5022 case tok::comma: Opc = BinaryOperator::Comma; break;
5023 }
5024 return Opc;
5025}
5026
5027static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5028 tok::TokenKind Kind) {
5029 UnaryOperator::Opcode Opc;
5030 switch (Kind) {
5031 default: assert(0 && "Unknown unary op!");
5032 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5033 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5034 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5035 case tok::star: Opc = UnaryOperator::Deref; break;
5036 case tok::plus: Opc = UnaryOperator::Plus; break;
5037 case tok::minus: Opc = UnaryOperator::Minus; break;
5038 case tok::tilde: Opc = UnaryOperator::Not; break;
5039 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005040 case tok::kw___real: Opc = UnaryOperator::Real; break;
5041 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5042 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5043 }
5044 return Opc;
5045}
5046
Douglas Gregord7f915e2008-11-06 23:29:22 +00005047/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5048/// operator @p Opc at location @c TokLoc. This routine only supports
5049/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005050Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5051 unsigned Op,
5052 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005053 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005054 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005055 // The following two variables are used for compound assignment operators
5056 QualType CompLHSTy; // Type of LHS after promotions for computation
5057 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005058
5059 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005060 case BinaryOperator::Assign:
5061 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5062 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005063 case BinaryOperator::PtrMemD:
5064 case BinaryOperator::PtrMemI:
5065 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5066 Opc == BinaryOperator::PtrMemI);
5067 break;
5068 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005069 case BinaryOperator::Div:
5070 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5071 break;
5072 case BinaryOperator::Rem:
5073 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5074 break;
5075 case BinaryOperator::Add:
5076 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5077 break;
5078 case BinaryOperator::Sub:
5079 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5080 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005081 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005082 case BinaryOperator::Shr:
5083 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5084 break;
5085 case BinaryOperator::LE:
5086 case BinaryOperator::LT:
5087 case BinaryOperator::GE:
5088 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005089 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005090 break;
5091 case BinaryOperator::EQ:
5092 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005093 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005094 break;
5095 case BinaryOperator::And:
5096 case BinaryOperator::Xor:
5097 case BinaryOperator::Or:
5098 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5099 break;
5100 case BinaryOperator::LAnd:
5101 case BinaryOperator::LOr:
5102 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5103 break;
5104 case BinaryOperator::MulAssign:
5105 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005106 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5107 CompLHSTy = CompResultTy;
5108 if (!CompResultTy.isNull())
5109 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005110 break;
5111 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005112 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5113 CompLHSTy = CompResultTy;
5114 if (!CompResultTy.isNull())
5115 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005116 break;
5117 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005118 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5119 if (!CompResultTy.isNull())
5120 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005121 break;
5122 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005123 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5124 if (!CompResultTy.isNull())
5125 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005126 break;
5127 case BinaryOperator::ShlAssign:
5128 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005129 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5130 CompLHSTy = CompResultTy;
5131 if (!CompResultTy.isNull())
5132 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005133 break;
5134 case BinaryOperator::AndAssign:
5135 case BinaryOperator::XorAssign:
5136 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005137 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5138 CompLHSTy = CompResultTy;
5139 if (!CompResultTy.isNull())
5140 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005141 break;
5142 case BinaryOperator::Comma:
5143 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5144 break;
5145 }
5146 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005147 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005148 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005149 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5150 else
5151 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005152 CompLHSTy, CompResultTy,
5153 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005154}
5155
Chris Lattner4b009652007-07-25 00:24:17 +00005156// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005157Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5158 tok::TokenKind Kind,
5159 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005160 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005161 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005162
Steve Naroff87d58b42007-09-16 03:34:24 +00005163 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5164 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005165
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005166 if (getLangOptions().CPlusPlus &&
5167 (lhs->getType()->isOverloadableType() ||
5168 rhs->getType()->isOverloadableType())) {
5169 // Find all of the overloaded operators visible from this
5170 // point. We perform both an operator-name lookup from the local
5171 // scope and an argument-dependent lookup based on the types of
5172 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005173 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005174 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5175 if (OverOp != OO_None) {
5176 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5177 Functions);
5178 Expr *Args[2] = { lhs, rhs };
5179 DeclarationName OpName
5180 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5181 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005182 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005183
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005184 // Build the (potentially-overloaded, potentially-dependent)
5185 // binary operation.
5186 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005187 }
5188
Douglas Gregord7f915e2008-11-06 23:29:22 +00005189 // Build a built-in binary operation.
5190 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005191}
5192
Douglas Gregorc78182d2009-03-13 23:49:33 +00005193Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5194 unsigned OpcIn,
5195 ExprArg InputArg) {
5196 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005197
Mike Stumpe127ae32009-05-16 07:39:55 +00005198 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005199 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005200 QualType resultType;
5201 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005202 case UnaryOperator::OffsetOf:
5203 assert(false && "Invalid unary operator");
5204 break;
5205
Chris Lattner4b009652007-07-25 00:24:17 +00005206 case UnaryOperator::PreInc:
5207 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005208 case UnaryOperator::PostInc:
5209 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005210 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005211 Opc == UnaryOperator::PreInc ||
5212 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005213 break;
Mike Stump9afab102009-02-19 03:04:26 +00005214 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005215 resultType = CheckAddressOfOperand(Input, OpLoc);
5216 break;
Mike Stump9afab102009-02-19 03:04:26 +00005217 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005218 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005219 resultType = CheckIndirectionOperand(Input, OpLoc);
5220 break;
5221 case UnaryOperator::Plus:
5222 case UnaryOperator::Minus:
5223 UsualUnaryConversions(Input);
5224 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005225 if (resultType->isDependentType())
5226 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005227 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5228 break;
5229 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5230 resultType->isEnumeralType())
5231 break;
5232 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5233 Opc == UnaryOperator::Plus &&
5234 resultType->isPointerType())
5235 break;
5236
Sebastian Redl8b769972009-01-19 00:08:26 +00005237 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5238 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005239 case UnaryOperator::Not: // bitwise complement
5240 UsualUnaryConversions(Input);
5241 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005242 if (resultType->isDependentType())
5243 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005244 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5245 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5246 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005247 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005248 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005249 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005250 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5251 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005252 break;
5253 case UnaryOperator::LNot: // logical negation
5254 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5255 DefaultFunctionArrayConversion(Input);
5256 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005257 if (resultType->isDependentType())
5258 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005259 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005260 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5261 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005262 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005263 // In C++, it's bool. C++ 5.3.1p8
5264 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005265 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005266 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005267 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005268 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005269 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005270 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005271 resultType = Input->getType();
5272 break;
5273 }
5274 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005275 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005276
5277 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005278 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005279}
5280
Douglas Gregorc78182d2009-03-13 23:49:33 +00005281// Unary Operators. 'Tok' is the token for the operator.
5282Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5283 tok::TokenKind Op, ExprArg input) {
5284 Expr *Input = (Expr*)input.get();
5285 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5286
5287 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5288 // Find all of the overloaded operators visible from this
5289 // point. We perform both an operator-name lookup from the local
5290 // scope and an argument-dependent lookup based on the types of
5291 // the arguments.
5292 FunctionSet Functions;
5293 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5294 if (OverOp != OO_None) {
5295 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5296 Functions);
5297 DeclarationName OpName
5298 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5299 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5300 }
5301
5302 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5303 }
5304
5305 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5306}
5307
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005308/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005309Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5310 SourceLocation LabLoc,
5311 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005312 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005313 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005314
Daniel Dunbar879788d2008-08-04 16:51:22 +00005315 // If we haven't seen this label yet, create a forward reference. It
5316 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005317 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005318 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005319
Chris Lattner4b009652007-07-25 00:24:17 +00005320 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005321 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5322 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005323}
5324
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005325Sema::OwningExprResult
5326Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5327 SourceLocation RPLoc) { // "({..})"
5328 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005329 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5330 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5331
Eli Friedmanbc941e12009-01-24 23:09:00 +00005332 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005333 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005334 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005335
Chris Lattner4b009652007-07-25 00:24:17 +00005336 // FIXME: there are a variety of strange constraints to enforce here, for
5337 // example, it is not possible to goto into a stmt expression apparently.
5338 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005339
Chris Lattner4b009652007-07-25 00:24:17 +00005340 // If there are sub stmts in the compound stmt, take the type of the last one
5341 // as the type of the stmtexpr.
5342 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005343
Chris Lattner200964f2008-07-26 19:51:01 +00005344 if (!Compound->body_empty()) {
5345 Stmt *LastStmt = Compound->body_back();
5346 // If LastStmt is a label, skip down through into the body.
5347 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5348 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005349
Chris Lattner200964f2008-07-26 19:51:01 +00005350 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005351 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005352 }
Mike Stump9afab102009-02-19 03:04:26 +00005353
Eli Friedman2b128322009-03-23 00:24:07 +00005354 // FIXME: Check that expression type is complete/non-abstract; statement
5355 // expressions are not lvalues.
5356
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005357 substmt.release();
5358 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005359}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005360
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005361Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5362 SourceLocation BuiltinLoc,
5363 SourceLocation TypeLoc,
5364 TypeTy *argty,
5365 OffsetOfComponent *CompPtr,
5366 unsigned NumComponents,
5367 SourceLocation RPLoc) {
5368 // FIXME: This function leaks all expressions in the offset components on
5369 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005370 // FIXME: Preserve type source info.
5371 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005372 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005373
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005374 bool Dependent = ArgTy->isDependentType();
5375
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005376 // We must have at least one component that refers to the type, and the first
5377 // one is known to be a field designator. Verify that the ArgTy represents
5378 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005379 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005380 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005381
Eli Friedman2b128322009-03-23 00:24:07 +00005382 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5383 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005384
Eli Friedman342d9432009-02-27 06:44:11 +00005385 // Otherwise, create a null pointer as the base, and iteratively process
5386 // the offsetof designators.
5387 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5388 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005389 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005390 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005391
Chris Lattnerb37522e2007-08-31 21:49:13 +00005392 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5393 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005394 // FIXME: This diagnostic isn't actually visible because the location is in
5395 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005396 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005397 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5398 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005399
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005400 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005401 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005402
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005403 // FIXME: Dependent case loses a lot of information here. And probably
5404 // leaks like a sieve.
5405 for (unsigned i = 0; i != NumComponents; ++i) {
5406 const OffsetOfComponent &OC = CompPtr[i];
5407 if (OC.isBrackets) {
5408 // Offset of an array sub-field. TODO: Should we allow vector elements?
5409 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5410 if (!AT) {
5411 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005412 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5413 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005414 }
5415
5416 // FIXME: C++: Verify that operator[] isn't overloaded.
5417
Eli Friedman342d9432009-02-27 06:44:11 +00005418 // Promote the array so it looks more like a normal array subscript
5419 // expression.
5420 DefaultFunctionArrayConversion(Res);
5421
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005422 // C99 6.5.2.1p1
5423 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005424 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005425 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005426 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005427 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005428 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005429
5430 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5431 OC.LocEnd);
5432 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005433 }
Mike Stump9afab102009-02-19 03:04:26 +00005434
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005435 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005436 if (!RC) {
5437 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005438 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5439 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005440 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005441
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005442 // Get the decl corresponding to this.
5443 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005444 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005445 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005446 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5447 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5448 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005449 DidWarnAboutNonPOD = true;
5450 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005451 }
5452
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005453 FieldDecl *MemberDecl
5454 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5455 LookupMemberName)
5456 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005457 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005458 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005459 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5460 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005461
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005462 // FIXME: C++: Verify that MemberDecl isn't a static field.
5463 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005464 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005465 Res = BuildAnonymousStructUnionMemberReference(
5466 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005467 } else {
5468 // MemberDecl->getType() doesn't get the right qualifiers, but it
5469 // doesn't matter here.
5470 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5471 MemberDecl->getType().getNonReferenceType());
5472 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005473 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005474 }
Mike Stump9afab102009-02-19 03:04:26 +00005475
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005476 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5477 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005478}
5479
5480
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005481Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5482 TypeTy *arg1,TypeTy *arg2,
5483 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005484 // FIXME: Preserve type source info.
5485 QualType argT1 = GetTypeFromParser(arg1);
5486 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005487
Steve Naroff63bad2d2007-08-01 22:05:33 +00005488 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005489
Douglas Gregore6211502009-05-19 22:28:02 +00005490 if (getLangOptions().CPlusPlus) {
5491 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5492 << SourceRange(BuiltinLoc, RPLoc);
5493 return ExprError();
5494 }
5495
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005496 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5497 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005498}
5499
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005500Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5501 ExprArg cond,
5502 ExprArg expr1, ExprArg expr2,
5503 SourceLocation RPLoc) {
5504 Expr *CondExpr = static_cast<Expr*>(cond.get());
5505 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5506 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005507
Steve Naroff93c53012007-08-03 21:21:27 +00005508 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5509
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005510 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005511 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005512 resType = Context.DependentTy;
5513 } else {
5514 // The conditional expression is required to be a constant expression.
5515 llvm::APSInt condEval(32);
5516 SourceLocation ExpLoc;
5517 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005518 return ExprError(Diag(ExpLoc,
5519 diag::err_typecheck_choose_expr_requires_constant)
5520 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005521
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005522 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5523 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5524 }
5525
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005526 cond.release(); expr1.release(); expr2.release();
5527 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5528 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005529}
5530
Steve Naroff52a81c02008-09-03 18:15:37 +00005531//===----------------------------------------------------------------------===//
5532// Clang Extensions.
5533//===----------------------------------------------------------------------===//
5534
5535/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005536void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005537 // Analyze block parameters.
5538 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005539
Steve Naroff52a81c02008-09-03 18:15:37 +00005540 // Add BSI to CurBlock.
5541 BSI->PrevBlockInfo = CurBlock;
5542 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005543
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005544 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005545 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005546 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005547 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005548 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5549 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005550
Steve Naroff52059382008-10-10 01:28:17 +00005551 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005552 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005553}
5554
Mike Stumpc1fddff2009-02-04 22:31:32 +00005555void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005556 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005557
5558 if (ParamInfo.getNumTypeObjects() == 0
5559 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005560 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005561 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5562
Mike Stump458287d2009-04-28 01:10:27 +00005563 if (T->isArrayType()) {
5564 Diag(ParamInfo.getSourceRange().getBegin(),
5565 diag::err_block_returns_array);
5566 return;
5567 }
5568
Mike Stumpc1fddff2009-02-04 22:31:32 +00005569 // The parameter list is optional, if there was none, assume ().
5570 if (!T->isFunctionType())
5571 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5572
5573 CurBlock->hasPrototype = true;
5574 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005575 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005576 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005577 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005578 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005579 // FIXME: remove the attribute.
5580 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005581 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5582
5583 // Do not allow returning a objc interface by-value.
5584 if (RetTy->isObjCInterfaceType()) {
5585 Diag(ParamInfo.getSourceRange().getBegin(),
5586 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5587 return;
5588 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005589 return;
5590 }
5591
Steve Naroff52a81c02008-09-03 18:15:37 +00005592 // Analyze arguments to block.
5593 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5594 "Not a function declarator!");
5595 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005596
Steve Naroff52059382008-10-10 01:28:17 +00005597 CurBlock->hasPrototype = FTI.hasPrototype;
5598 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005599
Steve Naroff52a81c02008-09-03 18:15:37 +00005600 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5601 // no arguments, not a function that takes a single void argument.
5602 if (FTI.hasPrototype &&
5603 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005604 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5605 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005606 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005607 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005608 } else if (FTI.hasPrototype) {
5609 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005610 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005611 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005612 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005613 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005614 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005615 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005616 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005617 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5618 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5619 // If this has an identifier, add it to the scope stack.
5620 if ((*AI)->getIdentifier())
5621 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005622
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005623 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005624 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005625 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005626 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005627 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005628 // FIXME: remove the attribute.
5629 }
5630
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005631 // Analyze the return type.
5632 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5633 QualType RetTy = T->getAsFunctionType()->getResultType();
5634
5635 // Do not allow returning a objc interface by-value.
5636 if (RetTy->isObjCInterfaceType()) {
5637 Diag(ParamInfo.getSourceRange().getBegin(),
5638 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5639 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005640 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005641}
5642
5643/// ActOnBlockError - If there is an error parsing a block, this callback
5644/// is invoked to pop the information about the block from the action impl.
5645void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5646 // Ensure that CurBlock is deleted.
5647 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005648
Chris Lattnere7765e12009-04-19 05:28:12 +00005649 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5650
Steve Naroff52a81c02008-09-03 18:15:37 +00005651 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005652 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005653 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005654 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005655}
5656
5657/// ActOnBlockStmtExpr - This is called when the body of a block statement
5658/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005659Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5660 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005661 // If blocks are disabled, emit an error.
5662 if (!LangOpts.Blocks)
5663 Diag(CaretLoc, diag::err_blocks_disable);
5664
Steve Naroff52a81c02008-09-03 18:15:37 +00005665 // Ensure that CurBlock is deleted.
5666 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005667
Steve Naroff52059382008-10-10 01:28:17 +00005668 PopDeclContext();
5669
Steve Naroff52a81c02008-09-03 18:15:37 +00005670 // Pop off CurBlock, handle nested blocks.
5671 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005672
Steve Naroff52a81c02008-09-03 18:15:37 +00005673 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005674 if (!BSI->ReturnType.isNull())
5675 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005676
Steve Naroff52a81c02008-09-03 18:15:37 +00005677 llvm::SmallVector<QualType, 8> ArgTypes;
5678 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5679 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005680
Mike Stump8e288f42009-07-28 22:04:01 +00005681 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005682 QualType BlockTy;
5683 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005684 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5685 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005686 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005687 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005688 BSI->isVariadic, 0, false, false, 0, 0,
5689 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005690
Eli Friedman2b128322009-03-23 00:24:07 +00005691 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005692 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005693 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005694
Chris Lattnere7765e12009-04-19 05:28:12 +00005695 // If needed, diagnose invalid gotos and switches in the block.
5696 if (CurFunctionNeedsScopeChecking)
5697 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5698 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5699
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005700 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005701 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005702 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5703 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005704}
5705
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005706Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5707 ExprArg expr, TypeTy *type,
5708 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005709 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005710 Expr *E = static_cast<Expr*>(expr.get());
5711 Expr *OrigExpr = E;
5712
Anders Carlsson36760332007-10-15 20:28:48 +00005713 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005714
5715 // Get the va_list type
5716 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005717 if (VaListType->isArrayType()) {
5718 // Deal with implicit array decay; for example, on x86-64,
5719 // va_list is an array, but it's supposed to decay to
5720 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005721 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005722 // Make sure the input expression also decays appropriately.
5723 UsualUnaryConversions(E);
5724 } else {
5725 // Otherwise, the va_list argument must be an l-value because
5726 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005727 if (!E->isTypeDependent() &&
5728 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005729 return ExprError();
5730 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005731
Douglas Gregor25990972009-05-19 23:10:31 +00005732 if (!E->isTypeDependent() &&
5733 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005734 return ExprError(Diag(E->getLocStart(),
5735 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005736 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005737 }
Mike Stump9afab102009-02-19 03:04:26 +00005738
Eli Friedman2b128322009-03-23 00:24:07 +00005739 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005740 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005741
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005742 expr.release();
5743 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5744 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005745}
5746
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005747Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005748 // The type of __null will be int or long, depending on the size of
5749 // pointers on the target.
5750 QualType Ty;
5751 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5752 Ty = Context.IntTy;
5753 else
5754 Ty = Context.LongTy;
5755
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005756 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005757}
5758
Chris Lattner005ed752008-01-04 18:04:52 +00005759bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5760 SourceLocation Loc,
5761 QualType DstType, QualType SrcType,
5762 Expr *SrcExpr, const char *Flavor) {
5763 // Decode the result (notice that AST's are still created for extensions).
5764 bool isInvalid = false;
5765 unsigned DiagKind;
5766 switch (ConvTy) {
5767 default: assert(0 && "Unknown conversion type");
5768 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005769 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005770 DiagKind = diag::ext_typecheck_convert_pointer_int;
5771 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005772 case IntToPointer:
5773 DiagKind = diag::ext_typecheck_convert_int_pointer;
5774 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005775 case IncompatiblePointer:
5776 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5777 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005778 case IncompatiblePointerSign:
5779 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5780 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005781 case FunctionVoidPointer:
5782 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5783 break;
5784 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005785 // If the qualifiers lost were because we were applying the
5786 // (deprecated) C++ conversion from a string literal to a char*
5787 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5788 // Ideally, this check would be performed in
5789 // CheckPointerTypesForAssignment. However, that would require a
5790 // bit of refactoring (so that the second argument is an
5791 // expression, rather than a type), which should be done as part
5792 // of a larger effort to fix CheckPointerTypesForAssignment for
5793 // C++ semantics.
5794 if (getLangOptions().CPlusPlus &&
5795 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5796 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005797 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5798 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005799 case IntToBlockPointer:
5800 DiagKind = diag::err_int_to_block_pointer;
5801 break;
5802 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005803 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005804 break;
Steve Naroff19608432008-10-14 22:18:38 +00005805 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005806 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005807 // it can give a more specific diagnostic.
5808 DiagKind = diag::warn_incompatible_qualified_id;
5809 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005810 case IncompatibleVectors:
5811 DiagKind = diag::warn_incompatible_vectors;
5812 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005813 case Incompatible:
5814 DiagKind = diag::err_typecheck_convert_incompatible;
5815 isInvalid = true;
5816 break;
5817 }
Mike Stump9afab102009-02-19 03:04:26 +00005818
Chris Lattner271d4c22008-11-24 05:29:24 +00005819 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5820 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005821 return isInvalid;
5822}
Anders Carlssond5201b92008-11-30 19:50:32 +00005823
Chris Lattnereec8ae22009-04-25 21:59:05 +00005824bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005825 llvm::APSInt ICEResult;
5826 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5827 if (Result)
5828 *Result = ICEResult;
5829 return false;
5830 }
5831
Anders Carlssond5201b92008-11-30 19:50:32 +00005832 Expr::EvalResult EvalResult;
5833
Mike Stump9afab102009-02-19 03:04:26 +00005834 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005835 EvalResult.HasSideEffects) {
5836 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5837
5838 if (EvalResult.Diag) {
5839 // We only show the note if it's not the usual "invalid subexpression"
5840 // or if it's actually in a subexpression.
5841 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5842 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5843 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5844 }
Mike Stump9afab102009-02-19 03:04:26 +00005845
Anders Carlssond5201b92008-11-30 19:50:32 +00005846 return true;
5847 }
5848
Eli Friedmance329412009-04-25 22:26:58 +00005849 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5850 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005851
Eli Friedmance329412009-04-25 22:26:58 +00005852 if (EvalResult.Diag &&
5853 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5854 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005855
Anders Carlssond5201b92008-11-30 19:50:32 +00005856 if (Result)
5857 *Result = EvalResult.Val.getInt();
5858 return false;
5859}
Douglas Gregor98189262009-06-19 23:52:42 +00005860
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005861Sema::ExpressionEvaluationContext
5862Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5863 // Introduce a new set of potentially referenced declarations to the stack.
5864 if (NewContext == PotentiallyPotentiallyEvaluated)
5865 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5866
5867 std::swap(ExprEvalContext, NewContext);
5868 return NewContext;
5869}
5870
5871void
5872Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5873 ExpressionEvaluationContext NewContext) {
5874 ExprEvalContext = NewContext;
5875
5876 if (OldContext == PotentiallyPotentiallyEvaluated) {
5877 // Mark any remaining declarations in the current position of the stack
5878 // as "referenced". If they were not meant to be referenced, semantic
5879 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5880 PotentiallyReferencedDecls RemainingDecls;
5881 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5882 PotentiallyReferencedDeclStack.pop_back();
5883
5884 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5885 IEnd = RemainingDecls.end();
5886 I != IEnd; ++I)
5887 MarkDeclarationReferenced(I->first, I->second);
5888 }
5889}
Douglas Gregor98189262009-06-19 23:52:42 +00005890
5891/// \brief Note that the given declaration was referenced in the source code.
5892///
5893/// This routine should be invoke whenever a given declaration is referenced
5894/// in the source code, and where that reference occurred. If this declaration
5895/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5896/// C99 6.9p3), then the declaration will be marked as used.
5897///
5898/// \param Loc the location where the declaration was referenced.
5899///
5900/// \param D the declaration that has been referenced by the source code.
5901void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5902 assert(D && "No declaration?");
5903
Douglas Gregorcad27f62009-06-22 23:06:13 +00005904 if (D->isUsed())
5905 return;
5906
Douglas Gregor98189262009-06-19 23:52:42 +00005907 // Mark a parameter declaration "used", regardless of whether we're in a
5908 // template or not.
5909 if (isa<ParmVarDecl>(D))
5910 D->setUsed(true);
5911
5912 // Do not mark anything as "used" within a dependent context; wait for
5913 // an instantiation.
5914 if (CurContext->isDependentContext())
5915 return;
5916
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005917 switch (ExprEvalContext) {
5918 case Unevaluated:
5919 // We are in an expression that is not potentially evaluated; do nothing.
5920 return;
5921
5922 case PotentiallyEvaluated:
5923 // We are in a potentially-evaluated expression, so this declaration is
5924 // "used"; handle this below.
5925 break;
5926
5927 case PotentiallyPotentiallyEvaluated:
5928 // We are in an expression that may be potentially evaluated; queue this
5929 // declaration reference until we know whether the expression is
5930 // potentially evaluated.
5931 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5932 return;
5933 }
5934
Douglas Gregor98189262009-06-19 23:52:42 +00005935 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005936 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005937 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005938 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5939 if (!Constructor->isUsed())
5940 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005941 } else if (Constructor->isImplicit() &&
5942 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005943 if (!Constructor->isUsed())
5944 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5945 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005946 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5947 if (Destructor->isImplicit() && !Destructor->isUsed())
5948 DefineImplicitDestructor(Loc, Destructor);
5949
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005950 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5951 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5952 MethodDecl->getOverloadedOperator() == OO_Equal) {
5953 if (!MethodDecl->isUsed())
5954 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5955 }
5956 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005957 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005958 // Implicit instantiation of function templates and member functions of
5959 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005960 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005961 // FIXME: distinguish between implicit instantiations of function
5962 // templates and explicit specializations (the latter don't get
5963 // instantiated, naturally).
5964 if (Function->getInstantiatedFromMemberFunction() ||
5965 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005966 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005967 }
5968
5969
Douglas Gregor98189262009-06-19 23:52:42 +00005970 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005971 Function->setUsed(true);
5972 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005973 }
Douglas Gregor98189262009-06-19 23:52:42 +00005974
5975 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005976 // Implicit instantiation of static data members of class templates.
5977 // FIXME: distinguish between implicit instantiations (which we need to
5978 // actually instantiate) and explicit specializations.
5979 if (Var->isStaticDataMember() &&
5980 Var->getInstantiatedFromStaticDataMember())
5981 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5982
Douglas Gregor98189262009-06-19 23:52:42 +00005983 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005984
Douglas Gregor98189262009-06-19 23:52:42 +00005985 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005986 return;
5987}
Douglas Gregor98189262009-06-19 23:52:42 +00005988}
5989