blob: 43ed22a48b959a6768540d5bf646facb2ac8f4f7 [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
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000090// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
91// will warn if the resulting type is not a POD type.
92void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
93
94{
95 DefaultArgumentPromotion(Expr);
96
97 if (!Expr->getType()->isPODType()) {
98 Diag(Expr->getLocStart(),
99 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
100 Expr->getType() << CT;
101 }
102}
103
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105/// UsualArithmeticConversions - Performs various conversions that are common to
106/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
107/// routine returns the first non-arithmetic type found. The client is
108/// responsible for emitting appropriate error diagnostics.
109/// FIXME: verify the conversion rules for "complex int" are consistent with
110/// GCC.
111QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
112 bool isCompAssign) {
113 if (!isCompAssign) {
114 UsualUnaryConversions(lhsExpr);
115 UsualUnaryConversions(rhsExpr);
116 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000117
Chris Lattner299b8842008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000124
125 // If both types are identical, no conversion is needed.
126 if (lhs == rhs)
127 return lhs;
128
129 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
130 // The caller can deal with this (e.g. pointer + int).
131 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
132 return lhs;
133
134 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
135 if (!isCompAssign) {
136 ImpCastExprToType(lhsExpr, destType);
137 ImpCastExprToType(rhsExpr, destType);
138 }
139 return destType;
140}
141
142QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
143 // Perform the usual unary conversions. We do this early so that
144 // integral promotions to "int" can allow us to exit early, in the
145 // lhs == rhs check. Also, for conversion purposes, we ignore any
146 // qualifiers. For example, "const float" and "float" are
147 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000148 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
149 else lhs = lhs.getUnqualifiedType();
150 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
151 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000152
Chris Lattner299b8842008-07-25 21:10:04 +0000153 // If both types are identical, no conversion is needed.
154 if (lhs == rhs)
155 return lhs;
156
157 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
158 // The caller can deal with this (e.g. pointer + int).
159 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
160 return lhs;
161
162 // At this point, we have two different arithmetic types.
163
164 // Handle complex types first (C99 6.3.1.8p1).
165 if (lhs->isComplexType() || rhs->isComplexType()) {
166 // if we have an integer operand, the result is the complex type.
167 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
168 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000169 return lhs;
170 }
171 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
172 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000173 return rhs;
174 }
175 // This handles complex/complex, complex/float, or float/complex.
176 // When both operands are complex, the shorter operand is converted to the
177 // type of the longer, and that is the type of the result. This corresponds
178 // to what is done when combining two real floating-point operands.
179 // The fun begins when size promotion occur across type domains.
180 // From H&S 6.3.4: When one operand is complex and the other is a real
181 // floating-point type, the less precise type is converted, within it's
182 // real or complex domain, to the precision of the other type. For example,
183 // when combining a "long double" with a "double _Complex", the
184 // "double _Complex" is promoted to "long double _Complex".
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // The left side is bigger, convert rhs.
188 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000191 }
192 // At this point, lhs and rhs have the same rank/size. Now, make sure the
193 // domains match. This is a requirement for our implementation, C99
194 // does not require this promotion.
195 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
196 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 }
202 return lhs; // The domain/size match exactly.
203 }
204 // Now handle "real" floating types (i.e. float, double, long double).
205 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
206 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000211 if (rhs->isComplexIntegerType()) {
212 // convert rhs to the complex floating point type.
213 return Context.getComplexType(lhs);
214 }
215 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000219 if (lhs->isComplexIntegerType()) {
220 // convert lhs to the complex floating point type.
221 return Context.getComplexType(rhs);
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 // We have two real floating types, float/complex combos were handled above.
224 // Convert the smaller operand to the bigger result.
225 int result = Context.getFloatingTypeOrder(lhs, rhs);
226
227 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000234 }
235 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
236 // Handle GCC complex int extension.
237 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
238 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
239
240 if (lhsComplexInt && rhsComplexInt) {
241 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
242 rhsComplexInt->getElementType()) >= 0) {
243 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return rhs;
253 }
254 }
255 // Finally, we have two differing integer types.
256 // The rules for this case are in C99 6.3.1.8
257 int compare = Context.getIntegerTypeOrder(lhs, rhs);
258 bool lhsSigned = lhs->isSignedIntegerType(),
259 rhsSigned = rhs->isSignedIntegerType();
260 QualType destType;
261 if (lhsSigned == rhsSigned) {
262 // Same signedness; use the higher-ranked type
263 destType = compare >= 0 ? lhs : rhs;
264 } else if (compare != (lhsSigned ? 1 : -1)) {
265 // The unsigned type has greater than or equal rank to the
266 // signed type, so use the unsigned type
267 destType = lhsSigned ? rhs : lhs;
268 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
269 // The two types are different widths; if we are here, that
270 // means the signed type is larger than the unsigned type, so
271 // use the signed type.
272 destType = lhsSigned ? lhs : rhs;
273 } else {
274 // The signed type is higher-ranked than the unsigned type,
275 // but isn't actually any bigger (like unsigned int and long
276 // on most 32-bit systems). Use the unsigned type corresponding
277 // to the signed type.
278 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
279 }
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000289/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
290/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
291/// multiple tokens. However, the common case is that StringToks points to one
292/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000299 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000300 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000309
310 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
311 if (getLangOptions().CPlusPlus)
312 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000313
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 // Get an array type for the string, according to C99 6.4.5. This includes
315 // the nul terminator character as well as the string length for pascal
316 // strings.
317 StrTy = Context.getConstantArrayType(StrTy,
318 llvm::APInt(32, Literal.GetStringLength()+1),
319 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000322 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000323 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000324 Literal.AnyWide, StrTy,
325 StringToks[0].getLocation(),
326 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000327}
328
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000329/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
330/// CurBlock to VD should cause it to be snapshotted (as we do for auto
331/// variables defined outside the block) or false if this is not needed (e.g.
332/// for values inside the block or for globals).
333///
334/// FIXME: This will create BlockDeclRefExprs for global variables,
335/// function references, etc which is suboptimal :) and breaks
336/// things like "integer constant expression" tests.
337static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
338 ValueDecl *VD) {
339 // If the value is defined inside the block, we couldn't snapshot it even if
340 // we wanted to.
341 if (CurBlock->TheDecl == VD->getDeclContext())
342 return false;
343
344 // If this is an enum constant or function, it is constant, don't snapshot.
345 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
346 return false;
347
348 // If this is a reference to an extern, static, or global variable, no need to
349 // snapshot it.
350 // FIXME: What about 'const' variables in C++?
351 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
352 return Var->hasLocalStorage();
353
354 return true;
355}
356
357
358
Steve Naroff0acc9c92007-09-15 18:49:24 +0000359/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000360/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000361/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000363/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000364Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
365 IdentifierInfo &II,
366 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000367 const CXXScopeSpec *SS,
368 bool isAddressOfOperand) {
369 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000370 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000371}
372
Douglas Gregor566782a2009-01-06 05:10:23 +0000373/// BuildDeclRefExpr - Build either a DeclRefExpr or a
374/// QualifiedDeclRefExpr based on whether or not SS is a
375/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000376DeclRefExpr *
377Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
378 bool TypeDependent, bool ValueDependent,
379 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000380 if (SS && !SS->isEmpty())
381 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000382 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000383 else
384 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000385}
386
Douglas Gregor723d3332009-01-07 00:43:41 +0000387/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
388/// variable corresponding to the anonymous union or struct whose type
389/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000390static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000391 assert(Record->isAnonymousStructOrUnion() &&
392 "Record must be an anonymous struct or union!");
393
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000394 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000395 // be an O(1) operation rather than a slow walk through DeclContext's
396 // vector (which itself will be eliminated). DeclGroups might make
397 // this even better.
398 DeclContext *Ctx = Record->getDeclContext();
399 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
400 DEnd = Ctx->decls_end();
401 D != DEnd; ++D) {
402 if (*D == Record) {
403 // The object for the anonymous struct/union directly
404 // follows its type in the list of declarations.
405 ++D;
406 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000407 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000408 return *D;
409 }
410 }
411
412 assert(false && "Missing object for anonymous record");
413 return 0;
414}
415
Sebastian Redlcd883f72009-01-18 18:53:16 +0000416Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000417Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
418 FieldDecl *Field,
419 Expr *BaseObjectExpr,
420 SourceLocation OpLoc) {
421 assert(Field->getDeclContext()->isRecord() &&
422 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
423 && "Field must be stored inside an anonymous struct or union");
424
425 // Construct the sequence of field member references
426 // we'll have to perform to get to the field in the anonymous
427 // union/struct. The list of members is built from the field
428 // outward, so traverse it backwards to go from an object in
429 // the current context to the field we found.
430 llvm::SmallVector<FieldDecl *, 4> AnonFields;
431 AnonFields.push_back(Field);
432 VarDecl *BaseObject = 0;
433 DeclContext *Ctx = Field->getDeclContext();
434 do {
435 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000436 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000437 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
438 AnonFields.push_back(AnonField);
439 else {
440 BaseObject = cast<VarDecl>(AnonObject);
441 break;
442 }
443 Ctx = Ctx->getParent();
444 } while (Ctx->isRecord() &&
445 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
446
447 // Build the expression that refers to the base object, from
448 // which we will build a sequence of member references to each
449 // of the anonymous union objects and, eventually, the field we
450 // found via name lookup.
451 bool BaseObjectIsPointer = false;
452 unsigned ExtraQuals = 0;
453 if (BaseObject) {
454 // BaseObject is an anonymous struct/union variable (and is,
455 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000456 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000457 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 SourceLocation());
459 ExtraQuals
460 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
461 } else if (BaseObjectExpr) {
462 // The caller provided the base object expression. Determine
463 // whether its a pointer and whether it adds any qualifiers to the
464 // anonymous struct/union fields we're looking into.
465 QualType ObjectType = BaseObjectExpr->getType();
466 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
467 BaseObjectIsPointer = true;
468 ObjectType = ObjectPtr->getPointeeType();
469 }
470 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
471 } else {
472 // We've found a member of an anonymous struct/union that is
473 // inside a non-anonymous struct/union, so in a well-formed
474 // program our base object expression is "this".
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
476 if (!MD->isStatic()) {
477 QualType AnonFieldType
478 = Context.getTagDeclType(
479 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
480 QualType ThisType = Context.getTagDeclType(MD->getParent());
481 if ((Context.getCanonicalType(AnonFieldType)
482 == Context.getCanonicalType(ThisType)) ||
483 IsDerivedFrom(ThisType, AnonFieldType)) {
484 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000485 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000486 MD->getThisType(Context));
487 BaseObjectIsPointer = true;
488 }
489 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 }
500
501 // Build the implicit member references to the field of the
502 // anonymous struct/union.
503 Expr *Result = BaseObjectExpr;
504 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
505 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
506 FI != FIEnd; ++FI) {
507 QualType MemberType = (*FI)->getType();
508 if (!(*FI)->isMutable()) {
509 unsigned combinedQualifiers
510 = MemberType.getCVRQualifiers() | ExtraQuals;
511 MemberType = MemberType.getQualifiedType(combinedQualifiers);
512 }
Steve Naroff774e4152009-01-21 00:14:39 +0000513 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
514 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000515 BaseObjectIsPointer = false;
516 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517 OpLoc = SourceLocation();
518 }
519
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000521}
522
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000523/// ActOnDeclarationNameExpr - The parser has read some kind of name
524/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
525/// performs lookup on that name and returns an expression that refers
526/// to that name. This routine isn't directly called from the parser,
527/// because the parser doesn't know about DeclarationName. Rather,
528/// this routine is called by ActOnIdentifierExpr,
529/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
530/// which form the DeclarationName from the corresponding syntactic
531/// forms.
532///
533/// HasTrailingLParen indicates whether this identifier is used in a
534/// function call context. LookupCtx is only used for a C++
535/// qualified-id (foo::bar) to indicate the class or namespace that
536/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000537///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000538/// isAddressOfOperand means that this expression is the direct operand
539/// of an address-of operator. This matters because this is the only
540/// situation where a qualified name referencing a non-static member may
541/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000542Sema::OwningExprResult
543Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
544 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000545 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000546 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000547 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000548 if (SS && SS->isInvalid())
549 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000550 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
551 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000552
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000553 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
554 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
555 // We've seen something of the form
556 //
557 // identifier(
558 //
559 // and we did not find any entity by the name
560 // "identifier". However, this identifier is still subject to
561 // argument-dependent lookup, so keep track of the name.
562 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
563 Context.OverloadTy,
564 Loc));
565 }
566
Douglas Gregor09be81b2009-02-04 17:27:36 +0000567 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000568 if (Lookup.isAmbiguous()) {
569 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet() ? SS->getRange()
571 : SourceRange());
572 return ExprError();
573 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000574 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000575
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000576 // If this reference is in an Objective-C method, then ivar lookup happens as
577 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000578 IdentifierInfo *II = Name.getAsIdentifierInfo();
579 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000585 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000592 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
593 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000603 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000604 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000622 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
625 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000626
Sebastian Redl0c9da212009-02-03 20:19:35 +0000627 // If this is an expression of the form &Class::member, don't build an
628 // implicit member ref, because we want a pointer to the member in general,
629 // not any specific instance's member.
630 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000631 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000632 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000633 QualType DType;
634 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
635 DType = FD->getType().getNonReferenceType();
636 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
637 DType = Method->getType();
638 } else if (isa<OverloadedFunctionDecl>(D)) {
639 DType = Context.OverloadTy;
640 }
641 // Could be an inner type. That's diagnosed below, so ignore it here.
642 if (!DType.isNull()) {
643 // The pointer is type- and value-dependent if it points into something
644 // dependent.
645 bool Dependent = false;
646 for (; DC; DC = DC->getParent()) {
647 // FIXME: could stop early at namespace scope.
648 if (DC->isRecord()) {
649 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
650 if (Context.getTypeDeclType(Record)->isDependentType()) {
651 Dependent = true;
652 break;
653 }
654 }
655 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000656 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000657 }
658 }
659 }
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661 // We may have found a field within an anonymous union or struct
662 // (C++ [class.union]).
663 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
664 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
665 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666
Douglas Gregor3257fb52008-12-22 05:46:06 +0000667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
668 if (!MD->isStatic()) {
669 // C++ [class.mfct.nonstatic]p2:
670 // [...] if name lookup (3.4.1) resolves the name in the
671 // id-expression to a nonstatic nontype member of class X or of
672 // a base class of X, the id-expression is transformed into a
673 // class member access expression (5.2.5) using (*this) (9.3.2)
674 // as the postfix-expression to the left of the '.' operator.
675 DeclContext *Ctx = 0;
676 QualType MemberType;
677 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
678 Ctx = FD->getDeclContext();
679 MemberType = FD->getType();
680
681 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
682 MemberType = RefType->getPointeeType();
683 else if (!FD->isMutable()) {
684 unsigned combinedQualifiers
685 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
686 MemberType = MemberType.getQualifiedType(combinedQualifiers);
687 }
688 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
689 if (!Method->isStatic()) {
690 Ctx = Method->getParent();
691 MemberType = Method->getType();
692 }
693 } else if (OverloadedFunctionDecl *Ovl
694 = dyn_cast<OverloadedFunctionDecl>(D)) {
695 for (OverloadedFunctionDecl::function_iterator
696 Func = Ovl->function_begin(),
697 FuncEnd = Ovl->function_end();
698 Func != FuncEnd; ++Func) {
699 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
700 if (!DMethod->isStatic()) {
701 Ctx = Ovl->getDeclContext();
702 MemberType = Context.OverloadTy;
703 break;
704 }
705 }
706 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000707
708 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000709 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
710 QualType ThisType = Context.getTagDeclType(MD->getParent());
711 if ((Context.getCanonicalType(CtxType)
712 == Context.getCanonicalType(ThisType)) ||
713 IsDerivedFrom(ThisType, CtxType)) {
714 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000715 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000716 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000717 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000719 }
720 }
721 }
722 }
723
Douglas Gregor8acb7272008-12-11 16:49:14 +0000724 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000725 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
726 if (MD->isStatic())
727 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000728 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
729 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000730 }
731
Douglas Gregor3257fb52008-12-22 05:46:06 +0000732 // Any other ways we could have found the field in a well-formed
733 // program would have been turned into implicit member expressions
734 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000735 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
736 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000737 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000738
Chris Lattner4b009652007-07-25 00:24:17 +0000739 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000740 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000741 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000743 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000744 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000745
Steve Naroffd6163f32008-09-05 22:11:13 +0000746 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
749 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000750 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
751 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
752 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000753 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000754
Chris Lattnerd9037472009-02-15 01:38:09 +0000755 // Check if referencing an identifier with __attribute__((deprecated)).
756 if (VD->getAttr<DeprecatedAttr>()) {
757 // If this reference happens *in* a deprecated function or method, don't
758 // warn. Implementing deprecated stuff requires referencing depreated
759 // stuff.
760 NamedDecl *ND = getCurFunctionOrMethodDecl();
761 if (ND == 0 || !ND->getAttr<DeprecatedAttr>())
762 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
763 }
764
Douglas Gregor48840c72008-12-10 23:01:14 +0000765 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
766 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
767 Scope *CheckS = S;
768 while (CheckS) {
769 if (CheckS->isWithinElse() &&
770 CheckS->getControlParent()->isDeclScope(Var)) {
771 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000772 ExprError(Diag(Loc, diag::warn_value_always_false)
773 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000774 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000775 ExprError(Diag(Loc, diag::warn_value_always_zero)
776 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000777 break;
778 }
779
780 // Move up one more control parent to check again.
781 CheckS = CheckS->getControlParent();
782 if (CheckS)
783 CheckS = CheckS->getParent();
784 }
785 }
786 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000787
788 // Only create DeclRefExpr's for valid Decl's.
789 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000790 return ExprError();
791
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000792 // If the identifier reference is inside a block, and it refers to a value
793 // that is outside the block, create a BlockDeclRefExpr instead of a
794 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
795 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000796 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000797 // We do not do this for things like enum constants, global variables, etc,
798 // as they do not get snapshotted.
799 //
800 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000801 // The BlocksAttr indicates the variable is bound by-reference.
802 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000803 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000804 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000805
Steve Naroff52059382008-10-10 01:28:17 +0000806 // Variable will be bound by-copy, make it const within the closure.
807 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000808 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000809 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000810 }
811 // If this reference is not in a block or if the referenced variable is
812 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000813
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000814 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000815 bool ValueDependent = false;
816 if (getLangOptions().CPlusPlus) {
817 // C++ [temp.dep.expr]p3:
818 // An id-expression is type-dependent if it contains:
819 // - an identifier that was declared with a dependent type,
820 if (VD->getType()->isDependentType())
821 TypeDependent = true;
822 // - FIXME: a template-id that is dependent,
823 // - a conversion-function-id that specifies a dependent type,
824 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
825 Name.getCXXNameType()->isDependentType())
826 TypeDependent = true;
827 // - a nested-name-specifier that contains a class-name that
828 // names a dependent type.
829 else if (SS && !SS->isEmpty()) {
830 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
831 DC; DC = DC->getParent()) {
832 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000833 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000834 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
835 if (Context.getTypeDeclType(Record)->isDependentType()) {
836 TypeDependent = true;
837 break;
838 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000839 }
840 }
841 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000842
Douglas Gregora5d84612008-12-10 20:57:37 +0000843 // C++ [temp.dep.constexpr]p2:
844 //
845 // An identifier is value-dependent if it is:
846 // - a name declared with a dependent type,
847 if (TypeDependent)
848 ValueDependent = true;
849 // - the name of a non-type template parameter,
850 else if (isa<NonTypeTemplateParmDecl>(VD))
851 ValueDependent = true;
852 // - a constant with integral or enumeration type and is
853 // initialized with an expression that is value-dependent
854 // (FIXME!).
855 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000856
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
858 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000859}
860
Sebastian Redlcd883f72009-01-18 18:53:16 +0000861Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
862 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000863 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000864
Chris Lattner4b009652007-07-25 00:24:17 +0000865 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000866 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000867 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
868 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
869 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000870 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000871
Chris Lattner7e637512008-01-12 08:14:25 +0000872 // Pre-defined identifiers are of type char[x], where x is the length of the
873 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000874 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000875 if (FunctionDecl *FD = getCurFunctionDecl())
876 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000877 else if (ObjCMethodDecl *MD = getCurMethodDecl())
878 Length = MD->getSynthesizedMethodSize();
879 else {
880 Diag(Loc, diag::ext_predef_outside_function);
881 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
882 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
883 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000884
885
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000886 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000887 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000888 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000889 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000890}
891
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000893 llvm::SmallString<16> CharBuffer;
894 CharBuffer.resize(Tok.getLength());
895 const char *ThisTokBegin = &CharBuffer[0];
896 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000897
Chris Lattner4b009652007-07-25 00:24:17 +0000898 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
899 Tok.getLocation(), PP);
900 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000901 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000902
903 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
904
Sebastian Redl75324932009-01-20 22:23:13 +0000905 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
906 Literal.isWide(),
907 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000908}
909
Sebastian Redlcd883f72009-01-18 18:53:16 +0000910Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
911 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000912 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
913 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000914 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000915 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000916 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000917 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000918 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000919
Chris Lattner4b009652007-07-25 00:24:17 +0000920 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000921 // Add padding so that NumericLiteralParser can overread by one character.
922 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000923 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000924
Chris Lattner4b009652007-07-25 00:24:17 +0000925 // Get the spelling of the token, which eliminates trigraphs, etc.
926 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927
Chris Lattner4b009652007-07-25 00:24:17 +0000928 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
929 Tok.getLocation(), PP);
930 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931 return ExprError();
932
Chris Lattner1de66eb2007-08-26 03:42:43 +0000933 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000934
Chris Lattner1de66eb2007-08-26 03:42:43 +0000935 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000936 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000937 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000938 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000939 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000940 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000941 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000942 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000943
944 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
945
Ted Kremenekddedbe22007-11-29 00:56:49 +0000946 // isExact will be set by GetFloatValue().
947 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000948 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
949 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000950
Chris Lattner1de66eb2007-08-26 03:42:43 +0000951 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000952 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000953 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000954 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000955
Neil Booth7421e9c2007-08-29 22:00:19 +0000956 // long long is a C99 feature.
957 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000958 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000959 Diag(Tok.getLocation(), diag::ext_longlong);
960
Chris Lattner4b009652007-07-25 00:24:17 +0000961 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000962 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963
Chris Lattner4b009652007-07-25 00:24:17 +0000964 if (Literal.GetIntegerValue(ResultVal)) {
965 // If this value didn't fit into uintmax_t, warn and force to ull.
966 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000967 Ty = Context.UnsignedLongLongTy;
968 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000969 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000970 } else {
971 // If this value fits into a ULL, try to figure out what else it fits into
972 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000973
Chris Lattner4b009652007-07-25 00:24:17 +0000974 // Octal, Hexadecimal, and integers with a U suffix are allowed to
975 // be an unsigned int.
976 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
977
978 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000979 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000980 if (!Literal.isLong && !Literal.isLongLong) {
981 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000982 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000983
Chris Lattner4b009652007-07-25 00:24:17 +0000984 // Does it fit in a unsigned int?
985 if (ResultVal.isIntN(IntSize)) {
986 // Does it fit in a signed int?
987 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000988 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000989 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000990 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000991 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000992 }
Chris Lattner4b009652007-07-25 00:24:17 +0000993 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994
Chris Lattner4b009652007-07-25 00:24:17 +0000995 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000996 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000997 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998
Chris Lattner4b009652007-07-25 00:24:17 +0000999 // Does it fit in a unsigned long?
1000 if (ResultVal.isIntN(LongSize)) {
1001 // Does it fit in a signed long?
1002 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001003 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001004 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001005 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001006 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008 }
1009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001011 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001012 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001013
Chris Lattner4b009652007-07-25 00:24:17 +00001014 // Does it fit in a unsigned long long?
1015 if (ResultVal.isIntN(LongLongSize)) {
1016 // Does it fit in a signed long long?
1017 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001018 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001019 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001020 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001021 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001022 }
1023 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001024
Chris Lattner4b009652007-07-25 00:24:17 +00001025 // If we still couldn't decide a type, we probably have something that
1026 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001027 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001028 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001029 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001030 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032
Chris Lattnere4068872008-05-09 05:59:00 +00001033 if (ResultVal.getBitWidth() != Width)
1034 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001035 }
Sebastian Redl75324932009-01-20 22:23:13 +00001036 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001037 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038
Chris Lattner1de66eb2007-08-26 03:42:43 +00001039 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1040 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001041 Res = new (Context) ImaginaryLiteral(Res,
1042 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043
1044 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001045}
1046
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1048 SourceLocation R, ExprArg Val) {
1049 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001050 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001051 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001052}
1053
1054/// The UsualUnaryConversions() function is *not* called by this routine.
1055/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001056bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1057 SourceLocation OpLoc,
1058 const SourceRange &ExprRange,
1059 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001060 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001061 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001062 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001063 if (isSizeof)
1064 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1065 return false;
1066 }
1067
1068 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001069 Diag(OpLoc, diag::ext_sizeof_void_type)
1070 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001071 return false;
1072 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001073
Chris Lattner159fe082009-01-24 19:46:37 +00001074 return DiagnoseIncompleteType(OpLoc, exprType,
1075 isSizeof ? diag::err_sizeof_incomplete_type :
1076 diag::err_alignof_incomplete_type,
1077 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001078}
1079
Chris Lattner8d9f7962009-01-24 20:17:12 +00001080bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1081 const SourceRange &ExprRange) {
1082 E = E->IgnoreParens();
1083
1084 // alignof decl is always ok.
1085 if (isa<DeclRefExpr>(E))
1086 return false;
1087
1088 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1089 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1090 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001091 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001092 return true;
1093 }
1094 // Other fields are ok.
1095 return false;
1096 }
1097 }
1098 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1099}
1100
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001101/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1102/// the same for @c alignof and @c __alignof
1103/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001104Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001105Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1106 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001107 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001108 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001109
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001110 QualType ArgTy;
1111 SourceRange Range;
1112 if (isType) {
1113 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1114 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001115
1116 // Verify that the operand is valid.
1117 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1118 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001119 } else {
1120 // Get the end location.
1121 Expr *ArgEx = (Expr *)TyOrEx;
1122 Range = ArgEx->getSourceRange();
1123 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001124
1125 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001126 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001127 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001128 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001129 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1130 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1131 isInvalid = true;
1132 } else {
1133 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1134 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001135
1136 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001137 DeleteExpr(ArgEx);
1138 return ExprError();
1139 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001140 }
1141
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001142 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001143 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001144 Context.getSizeType(), OpLoc,
1145 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001146}
1147
Chris Lattner5110ad52007-08-24 21:41:10 +00001148QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001149 DefaultFunctionArrayConversion(V);
1150
Chris Lattnera16e42d2007-08-26 05:39:26 +00001151 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001152 if (const ComplexType *CT = V->getType()->getAsComplexType())
1153 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001154
1155 // Otherwise they pass through real integer and floating point types here.
1156 if (V->getType()->isArithmeticType())
1157 return V->getType();
1158
1159 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001160 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001161 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001162}
1163
1164
Chris Lattner4b009652007-07-25 00:24:17 +00001165
Sebastian Redl8b769972009-01-19 00:08:26 +00001166Action::OwningExprResult
1167Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1168 tok::TokenKind Kind, ExprArg Input) {
1169 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001170
Chris Lattner4b009652007-07-25 00:24:17 +00001171 UnaryOperator::Opcode Opc;
1172 switch (Kind) {
1173 default: assert(0 && "Unknown unary op!");
1174 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1175 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1176 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001177
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178 if (getLangOptions().CPlusPlus &&
1179 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1180 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001181 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001182 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1183
1184 // C++ [over.inc]p1:
1185 //
1186 // [...] If the function is a member function with one
1187 // parameter (which shall be of type int) or a non-member
1188 // function with two parameters (the second of which shall be
1189 // of type int), it defines the postfix increment operator ++
1190 // for objects of that type. When the postfix increment is
1191 // called as a result of using the ++ operator, the int
1192 // argument will have value zero.
1193 Expr *Args[2] = {
1194 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001195 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1196 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001197 };
1198
1199 // Build the candidate set for overloading
1200 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001201 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1202 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001203
1204 // Perform overload resolution.
1205 OverloadCandidateSet::iterator Best;
1206 switch (BestViableFunction(CandidateSet, Best)) {
1207 case OR_Success: {
1208 // We found a built-in operator or an overloaded operator.
1209 FunctionDecl *FnDecl = Best->Function;
1210
1211 if (FnDecl) {
1212 // We matched an overloaded operator. Build a call to that
1213 // operator.
1214
1215 // Convert the arguments.
1216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1217 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001218 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001219 } else {
1220 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001221 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001222 FnDecl->getParamDecl(0)->getType(),
1223 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001224 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001225 }
1226
1227 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001228 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001229 = FnDecl->getType()->getAsFunctionType()->getResultType();
1230 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001231
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001232 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001233 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001234 SourceLocation());
1235 UsualUnaryConversions(FnExpr);
1236
Sebastian Redl8b769972009-01-19 00:08:26 +00001237 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001238 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1239 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001240 } else {
1241 // We matched a built-in operator. Convert the arguments, then
1242 // break out so that we will build the appropriate built-in
1243 // operator node.
1244 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1245 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001246 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001247
1248 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001249 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001250 }
1251
1252 case OR_No_Viable_Function:
1253 // No viable function; fall through to handling this as a
1254 // built-in operator, which will produce an error message for us.
1255 break;
1256
1257 case OR_Ambiguous:
1258 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1259 << UnaryOperator::getOpcodeStr(Opc)
1260 << Arg->getSourceRange();
1261 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001262 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001263 }
1264
1265 // Either we found no viable overloaded operator or we matched a
1266 // built-in operator. In either case, fall through to trying to
1267 // build a built-in operation.
1268 }
1269
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001270 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1271 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001272 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001273 return ExprError();
1274 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001275 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001276}
1277
Sebastian Redl8b769972009-01-19 00:08:26 +00001278Action::OwningExprResult
1279Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1280 ExprArg Idx, SourceLocation RLoc) {
1281 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1282 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001283
Douglas Gregor80723c52008-11-19 17:17:41 +00001284 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001285 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001286 LHSExp->getType()->isEnumeralType() ||
1287 RHSExp->getType()->isRecordType() ||
1288 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001289 // Add the appropriate overloaded operators (C++ [over.match.oper])
1290 // to the candidate set.
1291 OverloadCandidateSet CandidateSet;
1292 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001293 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1294 SourceRange(LLoc, RLoc)))
1295 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001296
Douglas Gregor80723c52008-11-19 17:17:41 +00001297 // Perform overload resolution.
1298 OverloadCandidateSet::iterator Best;
1299 switch (BestViableFunction(CandidateSet, Best)) {
1300 case OR_Success: {
1301 // We found a built-in operator or an overloaded operator.
1302 FunctionDecl *FnDecl = Best->Function;
1303
1304 if (FnDecl) {
1305 // We matched an overloaded operator. Build a call to that
1306 // operator.
1307
1308 // Convert the arguments.
1309 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1310 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1311 PerformCopyInitialization(RHSExp,
1312 FnDecl->getParamDecl(0)->getType(),
1313 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001314 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001315 } else {
1316 // Convert the arguments.
1317 if (PerformCopyInitialization(LHSExp,
1318 FnDecl->getParamDecl(0)->getType(),
1319 "passing") ||
1320 PerformCopyInitialization(RHSExp,
1321 FnDecl->getParamDecl(1)->getType(),
1322 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001323 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001324 }
1325
1326 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001327 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001328 = FnDecl->getType()->getAsFunctionType()->getResultType();
1329 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001330
Douglas Gregor80723c52008-11-19 17:17:41 +00001331 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001332 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001333 SourceLocation());
1334 UsualUnaryConversions(FnExpr);
1335
Sebastian Redl8b769972009-01-19 00:08:26 +00001336 Base.release();
1337 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001338 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001339 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001340 } else {
1341 // We matched a built-in operator. Convert the arguments, then
1342 // break out so that we will build the appropriate built-in
1343 // operator node.
1344 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1345 "passing") ||
1346 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1347 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001348 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001349
1350 break;
1351 }
1352 }
1353
1354 case OR_No_Viable_Function:
1355 // No viable function; fall through to handling this as a
1356 // built-in operator, which will produce an error message for us.
1357 break;
1358
1359 case OR_Ambiguous:
1360 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1361 << "[]"
1362 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1363 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001364 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001365 }
1366
1367 // Either we found no viable overloaded operator or we matched a
1368 // built-in operator. In either case, fall through to trying to
1369 // build a built-in operation.
1370 }
1371
Chris Lattner4b009652007-07-25 00:24:17 +00001372 // Perform default conversions.
1373 DefaultFunctionArrayConversion(LHSExp);
1374 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1377
1378 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001379 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001380 // in the subscript position. As a result, we need to derive the array base
1381 // and index from the expression types.
1382 Expr *BaseExpr, *IndexExpr;
1383 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001384 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001385 BaseExpr = LHSExp;
1386 IndexExpr = RHSExp;
1387 // FIXME: need to deal with const...
1388 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001389 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001390 // Handle the uncommon case of "123[Ptr]".
1391 BaseExpr = RHSExp;
1392 IndexExpr = LHSExp;
1393 // FIXME: need to deal with const...
1394 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001395 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1396 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001397 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001398
Chris Lattner4b009652007-07-25 00:24:17 +00001399 // FIXME: need to deal with const...
1400 ResultType = VTy->getElementType();
1401 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001402 return ExprError(Diag(LHSExp->getLocStart(),
1403 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1404 }
Chris Lattner4b009652007-07-25 00:24:17 +00001405 // C99 6.5.2.1p1
1406 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001407 return ExprError(Diag(IndexExpr->getLocStart(),
1408 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001409
1410 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1411 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001412 // void (*)(int)) and pointers to incomplete types. Functions are not
1413 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001414 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001416 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001417 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001418
Sebastian Redl8b769972009-01-19 00:08:26 +00001419 Base.release();
1420 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001421 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1422 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001423}
1424
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001425QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001426CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001427 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001428 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001429
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001430 // The vector accessor can't exceed the number of elements.
1431 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001432
1433 // This flag determines whether or not the component is one of the four
1434 // special names that indicate a subset of exactly half the elements are
1435 // to be selected.
1436 bool HalvingSwizzle = false;
1437
1438 // This flag determines whether or not CompName has an 's' char prefix,
1439 // indicating that it is a string of hex values to be used as vector indices.
1440 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001441
1442 // Check that we've found one of the special components, or that the component
1443 // names must come from the same set.
1444 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001445 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1446 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001447 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001448 do
1449 compStr++;
1450 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001451 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001452 do
1453 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001454 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001455 }
Nate Begeman1486b502009-01-18 01:47:54 +00001456
1457 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001458 // We didn't get to the end of the string. This means the component names
1459 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001460 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1461 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001462 return QualType();
1463 }
Nate Begeman1486b502009-01-18 01:47:54 +00001464
1465 // Ensure no component accessor exceeds the width of the vector type it
1466 // operates on.
1467 if (!HalvingSwizzle) {
1468 compStr = CompName.getName();
1469
1470 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001471 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001472
1473 while (*compStr) {
1474 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1475 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1476 << baseType << SourceRange(CompLoc);
1477 return QualType();
1478 }
1479 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001480 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001481
Nate Begeman1486b502009-01-18 01:47:54 +00001482 // If this is a halving swizzle, verify that the base type has an even
1483 // number of elements.
1484 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001485 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001486 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001487 return QualType();
1488 }
1489
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001490 // The component accessor looks fine - now we need to compute the actual type.
1491 // The vector type is implied by the component accessor. For example,
1492 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001493 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001494 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001495 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1496 : CompName.getLength();
1497 if (HexSwizzle)
1498 CompSize--;
1499
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001500 if (CompSize == 1)
1501 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001502
Nate Begemanaf6ed502008-04-18 23:10:10 +00001503 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001504 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001505 // diagostics look bad. We want extended vector types to appear built-in.
1506 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1507 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1508 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001509 }
1510 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001511}
1512
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001513/// constructSetterName - Return the setter name for the given
1514/// identifier, i.e. "set" + Name where the initial character of Name
1515/// has been capitalized.
1516// FIXME: Merge with same routine in Parser. But where should this
1517// live?
1518static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1519 const IdentifierInfo *Name) {
1520 llvm::SmallString<100> SelectorName;
1521 SelectorName = "set";
1522 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1523 SelectorName[3] = toupper(SelectorName[3]);
1524 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1525}
1526
Sebastian Redl8b769972009-01-19 00:08:26 +00001527Action::OwningExprResult
1528Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1529 tok::TokenKind OpKind, SourceLocation MemberLoc,
1530 IdentifierInfo &Member) {
1531 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001532 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001533
1534 // Perform default conversions.
1535 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001536
Steve Naroff2cb66382007-07-26 03:11:44 +00001537 QualType BaseType = BaseExpr->getType();
1538 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001539
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001540 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1541 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001542 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001543 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001544 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001545 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001546 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1547 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001548 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001549 return ExprError(Diag(MemberLoc,
1550 diag::err_typecheck_member_reference_arrow)
1551 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001552 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001553
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001554 // Handle field access to simple records. This also handles access to fields
1555 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001556 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001557 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001558 if (DiagnoseIncompleteType(OpLoc, BaseType,
1559 diag::err_typecheck_incomplete_tag,
1560 BaseExpr->getSourceRange()))
1561 return ExprError();
1562
Steve Naroff2cb66382007-07-26 03:11:44 +00001563 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001564 // FIXME: Qualified name lookup for C++ is a bit more complicated
1565 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001567 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001568 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001569
Douglas Gregor09be81b2009-02-04 17:27:36 +00001570 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001571 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001572 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1573 << &Member << BaseExpr->getSourceRange());
1574 else if (Result.isAmbiguous()) {
1575 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1576 MemberLoc, BaseExpr->getSourceRange());
1577 return ExprError();
1578 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001579 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001580
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001581 // If the decl being referenced had an error, return an error for this
1582 // sub-expr without emitting another error, in order to avoid cascading
1583 // error cases.
1584 if (MemberDecl->isInvalidDecl())
1585 return ExprError();
1586
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001587 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001588 // We may have found a field within an anonymous union or struct
1589 // (C++ [class.union]).
1590 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001591 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001592 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001593
Douglas Gregor82d44772008-12-20 23:49:58 +00001594 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1595 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001596 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001597 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1598 MemberType = Ref->getPointeeType();
1599 else {
1600 unsigned combinedQualifiers =
1601 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001602 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001603 combinedQualifiers &= ~QualType::Const;
1604 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1605 }
Eli Friedman76b49832008-02-06 22:48:16 +00001606
Steve Naroff774e4152009-01-21 00:14:39 +00001607 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1608 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001609 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001610 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 Var, MemberLoc,
1612 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001613 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001614 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1615 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001617 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001618 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001619 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001620 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001621 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001622 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001623 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001624 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1625 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001626
Douglas Gregor82d44772008-12-20 23:49:58 +00001627 // We found a declaration kind that we didn't expect. This is a
1628 // generic error message that tells the user that she can't refer
1629 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001630 return ExprError(Diag(MemberLoc,
1631 diag::err_typecheck_member_reference_unknown)
1632 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001633 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001634
Chris Lattnere9d71612008-07-21 04:59:05 +00001635 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1636 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001637 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001638 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001639 // If the decl being referenced had an error, return an error for this
1640 // sub-expr without emitting another error, in order to avoid cascading
1641 // error cases.
1642 if (IV->isInvalidDecl())
1643 return ExprError();
1644
Steve Naroff774e4152009-01-21 00:14:39 +00001645 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1646 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001647 OpKind == tok::arrow);
1648 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001649 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001650 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001651 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1652 << IFTy->getDecl()->getDeclName() << &Member
1653 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001654 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001655
Chris Lattnere9d71612008-07-21 04:59:05 +00001656 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1657 // pointer to a (potentially qualified) interface type.
1658 const PointerType *PTy;
1659 const ObjCInterfaceType *IFTy;
1660 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1661 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1662 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001663
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001664 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001665 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001666 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001667 MemberLoc, BaseExpr));
1668
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001669 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001670 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1671 E = IFTy->qual_end(); I != E; ++I)
1672 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001673 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001675
1676 // If that failed, look for an "implicit" property by seeing if the nullary
1677 // selector is implemented.
1678
1679 // FIXME: The logic for looking up nullary and unary selectors should be
1680 // shared with the code in ActOnInstanceMessage.
1681
1682 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1683 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001684
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001685 // If this reference is in an @implementation, check for 'private' methods.
1686 if (!Getter)
1687 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1688 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1689 if (ObjCImplementationDecl *ImpDecl =
1690 ObjCImplementations[ClassDecl->getIdentifier()])
1691 Getter = ImpDecl->getInstanceMethod(Sel);
1692
Steve Naroff04151f32008-10-22 19:16:27 +00001693 // Look through local category implementations associated with the class.
1694 if (!Getter) {
1695 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1696 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1697 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1698 }
1699 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001700 if (Getter) {
1701 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001702 // will look for the matching setter, in case it is needed.
1703 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1704 &Member);
1705 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1706 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1707 if (!Setter) {
1708 // If this reference is in an @implementation, also check for 'private'
1709 // methods.
1710 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1711 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1712 if (ObjCImplementationDecl *ImpDecl =
1713 ObjCImplementations[ClassDecl->getIdentifier()])
1714 Setter = ImpDecl->getInstanceMethod(SetterSel);
1715 }
1716 // Look through local category implementations associated with the class.
1717 if (!Setter) {
1718 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1719 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1720 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1721 }
1722 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001723
1724 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001725 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1726 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001727 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001728
1729 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1730 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001731 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001732 // Handle properties on qualified "id" protocols.
1733 const ObjCQualifiedIdType *QIdTy;
1734 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1735 // Check protocols on qualified interfaces.
1736 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001737 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001738 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001739 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001740 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001741 // Also must look for a getter name which uses property syntax.
1742 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1743 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001744 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1745 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001746 }
1747 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001748
1749 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1750 << &Member << BaseType);
1751 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001752 // Handle 'field access' to vectors, such as 'V.xx'.
1753 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001754 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1755 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001756 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001757 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1758 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001759 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001760
1761 return ExprError(Diag(MemberLoc,
1762 diag::err_typecheck_member_reference_struct_union)
1763 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001764}
1765
Douglas Gregor3257fb52008-12-22 05:46:06 +00001766/// ConvertArgumentsForCall - Converts the arguments specified in
1767/// Args/NumArgs to the parameter types of the function FDecl with
1768/// function prototype Proto. Call is the call expression itself, and
1769/// Fn is the function expression. For a C++ member function, this
1770/// routine does not attempt to convert the object argument. Returns
1771/// true if the call is ill-formed.
1772bool
1773Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1774 FunctionDecl *FDecl,
1775 const FunctionTypeProto *Proto,
1776 Expr **Args, unsigned NumArgs,
1777 SourceLocation RParenLoc) {
1778 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1779 // assignment, to the types of the corresponding parameter, ...
1780 unsigned NumArgsInProto = Proto->getNumArgs();
1781 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001782 bool Invalid = false;
1783
Douglas Gregor3257fb52008-12-22 05:46:06 +00001784 // If too few arguments are available (and we don't have default
1785 // arguments for the remaining parameters), don't make the call.
1786 if (NumArgs < NumArgsInProto) {
1787 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1788 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1789 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1790 // Use default arguments for missing arguments
1791 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001792 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001793 }
1794
1795 // If too many are passed and not variadic, error on the extras and drop
1796 // them.
1797 if (NumArgs > NumArgsInProto) {
1798 if (!Proto->isVariadic()) {
1799 Diag(Args[NumArgsInProto]->getLocStart(),
1800 diag::err_typecheck_call_too_many_args)
1801 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1802 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1803 Args[NumArgs-1]->getLocEnd());
1804 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001805 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001806 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001807 }
1808 NumArgsToCheck = NumArgsInProto;
1809 }
1810
1811 // Continue to check argument types (even if we have too few/many args).
1812 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1813 QualType ProtoArgType = Proto->getArgType(i);
1814
1815 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001816 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001817 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001818
1819 // Pass the argument.
1820 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1821 return true;
1822 } else
1823 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001824 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001825 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001826
Douglas Gregor3257fb52008-12-22 05:46:06 +00001827 Call->setArg(i, Arg);
1828 }
1829
1830 // If this is a variadic call, handle args passed through "...".
1831 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001832 VariadicCallType CallType = VariadicFunction;
1833 if (Fn->getType()->isBlockPointerType())
1834 CallType = VariadicBlock; // Block
1835 else if (isa<MemberExpr>(Fn))
1836 CallType = VariadicMethod;
1837
Douglas Gregor3257fb52008-12-22 05:46:06 +00001838 // Promote the arguments (C99 6.5.2.2p7).
1839 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1840 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001841 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001842 Call->setArg(i, Arg);
1843 }
1844 }
1845
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001846 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001847}
1848
Steve Naroff87d58b42007-09-16 03:34:24 +00001849/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001850/// This provides the location of the left/right parens and a list of comma
1851/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001852Action::OwningExprResult
1853Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1854 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001855 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001856 unsigned NumArgs = args.size();
1857 Expr *Fn = static_cast<Expr *>(fn.release());
1858 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001859 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001860 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001861 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001862
Douglas Gregor3257fb52008-12-22 05:46:06 +00001863 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001864 // Determine whether this is a dependent call inside a C++ template,
1865 // in which case we won't do any semantic analysis now.
1866 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1867 bool Dependent = false;
1868 if (Fn->isTypeDependent())
1869 Dependent = true;
1870 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1871 Dependent = true;
1872
1873 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001874 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001875 Context.DependentTy, RParenLoc));
1876
1877 // Determine whether this is a call to an object (C++ [over.call.object]).
1878 if (Fn->getType()->isRecordType())
1879 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1880 CommaLocs, RParenLoc));
1881
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001882 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1884 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1885 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001886 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1887 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001888 }
1889
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001890 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001891 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001892 Expr *FnExpr = Fn;
1893 bool ADL = true;
1894 while (true) {
1895 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1896 FnExpr = IcExpr->getSubExpr();
1897 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001898 // Parentheses around a function disable ADL
1899 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001900 ADL = false;
1901 FnExpr = PExpr->getSubExpr();
1902 } else if (isa<UnaryOperator>(FnExpr) &&
1903 cast<UnaryOperator>(FnExpr)->getOpcode()
1904 == UnaryOperator::AddrOf) {
1905 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001906 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1907 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1908 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1909 break;
1910 } else if (UnresolvedFunctionNameExpr *DepName
1911 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1912 UnqualifiedName = DepName->getName();
1913 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001914 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001915 // Any kind of name that does not refer to a declaration (or
1916 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1917 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001918 break;
1919 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001920 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001921
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001922 OverloadedFunctionDecl *Ovl = 0;
1923 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001924 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001925 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1926 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001927
Douglas Gregorfcb19192009-02-11 23:02:49 +00001928 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001929 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001930 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001931 ADL = false;
1932
Douglas Gregorfcb19192009-02-11 23:02:49 +00001933 // We don't perform ADL in C.
1934 if (!getLangOptions().CPlusPlus)
1935 ADL = false;
1936
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001937 if (Ovl || ADL) {
1938 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1939 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001940 NumArgs, CommaLocs, RParenLoc, ADL);
1941 if (!FDecl)
1942 return ExprError();
1943
1944 // Update Fn to refer to the actual function selected.
1945 Expr *NewFn = 0;
1946 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001947 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001948 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1949 QDRExpr->getLocation(),
1950 false, false,
1951 QDRExpr->getSourceRange().getBegin());
1952 else
1953 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1954 Fn->getSourceRange().getBegin());
1955 Fn->Destroy(Context);
1956 Fn = NewFn;
1957 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001958 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001959
1960 // Promote the function operand.
1961 UsualUnaryConversions(Fn);
1962
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001963 // Make the call expr early, before semantic checks. This guarantees cleanup
1964 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001965 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1966 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00001967 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1968 Args, NumArgs,
1969 Context.BoolTy,
1970 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001971
Steve Naroffd6163f32008-09-05 22:11:13 +00001972 const FunctionType *FuncT;
1973 if (!Fn->getType()->isBlockPointerType()) {
1974 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1975 // have type pointer to function".
1976 const PointerType *PT = Fn->getType()->getAsPointerType();
1977 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001978 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1979 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001980 FuncT = PT->getPointeeType()->getAsFunctionType();
1981 } else { // This is a block call.
1982 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1983 getAsFunctionType();
1984 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001985 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001986 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1987 << Fn->getType() << Fn->getSourceRange());
1988
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001989 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001990 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001991
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001992 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001993 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1994 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001995 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001996 } else {
1997 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001998
Steve Naroffdb65e052007-08-28 23:30:39 +00001999 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002000 for (unsigned i = 0; i != NumArgs; i++) {
2001 Expr *Arg = Args[i];
2002 DefaultArgumentPromotion(Arg);
2003 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002004 }
Chris Lattner4b009652007-07-25 00:24:17 +00002005 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002006
Douglas Gregor3257fb52008-12-22 05:46:06 +00002007 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2008 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002009 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2010 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002011
Chris Lattner2e64c072007-08-10 20:18:51 +00002012 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002013 if (FDecl)
2014 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002015
Sebastian Redl8b769972009-01-19 00:08:26 +00002016 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002017}
2018
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002019Action::OwningExprResult
2020Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2021 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002022 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002023 QualType literalType = QualType::getFromOpaquePtr(Ty);
2024 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002025 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002026 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002027
Eli Friedman8c2173d2008-05-20 05:22:08 +00002028 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002029 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002030 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2031 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002032 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2033 diag::err_typecheck_decl_incomplete_type,
2034 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002035 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002036
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002037 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002038 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002039 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002040
Chris Lattnere5cb5862008-12-04 23:50:19 +00002041 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002042 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002043 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002044 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002045 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002046 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002047 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2048 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002049}
2050
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002051Action::OwningExprResult
2052Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2053 InitListDesignations &Designators,
2054 SourceLocation RBraceLoc) {
2055 unsigned NumInit = initlist.size();
2056 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002057
Steve Naroff0acc9c92007-09-15 18:49:24 +00002058 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002059 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002060
Steve Naroff774e4152009-01-21 00:14:39 +00002061 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002062 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002063 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002064 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002065}
2066
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002067/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002068bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002069 UsualUnaryConversions(castExpr);
2070
2071 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2072 // type needs to be scalar.
2073 if (castType->isVoidType()) {
2074 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002075 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2076 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002077 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002078 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2079 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2080 (castType->isStructureType() || castType->isUnionType())) {
2081 // GCC struct/union extension: allow cast to self.
2082 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2083 << castType << castExpr->getSourceRange();
2084 } else if (castType->isUnionType()) {
2085 // GCC cast to union extension
2086 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2087 RecordDecl::field_iterator Field, FieldEnd;
2088 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2089 Field != FieldEnd; ++Field) {
2090 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2091 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2092 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2093 << castExpr->getSourceRange();
2094 break;
2095 }
2096 }
2097 if (Field == FieldEnd)
2098 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2099 << castExpr->getType() << castExpr->getSourceRange();
2100 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002101 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002102 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002103 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002104 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002105 } else if (!castExpr->getType()->isScalarType() &&
2106 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002107 return Diag(castExpr->getLocStart(),
2108 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002109 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002110 } else if (castExpr->getType()->isVectorType()) {
2111 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2112 return true;
2113 } else if (castType->isVectorType()) {
2114 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2115 return true;
2116 }
2117 return false;
2118}
2119
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002120bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002121 assert(VectorTy->isVectorType() && "Not a vector type!");
2122
2123 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002124 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002125 return Diag(R.getBegin(),
2126 Ty->isVectorType() ?
2127 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002128 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002129 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002130 } else
2131 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002132 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002133 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002134
2135 return false;
2136}
2137
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002138Action::OwningExprResult
2139Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2140 SourceLocation RParenLoc, ExprArg Op) {
2141 assert((Ty != 0) && (Op.get() != 0) &&
2142 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002143
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002144 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002145 QualType castType = QualType::getFromOpaquePtr(Ty);
2146
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002147 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002148 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002149 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002150 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002151}
2152
Chris Lattner98a425c2007-11-26 01:40:58 +00002153/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2154/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002155inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2156 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2157 UsualUnaryConversions(cond);
2158 UsualUnaryConversions(lex);
2159 UsualUnaryConversions(rex);
2160 QualType condT = cond->getType();
2161 QualType lexT = lex->getType();
2162 QualType rexT = rex->getType();
2163
2164 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002165 if (!cond->isTypeDependent()) {
2166 if (!condT->isScalarType()) { // C99 6.5.15p2
2167 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2168 return QualType();
2169 }
Chris Lattner4b009652007-07-25 00:24:17 +00002170 }
Chris Lattner992ae932008-01-06 22:42:25 +00002171
2172 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002173 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2174 return Context.DependentTy;
2175
Chris Lattner992ae932008-01-06 22:42:25 +00002176 // If both operands have arithmetic type, do the usual arithmetic conversions
2177 // to find a common type: C99 6.5.15p3,5.
2178 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002179 UsualArithmeticConversions(lex, rex);
2180 return lex->getType();
2181 }
Chris Lattner992ae932008-01-06 22:42:25 +00002182
2183 // If both operands are the same structure or union type, the result is that
2184 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002185 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002186 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002187 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002188 // "If both the operands have structure or union type, the result has
2189 // that type." This implies that CV qualifiers are dropped.
2190 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002191 }
Chris Lattner992ae932008-01-06 22:42:25 +00002192
2193 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002194 // The following || allows only one side to be void (a GCC-ism).
2195 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002196 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002197 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2198 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002199 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002200 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2201 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002202 ImpCastExprToType(lex, Context.VoidTy);
2203 ImpCastExprToType(rex, Context.VoidTy);
2204 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002205 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002206 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2207 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002208 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2209 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002210 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002211 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002212 return lexT;
2213 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002214 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2215 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002216 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002217 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002218 return rexT;
2219 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002220 // Handle the case where both operands are pointers before we handle null
2221 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002222 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2223 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2224 // get the "pointed to" types
2225 QualType lhptee = LHSPT->getPointeeType();
2226 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002227
Chris Lattner71225142007-07-31 21:27:01 +00002228 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2229 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002230 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002231 // Figure out necessary qualifiers (C99 6.5.15p6)
2232 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002233 QualType destType = Context.getPointerType(destPointee);
2234 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2235 ImpCastExprToType(rex, destType); // promote to void*
2236 return destType;
2237 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002238 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002239 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002240 QualType destType = Context.getPointerType(destPointee);
2241 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2242 ImpCastExprToType(rex, destType); // promote to void*
2243 return destType;
2244 }
Chris Lattner4b009652007-07-25 00:24:17 +00002245
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002246 QualType compositeType = lexT;
2247
2248 // If either type is an Objective-C object type then check
2249 // compatibility according to Objective-C.
2250 if (Context.isObjCObjectPointerType(lexT) ||
2251 Context.isObjCObjectPointerType(rexT)) {
2252 // If both operands are interfaces and either operand can be
2253 // assigned to the other, use that type as the composite
2254 // type. This allows
2255 // xxx ? (A*) a : (B*) b
2256 // where B is a subclass of A.
2257 //
2258 // Additionally, as for assignment, if either type is 'id'
2259 // allow silent coercion. Finally, if the types are
2260 // incompatible then make sure to use 'id' as the composite
2261 // type so the result is acceptable for sending messages to.
2262
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002263 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2264 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002265 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2266 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2267 if (LHSIface && RHSIface &&
2268 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2269 compositeType = lexT;
2270 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002271 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002272 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002273 } else if (Context.isObjCIdStructType(lhptee) ||
2274 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002275 compositeType = Context.getObjCIdType();
2276 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002277 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2278 << lexT << rexT
2279 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002280 QualType incompatTy = Context.getObjCIdType();
2281 ImpCastExprToType(lex, incompatTy);
2282 ImpCastExprToType(rex, incompatTy);
2283 return incompatTy;
2284 }
2285 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2286 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002287 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002288 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002289 // In this situation, we assume void* type. No especially good
2290 // reason, but this is what gcc does, and we do have to pick
2291 // to get a consistent AST.
2292 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002293 ImpCastExprToType(lex, incompatTy);
2294 ImpCastExprToType(rex, incompatTy);
2295 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002296 }
2297 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002298 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2299 // differently qualified versions of compatible types, the result type is
2300 // a pointer to an appropriately qualified version of the *composite*
2301 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002302 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002303 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002304 ImpCastExprToType(lex, compositeType);
2305 ImpCastExprToType(rex, compositeType);
2306 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002307 }
Chris Lattner4b009652007-07-25 00:24:17 +00002308 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002309 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2310 // evaluates to "struct objc_object *" (and is handled above when comparing
2311 // id with statically typed objects).
2312 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2313 // GCC allows qualified id and any Objective-C type to devolve to
2314 // id. Currently localizing to here until clear this should be
2315 // part of ObjCQualifiedIdTypesAreCompatible.
2316 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2317 (lexT->isObjCQualifiedIdType() &&
2318 Context.isObjCObjectPointerType(rexT)) ||
2319 (rexT->isObjCQualifiedIdType() &&
2320 Context.isObjCObjectPointerType(lexT))) {
2321 // FIXME: This is not the correct composite type. This only
2322 // happens to work because id can more or less be used anywhere,
2323 // however this may change the type of method sends.
2324 // FIXME: gcc adds some type-checking of the arguments and emits
2325 // (confusing) incompatible comparison warnings in some
2326 // cases. Investigate.
2327 QualType compositeType = Context.getObjCIdType();
2328 ImpCastExprToType(lex, compositeType);
2329 ImpCastExprToType(rex, compositeType);
2330 return compositeType;
2331 }
2332 }
2333
Steve Naroff3eac7692008-09-10 19:17:48 +00002334 // Selection between block pointer types is ok as long as they are the same.
2335 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2336 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2337 return lexT;
2338
Chris Lattner992ae932008-01-06 22:42:25 +00002339 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002340 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002341 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002342 return QualType();
2343}
2344
Steve Naroff87d58b42007-09-16 03:34:24 +00002345/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002346/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002347Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2348 SourceLocation ColonLoc,
2349 ExprArg Cond, ExprArg LHS,
2350 ExprArg RHS) {
2351 Expr *CondExpr = (Expr *) Cond.get();
2352 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002353
2354 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2355 // was the condition.
2356 bool isLHSNull = LHSExpr == 0;
2357 if (isLHSNull)
2358 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002359
2360 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002361 RHSExpr, QuestionLoc);
2362 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002363 return ExprError();
2364
2365 Cond.release();
2366 LHS.release();
2367 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002368 return Owned(new (Context) ConditionalOperator(CondExpr,
2369 isLHSNull ? 0 : LHSExpr,
2370 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002371}
2372
Chris Lattner4b009652007-07-25 00:24:17 +00002373
2374// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2375// being closely modeled after the C99 spec:-). The odd characteristic of this
2376// routine is it effectively iqnores the qualifiers on the top level pointee.
2377// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2378// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002379Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002380Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2381 QualType lhptee, rhptee;
2382
2383 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002384 lhptee = lhsType->getAsPointerType()->getPointeeType();
2385 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002386
2387 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002388 lhptee = Context.getCanonicalType(lhptee);
2389 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002390
Chris Lattner005ed752008-01-04 18:04:52 +00002391 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002392
2393 // C99 6.5.16.1p1: This following citation is common to constraints
2394 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2395 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002396 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002397 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002398 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002399
2400 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2401 // incomplete type and the other is a pointer to a qualified or unqualified
2402 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002403 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002404 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002405 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002406
2407 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002408 assert(rhptee->isFunctionType());
2409 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002410 }
2411
2412 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002413 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002414 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002415
2416 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002417 assert(lhptee->isFunctionType());
2418 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002419 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002420
2421 // Check for ObjC interfaces
2422 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2423 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2424 if (LHSIface && RHSIface &&
2425 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2426 return ConvTy;
2427
2428 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002429 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002430 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002431 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002432 return ConvTy;
2433
Chris Lattner4b009652007-07-25 00:24:17 +00002434 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2435 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002436 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2437 rhptee.getUnqualifiedType()))
2438 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002439 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002440}
2441
Steve Naroff3454b6c2008-09-04 15:10:53 +00002442/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2443/// block pointer types are compatible or whether a block and normal pointer
2444/// are compatible. It is more restrict than comparing two function pointer
2445// types.
2446Sema::AssignConvertType
2447Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2448 QualType rhsType) {
2449 QualType lhptee, rhptee;
2450
2451 // get the "pointed to" type (ignoring qualifiers at the top level)
2452 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2453 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2454
2455 // make sure we operate on the canonical type
2456 lhptee = Context.getCanonicalType(lhptee);
2457 rhptee = Context.getCanonicalType(rhptee);
2458
2459 AssignConvertType ConvTy = Compatible;
2460
2461 // For blocks we enforce that qualifiers are identical.
2462 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2463 ConvTy = CompatiblePointerDiscardsQualifiers;
2464
2465 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2466 return IncompatibleBlockPointer;
2467 return ConvTy;
2468}
2469
Chris Lattner4b009652007-07-25 00:24:17 +00002470/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2471/// has code to accommodate several GCC extensions when type checking
2472/// pointers. Here are some objectionable examples that GCC considers warnings:
2473///
2474/// int a, *pint;
2475/// short *pshort;
2476/// struct foo *pfoo;
2477///
2478/// pint = pshort; // warning: assignment from incompatible pointer type
2479/// a = pint; // warning: assignment makes integer from pointer without a cast
2480/// pint = a; // warning: assignment makes pointer from integer without a cast
2481/// pint = pfoo; // warning: assignment from incompatible pointer type
2482///
2483/// As a result, the code for dealing with pointers is more complex than the
2484/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002485///
Chris Lattner005ed752008-01-04 18:04:52 +00002486Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002487Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002488 // Get canonical types. We're not formatting these types, just comparing
2489 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002490 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2491 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002492
2493 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002494 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002495
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002496 // If the left-hand side is a reference type, then we are in a
2497 // (rare!) case where we've allowed the use of references in C,
2498 // e.g., as a parameter type in a built-in function. In this case,
2499 // just make sure that the type referenced is compatible with the
2500 // right-hand side type. The caller is responsible for adjusting
2501 // lhsType so that the resulting expression does not have reference
2502 // type.
2503 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2504 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002505 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002506 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002507 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002508
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002509 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2510 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002511 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002512 // Relax integer conversions like we do for pointers below.
2513 if (rhsType->isIntegerType())
2514 return IntToPointer;
2515 if (lhsType->isIntegerType())
2516 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002517 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002518 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002519
Nate Begemanc5f0f652008-07-14 18:02:46 +00002520 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002521 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002522 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2523 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002524 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002525
Nate Begemanc5f0f652008-07-14 18:02:46 +00002526 // If we are allowing lax vector conversions, and LHS and RHS are both
2527 // vectors, the total size only needs to be the same. This is a bitcast;
2528 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002529 if (getLangOptions().LaxVectorConversions &&
2530 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002531 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002532 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002533 }
2534 return Incompatible;
2535 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002536
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002537 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002538 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002539
Chris Lattner390564e2008-04-07 06:49:41 +00002540 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002541 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002542 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002543
Chris Lattner390564e2008-04-07 06:49:41 +00002544 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002545 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002546
Steve Naroffa982c712008-09-29 18:10:17 +00002547 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002548 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002549 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002550
2551 // Treat block pointers as objects.
2552 if (getLangOptions().ObjC1 &&
2553 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2554 return Compatible;
2555 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002556 return Incompatible;
2557 }
2558
2559 if (isa<BlockPointerType>(lhsType)) {
2560 if (rhsType->isIntegerType())
2561 return IntToPointer;
2562
Steve Naroffa982c712008-09-29 18:10:17 +00002563 // Treat block pointers as objects.
2564 if (getLangOptions().ObjC1 &&
2565 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2566 return Compatible;
2567
Steve Naroff3454b6c2008-09-04 15:10:53 +00002568 if (rhsType->isBlockPointerType())
2569 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2570
2571 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2572 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002573 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002574 }
Chris Lattner1853da22008-01-04 23:18:45 +00002575 return Incompatible;
2576 }
2577
Chris Lattner390564e2008-04-07 06:49:41 +00002578 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002579 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002580 if (lhsType == Context.BoolTy)
2581 return Compatible;
2582
2583 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002584 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002585
Chris Lattner390564e2008-04-07 06:49:41 +00002586 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002587 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002588
2589 if (isa<BlockPointerType>(lhsType) &&
2590 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002591 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002592 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002593 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002594
Chris Lattner1853da22008-01-04 23:18:45 +00002595 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002596 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002597 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002598 }
2599 return Incompatible;
2600}
2601
Chris Lattner005ed752008-01-04 18:04:52 +00002602Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002603Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002604 if (getLangOptions().CPlusPlus) {
2605 if (!lhsType->isRecordType()) {
2606 // C++ 5.17p3: If the left operand is not of class type, the
2607 // expression is implicitly converted (C++ 4) to the
2608 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002609 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2610 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002611 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002612 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002613 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002614 }
2615
2616 // FIXME: Currently, we fall through and treat C++ classes like C
2617 // structures.
2618 }
2619
Steve Naroffcdee22d2007-11-27 17:58:44 +00002620 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2621 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002622 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2623 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002624 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002625 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002626 return Compatible;
2627 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002628
2629 // We don't allow conversion of non-null-pointer constants to integers.
2630 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2631 return IntToBlockPointer;
2632
Chris Lattner5f505bf2007-10-16 02:55:40 +00002633 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002634 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002635 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002636 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002637 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002638 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002639 if (!lhsType->isReferenceType())
2640 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002641
Chris Lattner005ed752008-01-04 18:04:52 +00002642 Sema::AssignConvertType result =
2643 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002644
2645 // C99 6.5.16.1p2: The value of the right operand is converted to the
2646 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002647 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2648 // so that we can use references in built-in functions even in C.
2649 // The getNonReferenceType() call makes sure that the resulting expression
2650 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002651 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002652 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002653 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002654}
2655
Chris Lattner005ed752008-01-04 18:04:52 +00002656Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002657Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2658 return CheckAssignmentConstraints(lhsType, rhsType);
2659}
2660
Chris Lattner1eafdea2008-11-18 01:30:42 +00002661QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002662 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002663 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002664 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002665 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002666}
2667
Chris Lattner1eafdea2008-11-18 01:30:42 +00002668inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002669 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002670 // For conversion purposes, we ignore any qualifiers.
2671 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002672 QualType lhsType =
2673 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2674 QualType rhsType =
2675 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002676
Nate Begemanc5f0f652008-07-14 18:02:46 +00002677 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002678 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002679 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002680
Nate Begemanc5f0f652008-07-14 18:02:46 +00002681 // Handle the case of a vector & extvector type of the same size and element
2682 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002683 if (getLangOptions().LaxVectorConversions) {
2684 // FIXME: Should we warn here?
2685 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002686 if (const VectorType *RV = rhsType->getAsVectorType())
2687 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002688 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002689 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002690 }
2691 }
2692 }
2693
Nate Begemanc5f0f652008-07-14 18:02:46 +00002694 // If the lhs is an extended vector and the rhs is a scalar of the same type
2695 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002696 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002697 QualType eltType = V->getElementType();
2698
2699 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2700 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2701 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002702 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002703 return lhsType;
2704 }
2705 }
2706
Nate Begemanc5f0f652008-07-14 18:02:46 +00002707 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002708 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002709 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002710 QualType eltType = V->getElementType();
2711
2712 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2713 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2714 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002715 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002716 return rhsType;
2717 }
2718 }
2719
Chris Lattner4b009652007-07-25 00:24:17 +00002720 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002721 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002722 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002723 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002724 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002725}
2726
Chris Lattner4b009652007-07-25 00:24:17 +00002727inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002729{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002730 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002732
Steve Naroff8f708362007-08-24 19:07:16 +00002733 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002734
Chris Lattner4b009652007-07-25 00:24:17 +00002735 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002736 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002737 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002738}
2739
2740inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002742{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002743 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2744 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2745 return CheckVectorOperands(Loc, lex, rex);
2746 return InvalidOperands(Loc, lex, rex);
2747 }
Chris Lattner4b009652007-07-25 00:24:17 +00002748
Steve Naroff8f708362007-08-24 19:07:16 +00002749 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002750
Chris Lattner4b009652007-07-25 00:24:17 +00002751 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002752 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002753 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002754}
2755
2756inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002757 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002758{
2759 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002760 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002761
Steve Naroff8f708362007-08-24 19:07:16 +00002762 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002763
Chris Lattner4b009652007-07-25 00:24:17 +00002764 // handle the common case first (both operands are arithmetic).
2765 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002766 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002767
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002768 // Put any potential pointer into PExp
2769 Expr* PExp = lex, *IExp = rex;
2770 if (IExp->getType()->isPointerType())
2771 std::swap(PExp, IExp);
2772
2773 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2774 if (IExp->getType()->isIntegerType()) {
2775 // Check for arithmetic on pointers to incomplete types
2776 if (!PTy->getPointeeType()->isObjectType()) {
2777 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002778 if (getLangOptions().CPlusPlus) {
2779 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2780 << lex->getSourceRange() << rex->getSourceRange();
2781 return QualType();
2782 }
2783
2784 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002785 Diag(Loc, diag::ext_gnu_void_ptr)
2786 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002787 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002788 if (getLangOptions().CPlusPlus) {
2789 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2790 << lex->getType() << lex->getSourceRange();
2791 return QualType();
2792 }
2793
2794 // GNU extension: arithmetic on pointer to function
2795 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002796 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002797 } else {
2798 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2799 diag::err_typecheck_arithmetic_incomplete_type,
2800 lex->getSourceRange(), SourceRange(),
2801 lex->getType());
2802 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002803 }
2804 }
2805 return PExp->getType();
2806 }
2807 }
2808
Chris Lattner1eafdea2008-11-18 01:30:42 +00002809 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002810}
2811
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002812// C99 6.5.6
2813QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002814 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002815 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002816 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002817
Steve Naroff8f708362007-08-24 19:07:16 +00002818 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002819
Chris Lattnerf6da2912007-12-09 21:53:25 +00002820 // Enforce type constraints: C99 6.5.6p3.
2821
2822 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002823 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002824 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002825
2826 // Either ptr - int or ptr - ptr.
2827 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002828 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002829
Chris Lattnerf6da2912007-12-09 21:53:25 +00002830 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002831 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002832 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002833 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002834 Diag(Loc, diag::ext_gnu_void_ptr)
2835 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002836 } else if (lpointee->isFunctionType()) {
2837 if (getLangOptions().CPlusPlus) {
2838 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2839 << lex->getType() << lex->getSourceRange();
2840 return QualType();
2841 }
2842
2843 // GNU extension: arithmetic on pointer to function
2844 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2845 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002846 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002847 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002848 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002849 return QualType();
2850 }
2851 }
2852
2853 // The result type of a pointer-int computation is the pointer type.
2854 if (rex->getType()->isIntegerType())
2855 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002856
Chris Lattnerf6da2912007-12-09 21:53:25 +00002857 // Handle pointer-pointer subtractions.
2858 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002859 QualType rpointee = RHSPTy->getPointeeType();
2860
Chris Lattnerf6da2912007-12-09 21:53:25 +00002861 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002862 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002863 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002864 if (rpointee->isVoidType()) {
2865 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002866 Diag(Loc, diag::ext_gnu_void_ptr)
2867 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002868 } else if (rpointee->isFunctionType()) {
2869 if (getLangOptions().CPlusPlus) {
2870 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2871 << rex->getType() << rex->getSourceRange();
2872 return QualType();
2873 }
2874
2875 // GNU extension: arithmetic on pointer to function
2876 if (!lpointee->isFunctionType())
2877 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2878 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002879 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002880 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002881 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002882 return QualType();
2883 }
2884 }
2885
2886 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002887 if (!Context.typesAreCompatible(
2888 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2889 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002890 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002891 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002892 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002893 return QualType();
2894 }
2895
2896 return Context.getPointerDiffType();
2897 }
2898 }
2899
Chris Lattner1eafdea2008-11-18 01:30:42 +00002900 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002901}
2902
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002903// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002904QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002905 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002906 // C99 6.5.7p2: Each of the operands shall have integer type.
2907 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002908 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002909
Chris Lattner2c8bff72007-12-12 05:47:28 +00002910 // Shifts don't perform usual arithmetic conversions, they just do integer
2911 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002912 if (!isCompAssign)
2913 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002914 UsualUnaryConversions(rex);
2915
2916 // "The type of the result is that of the promoted left operand."
2917 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002918}
2919
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002920// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002921QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002922 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002923 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002924 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002925
Chris Lattner254f3bc2007-08-26 01:18:55 +00002926 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002927 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2928 UsualArithmeticConversions(lex, rex);
2929 else {
2930 UsualUnaryConversions(lex);
2931 UsualUnaryConversions(rex);
2932 }
Chris Lattner4b009652007-07-25 00:24:17 +00002933 QualType lType = lex->getType();
2934 QualType rType = rex->getType();
2935
Ted Kremenek486509e2007-10-29 17:13:39 +00002936 // For non-floating point types, check for self-comparisons of the form
2937 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2938 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002939 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002940 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2941 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002942 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002943 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002944 }
2945
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002946 // The result of comparisons is 'bool' in C++, 'int' in C.
2947 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2948
Chris Lattner254f3bc2007-08-26 01:18:55 +00002949 if (isRelational) {
2950 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002951 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002952 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002953 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002954 if (lType->isFloatingType()) {
2955 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002956 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002957 }
2958
Chris Lattner254f3bc2007-08-26 01:18:55 +00002959 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002960 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002961 }
Chris Lattner4b009652007-07-25 00:24:17 +00002962
Chris Lattner22be8422007-08-26 01:10:14 +00002963 bool LHSIsNull = lex->isNullPointerConstant(Context);
2964 bool RHSIsNull = rex->isNullPointerConstant(Context);
2965
Chris Lattner254f3bc2007-08-26 01:18:55 +00002966 // All of the following pointer related warnings are GCC extensions, except
2967 // when handling null pointer constants. One day, we can consider making them
2968 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002969 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002970 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002971 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002972 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002973 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002974
Steve Naroff3b435622007-11-13 14:57:38 +00002975 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002976 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2977 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002978 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00002979 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002980 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002981 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002982 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002983 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002984 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002985 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002986 // Handle block pointer types.
2987 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2988 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2989 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2990
2991 if (!LHSIsNull && !RHSIsNull &&
2992 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002993 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002994 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002995 }
2996 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002997 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002998 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002999 // Allow block pointers to be compared with null pointer constants.
3000 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3001 (lType->isPointerType() && rType->isBlockPointerType())) {
3002 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003003 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003004 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003005 }
3006 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003007 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003008 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003009
Steve Naroff936c4362008-06-03 14:04:54 +00003010 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003011 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003012 const PointerType *LPT = lType->getAsPointerType();
3013 const PointerType *RPT = rType->getAsPointerType();
3014 bool LPtrToVoid = LPT ?
3015 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3016 bool RPtrToVoid = RPT ?
3017 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3018
3019 if (!LPtrToVoid && !RPtrToVoid &&
3020 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003021 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003022 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003023 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003024 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003025 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003026 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003027 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003028 }
Steve Naroff936c4362008-06-03 14:04:54 +00003029 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3030 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003031 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003032 } else {
3033 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003034 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003035 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003036 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003037 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003038 }
Steve Naroff936c4362008-06-03 14:04:54 +00003039 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003040 }
Steve Naroff936c4362008-06-03 14:04:54 +00003041 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3042 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003043 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003044 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003045 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003046 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003047 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003048 }
Steve Naroff936c4362008-06-03 14:04:54 +00003049 if (lType->isIntegerType() &&
3050 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003051 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003052 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003053 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003054 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003055 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003056 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003057 // Handle block pointers.
3058 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3059 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003060 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003061 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003062 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003063 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003064 }
3065 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3066 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003067 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003068 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003069 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003070 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003071 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003072 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003073}
3074
Nate Begemanc5f0f652008-07-14 18:02:46 +00003075/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3076/// operates on extended vector types. Instead of producing an IntTy result,
3077/// like a scalar comparison, a vector comparison produces a vector of integer
3078/// types.
3079QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003081 bool isRelational) {
3082 // Check to make sure we're operating on vectors of the same type and width,
3083 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003084 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003085 if (vType.isNull())
3086 return vType;
3087
3088 QualType lType = lex->getType();
3089 QualType rType = rex->getType();
3090
3091 // For non-floating point types, check for self-comparisons of the form
3092 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3093 // often indicate logic errors in the program.
3094 if (!lType->isFloatingType()) {
3095 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3096 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3097 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003098 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003099 }
3100
3101 // Check for comparisons of floating point operands using != and ==.
3102 if (!isRelational && lType->isFloatingType()) {
3103 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003104 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003105 }
3106
3107 // Return the type for the comparison, which is the same as vector type for
3108 // integer vectors, or an integer type of identical size and number of
3109 // elements for floating point vectors.
3110 if (lType->isIntegerType())
3111 return lType;
3112
3113 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003114 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003115 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003116 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003117 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3118 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3119
3120 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3121 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003122 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3123}
3124
Chris Lattner4b009652007-07-25 00:24:17 +00003125inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003126 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003127{
3128 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003129 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003130
Steve Naroff8f708362007-08-24 19:07:16 +00003131 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003132
3133 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003134 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003135 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003136}
3137
3138inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003139 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003140{
3141 UsualUnaryConversions(lex);
3142 UsualUnaryConversions(rex);
3143
Eli Friedmanbea3f842008-05-13 20:16:47 +00003144 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003145 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003146 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003147}
3148
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003149/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3150/// is a read-only property; return true if so. A readonly property expression
3151/// depends on various declarations and thus must be treated specially.
3152///
3153static bool IsReadonlyProperty(Expr *E, Sema &S)
3154{
3155 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3156 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3157 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3158 QualType BaseType = PropExpr->getBase()->getType();
3159 if (const PointerType *PTy = BaseType->getAsPointerType())
3160 if (const ObjCInterfaceType *IFTy =
3161 PTy->getPointeeType()->getAsObjCInterfaceType())
3162 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3163 if (S.isPropertyReadonly(PDecl, IFace))
3164 return true;
3165 }
3166 }
3167 return false;
3168}
3169
Chris Lattner4c2642c2008-11-18 01:22:49 +00003170/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3171/// emit an error and return true. If so, return false.
3172static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003173 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3174 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3175 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003176 if (IsLV == Expr::MLV_Valid)
3177 return false;
3178
3179 unsigned Diag = 0;
3180 bool NeedType = false;
3181 switch (IsLV) { // C99 6.5.16p2
3182 default: assert(0 && "Unknown result from isModifiableLvalue!");
3183 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003184 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003185 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3186 NeedType = true;
3187 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003188 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003189 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3190 NeedType = true;
3191 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003192 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003193 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3194 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003195 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003196 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3197 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003198 case Expr::MLV_IncompleteType:
3199 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003200 return S.DiagnoseIncompleteType(Loc, E->getType(),
3201 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3202 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003203 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003204 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3205 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003206 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003207 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3208 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003209 case Expr::MLV_ReadonlyProperty:
3210 Diag = diag::error_readonly_property_assignment;
3211 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003212 case Expr::MLV_NoSetterProperty:
3213 Diag = diag::error_nosetter_property_assignment;
3214 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003215 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003216
Chris Lattner4c2642c2008-11-18 01:22:49 +00003217 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003218 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003219 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003220 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003221 return true;
3222}
3223
3224
3225
3226// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003227QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3228 SourceLocation Loc,
3229 QualType CompoundType) {
3230 // Verify that LHS is a modifiable lvalue, and emit error if not.
3231 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003232 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003233
3234 QualType LHSType = LHS->getType();
3235 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003236
Chris Lattner005ed752008-01-04 18:04:52 +00003237 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003238 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003239 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003240 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003241 // Special case of NSObject attributes on c-style pointer types.
3242 if (ConvTy == IncompatiblePointer &&
3243 ((Context.isObjCNSObjectType(LHSType) &&
3244 Context.isObjCObjectPointerType(RHSType)) ||
3245 (Context.isObjCNSObjectType(RHSType) &&
3246 Context.isObjCObjectPointerType(LHSType))))
3247 ConvTy = Compatible;
3248
Chris Lattner34c85082008-08-21 18:04:13 +00003249 // If the RHS is a unary plus or minus, check to see if they = and + are
3250 // right next to each other. If so, the user may have typo'd "x =+ 4"
3251 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003253 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3254 RHSCheck = ICE->getSubExpr();
3255 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3256 if ((UO->getOpcode() == UnaryOperator::Plus ||
3257 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003258 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003259 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003260 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003261 Diag(Loc, diag::warn_not_compound_assign)
3262 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3263 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003264 }
3265 } else {
3266 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003267 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003268 }
Chris Lattner005ed752008-01-04 18:04:52 +00003269
Chris Lattner1eafdea2008-11-18 01:30:42 +00003270 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3271 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003272 return QualType();
3273
Chris Lattner4b009652007-07-25 00:24:17 +00003274 // C99 6.5.16p3: The type of an assignment expression is the type of the
3275 // left operand unless the left operand has qualified type, in which case
3276 // it is the unqualified version of the type of the left operand.
3277 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3278 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003279 // C++ 5.17p1: the type of the assignment expression is that of its left
3280 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003281 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003282}
3283
Chris Lattner1eafdea2008-11-18 01:30:42 +00003284// C99 6.5.17
3285QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3286 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003287
3288 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003289 DefaultFunctionArrayConversion(RHS);
3290 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003291}
3292
3293/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3294/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003295QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3296 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003297 QualType ResType = Op->getType();
3298 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003299
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003300 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3301 // Decrement of bool is not allowed.
3302 if (!isInc) {
3303 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3304 return QualType();
3305 }
3306 // Increment of bool sets it to true, but is deprecated.
3307 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3308 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003309 // OK!
3310 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3311 // C99 6.5.2.4p2, 6.5.6p2
3312 if (PT->getPointeeType()->isObjectType()) {
3313 // Pointer to object is ok!
3314 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003315 if (getLangOptions().CPlusPlus) {
3316 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3317 << Op->getSourceRange();
3318 return QualType();
3319 }
3320
3321 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003322 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003323 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003324 if (getLangOptions().CPlusPlus) {
3325 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3326 << Op->getType() << Op->getSourceRange();
3327 return QualType();
3328 }
3329
3330 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003331 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003332 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003333 } else {
3334 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3335 diag::err_typecheck_arithmetic_incomplete_type,
3336 Op->getSourceRange(), SourceRange(),
3337 ResType);
3338 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003339 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003340 } else if (ResType->isComplexType()) {
3341 // C99 does not support ++/-- on complex types, we allow as an extension.
3342 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003343 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003344 } else {
3345 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003346 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003347 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003348 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003349 // At this point, we know we have a real, complex or pointer type.
3350 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003351 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003352 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003353 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003354}
3355
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003356/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003357/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003358/// where the declaration is needed for type checking. We only need to
3359/// handle cases when the expression references a function designator
3360/// or is an lvalue. Here are some examples:
3361/// - &(x) => x
3362/// - &*****f => f for f a function designator.
3363/// - &s.xx => s
3364/// - &s.zz[1].yy -> s, if zz is an array
3365/// - *(x + 1) -> x, if x is an array
3366/// - &"123"[2] -> 0
3367/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003368static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003369 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003370 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003371 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003372 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003373 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003374 // Fields cannot be declared with a 'register' storage class.
3375 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003376 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003377 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003378 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003379 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003380 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003381
Douglas Gregord2baafd2008-10-21 16:13:35 +00003382 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003383 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003384 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003385 return 0;
3386 else
3387 return VD;
3388 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003389 case Stmt::UnaryOperatorClass: {
3390 UnaryOperator *UO = cast<UnaryOperator>(E);
3391
3392 switch(UO->getOpcode()) {
3393 case UnaryOperator::Deref: {
3394 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003395 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3396 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3397 if (!VD || VD->getType()->isPointerType())
3398 return 0;
3399 return VD;
3400 }
3401 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003402 }
3403 case UnaryOperator::Real:
3404 case UnaryOperator::Imag:
3405 case UnaryOperator::Extension:
3406 return getPrimaryDecl(UO->getSubExpr());
3407 default:
3408 return 0;
3409 }
3410 }
3411 case Stmt::BinaryOperatorClass: {
3412 BinaryOperator *BO = cast<BinaryOperator>(E);
3413
3414 // Handle cases involving pointer arithmetic. The result of an
3415 // Assign or AddAssign is not an lvalue so they can be ignored.
3416
3417 // (x + n) or (n + x) => x
3418 if (BO->getOpcode() == BinaryOperator::Add) {
3419 if (BO->getLHS()->getType()->isPointerType()) {
3420 return getPrimaryDecl(BO->getLHS());
3421 } else if (BO->getRHS()->getType()->isPointerType()) {
3422 return getPrimaryDecl(BO->getRHS());
3423 }
3424 }
3425
3426 return 0;
3427 }
Chris Lattner4b009652007-07-25 00:24:17 +00003428 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003429 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003430 case Stmt::ImplicitCastExprClass:
3431 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003432 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003433 default:
3434 return 0;
3435 }
3436}
3437
3438/// CheckAddressOfOperand - The operand of & must be either a function
3439/// designator or an lvalue designating an object. If it is an lvalue, the
3440/// object cannot be declared with storage class register or be a bit field.
3441/// Note: The usual conversions are *not* applied to the operand of the &
3442/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003443/// In C++, the operand might be an overloaded function name, in which case
3444/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003445QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003446 if (op->isTypeDependent())
3447 return Context.DependentTy;
3448
Steve Naroff9c6c3592008-01-13 17:10:08 +00003449 if (getLangOptions().C99) {
3450 // Implement C99-only parts of addressof rules.
3451 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3452 if (uOp->getOpcode() == UnaryOperator::Deref)
3453 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3454 // (assuming the deref expression is valid).
3455 return uOp->getSubExpr()->getType();
3456 }
3457 // Technically, there should be a check for array subscript
3458 // expressions here, but the result of one is always an lvalue anyway.
3459 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003460 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003461 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003462
Chris Lattner4b009652007-07-25 00:24:17 +00003463 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003464 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3465 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003466 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3467 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003468 return QualType();
3469 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003470 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003471 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3472 if (Field->isBitField()) {
3473 Diag(OpLoc, diag::err_typecheck_address_of)
3474 << "bit-field" << op->getSourceRange();
3475 return QualType();
3476 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003477 }
3478 // Check for Apple extension for accessing vector components.
3479 } else if (isa<ArraySubscriptExpr>(op) &&
3480 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003481 Diag(OpLoc, diag::err_typecheck_address_of)
3482 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003483 return QualType();
3484 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003485 // We have an lvalue with a decl. Make sure the decl is not declared
3486 // with the register storage-class specifier.
3487 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3488 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003489 Diag(OpLoc, diag::err_typecheck_address_of)
3490 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003491 return QualType();
3492 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003493 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003494 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003495 } else if (isa<FieldDecl>(dcl)) {
3496 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003497 // Could be a pointer to member, though, if there is an explicit
3498 // scope qualifier for the class.
3499 if (isa<QualifiedDeclRefExpr>(op)) {
3500 DeclContext *Ctx = dcl->getDeclContext();
3501 if (Ctx && Ctx->isRecord())
3502 return Context.getMemberPointerType(op->getType(),
3503 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3504 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003505 } else if (isa<FunctionDecl>(dcl)) {
3506 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003507 // As above.
3508 if (isa<QualifiedDeclRefExpr>(op)) {
3509 DeclContext *Ctx = dcl->getDeclContext();
3510 if (Ctx && Ctx->isRecord())
3511 return Context.getMemberPointerType(op->getType(),
3512 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3513 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003514 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003515 else
Chris Lattner4b009652007-07-25 00:24:17 +00003516 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003517 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003518
Chris Lattner4b009652007-07-25 00:24:17 +00003519 // If the operand has type "type", the result has type "pointer to type".
3520 return Context.getPointerType(op->getType());
3521}
3522
Chris Lattnerda5c0872008-11-23 09:13:29 +00003523QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3524 UsualUnaryConversions(Op);
3525 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003526
Chris Lattnerda5c0872008-11-23 09:13:29 +00003527 // Note that per both C89 and C99, this is always legal, even if ptype is an
3528 // incomplete type or void. It would be possible to warn about dereferencing
3529 // a void pointer, but it's completely well-defined, and such a warning is
3530 // unlikely to catch any mistakes.
3531 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003532 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003533
Chris Lattner77d52da2008-11-20 06:06:08 +00003534 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003535 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003536 return QualType();
3537}
3538
3539static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3540 tok::TokenKind Kind) {
3541 BinaryOperator::Opcode Opc;
3542 switch (Kind) {
3543 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003544 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3545 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003546 case tok::star: Opc = BinaryOperator::Mul; break;
3547 case tok::slash: Opc = BinaryOperator::Div; break;
3548 case tok::percent: Opc = BinaryOperator::Rem; break;
3549 case tok::plus: Opc = BinaryOperator::Add; break;
3550 case tok::minus: Opc = BinaryOperator::Sub; break;
3551 case tok::lessless: Opc = BinaryOperator::Shl; break;
3552 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3553 case tok::lessequal: Opc = BinaryOperator::LE; break;
3554 case tok::less: Opc = BinaryOperator::LT; break;
3555 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3556 case tok::greater: Opc = BinaryOperator::GT; break;
3557 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3558 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3559 case tok::amp: Opc = BinaryOperator::And; break;
3560 case tok::caret: Opc = BinaryOperator::Xor; break;
3561 case tok::pipe: Opc = BinaryOperator::Or; break;
3562 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3563 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3564 case tok::equal: Opc = BinaryOperator::Assign; break;
3565 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3566 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3567 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3568 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3569 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3570 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3571 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3572 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3573 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3574 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3575 case tok::comma: Opc = BinaryOperator::Comma; break;
3576 }
3577 return Opc;
3578}
3579
3580static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3581 tok::TokenKind Kind) {
3582 UnaryOperator::Opcode Opc;
3583 switch (Kind) {
3584 default: assert(0 && "Unknown unary op!");
3585 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3586 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3587 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3588 case tok::star: Opc = UnaryOperator::Deref; break;
3589 case tok::plus: Opc = UnaryOperator::Plus; break;
3590 case tok::minus: Opc = UnaryOperator::Minus; break;
3591 case tok::tilde: Opc = UnaryOperator::Not; break;
3592 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003593 case tok::kw___real: Opc = UnaryOperator::Real; break;
3594 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3595 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3596 }
3597 return Opc;
3598}
3599
Douglas Gregord7f915e2008-11-06 23:29:22 +00003600/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3601/// operator @p Opc at location @c TokLoc. This routine only supports
3602/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003603Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3604 unsigned Op,
3605 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003606 QualType ResultTy; // Result type of the binary operator.
3607 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3608 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3609
3610 switch (Opc) {
3611 default:
3612 assert(0 && "Unknown binary expr!");
3613 case BinaryOperator::Assign:
3614 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3615 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003616 case BinaryOperator::PtrMemD:
3617 case BinaryOperator::PtrMemI:
3618 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3619 Opc == BinaryOperator::PtrMemI);
3620 break;
3621 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003622 case BinaryOperator::Div:
3623 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3624 break;
3625 case BinaryOperator::Rem:
3626 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3627 break;
3628 case BinaryOperator::Add:
3629 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3630 break;
3631 case BinaryOperator::Sub:
3632 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3633 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003634 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003635 case BinaryOperator::Shr:
3636 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3637 break;
3638 case BinaryOperator::LE:
3639 case BinaryOperator::LT:
3640 case BinaryOperator::GE:
3641 case BinaryOperator::GT:
3642 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3643 break;
3644 case BinaryOperator::EQ:
3645 case BinaryOperator::NE:
3646 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3647 break;
3648 case BinaryOperator::And:
3649 case BinaryOperator::Xor:
3650 case BinaryOperator::Or:
3651 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3652 break;
3653 case BinaryOperator::LAnd:
3654 case BinaryOperator::LOr:
3655 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3656 break;
3657 case BinaryOperator::MulAssign:
3658 case BinaryOperator::DivAssign:
3659 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3660 if (!CompTy.isNull())
3661 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3662 break;
3663 case BinaryOperator::RemAssign:
3664 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3665 if (!CompTy.isNull())
3666 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3667 break;
3668 case BinaryOperator::AddAssign:
3669 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3670 if (!CompTy.isNull())
3671 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3672 break;
3673 case BinaryOperator::SubAssign:
3674 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3675 if (!CompTy.isNull())
3676 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3677 break;
3678 case BinaryOperator::ShlAssign:
3679 case BinaryOperator::ShrAssign:
3680 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3681 if (!CompTy.isNull())
3682 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3683 break;
3684 case BinaryOperator::AndAssign:
3685 case BinaryOperator::XorAssign:
3686 case BinaryOperator::OrAssign:
3687 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3688 if (!CompTy.isNull())
3689 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3690 break;
3691 case BinaryOperator::Comma:
3692 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3693 break;
3694 }
3695 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003696 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003697 if (CompTy.isNull())
3698 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3699 else
3700 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003701 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003702}
3703
Chris Lattner4b009652007-07-25 00:24:17 +00003704// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003705Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3706 tok::TokenKind Kind,
3707 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003708 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003709 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003710
Steve Naroff87d58b42007-09-16 03:34:24 +00003711 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3712 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003713
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003714 // If either expression is type-dependent, just build the AST.
3715 // FIXME: We'll need to perform some caching of the result of name
3716 // lookup for operator+.
3717 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003718 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3719 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003720 Context.DependentTy,
3721 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003722 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003723 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3724 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003725 }
3726
Sebastian Redl95216a62009-02-07 00:15:38 +00003727 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003728 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3729 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003730 // If this is one of the assignment operators, we only perform
3731 // overload resolution if the left-hand side is a class or
3732 // enumeration type (C++ [expr.ass]p3).
3733 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3734 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3735 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3736 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003737
Douglas Gregord7f915e2008-11-06 23:29:22 +00003738 // Determine which overloaded operator we're dealing with.
3739 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003740 // Overloading .* is not possible.
3741 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003742 OO_Star, OO_Slash, OO_Percent,
3743 OO_Plus, OO_Minus,
3744 OO_LessLess, OO_GreaterGreater,
3745 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3746 OO_EqualEqual, OO_ExclaimEqual,
3747 OO_Amp,
3748 OO_Caret,
3749 OO_Pipe,
3750 OO_AmpAmp,
3751 OO_PipePipe,
3752 OO_Equal, OO_StarEqual,
3753 OO_SlashEqual, OO_PercentEqual,
3754 OO_PlusEqual, OO_MinusEqual,
3755 OO_LessLessEqual, OO_GreaterGreaterEqual,
3756 OO_AmpEqual, OO_CaretEqual,
3757 OO_PipeEqual,
3758 OO_Comma
3759 };
3760 OverloadedOperatorKind OverOp = OverOps[Opc];
3761
Douglas Gregor5ed15042008-11-18 23:14:02 +00003762 // Add the appropriate overloaded operators (C++ [over.match.oper])
3763 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003764 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003765 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003766 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3767 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003768
3769 // Perform overload resolution.
3770 OverloadCandidateSet::iterator Best;
3771 switch (BestViableFunction(CandidateSet, Best)) {
3772 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003773 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003774 FunctionDecl *FnDecl = Best->Function;
3775
Douglas Gregor70d26122008-11-12 17:17:38 +00003776 if (FnDecl) {
3777 // We matched an overloaded operator. Build a call to that
3778 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003779
Douglas Gregor70d26122008-11-12 17:17:38 +00003780 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003781 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3782 if (PerformObjectArgumentInitialization(lhs, Method) ||
3783 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3784 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003785 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003786 } else {
3787 // Convert the arguments.
3788 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3789 "passing") ||
3790 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3791 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003792 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003793 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003794
Douglas Gregor70d26122008-11-12 17:17:38 +00003795 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003796 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003797 = FnDecl->getType()->getAsFunctionType()->getResultType();
3798 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003799
Douglas Gregor70d26122008-11-12 17:17:38 +00003800 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003801 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3802 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003803 UsualUnaryConversions(FnExpr);
3804
Ted Kremenek362abcd2009-02-09 20:51:47 +00003805 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003806 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003807 } else {
3808 // We matched a built-in operator. Convert the arguments, then
3809 // break out so that we will build the appropriate built-in
3810 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003811 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3812 Best->Conversions[0], "passing") ||
3813 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3814 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003815 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003816
3817 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003818 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003819 }
3820
3821 case OR_No_Viable_Function:
3822 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003823 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003824 break;
3825
3826 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003827 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3828 << BinaryOperator::getOpcodeStr(Opc)
3829 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003830 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003831 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003832 }
3833
Douglas Gregor70d26122008-11-12 17:17:38 +00003834 // Either we found no viable overloaded operator or we matched a
3835 // built-in operator. In either case, fall through to trying to
3836 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003837 }
3838
Douglas Gregord7f915e2008-11-06 23:29:22 +00003839 // Build a built-in binary operation.
3840 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003841}
3842
3843// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003844Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3845 tok::TokenKind Op, ExprArg input) {
3846 // FIXME: Input is modified later, but smart pointer not reassigned.
3847 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003848 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003849
3850 if (getLangOptions().CPlusPlus &&
3851 (Input->getType()->isRecordType()
3852 || Input->getType()->isEnumeralType())) {
3853 // Determine which overloaded operator we're dealing with.
3854 static const OverloadedOperatorKind OverOps[] = {
3855 OO_None, OO_None,
3856 OO_PlusPlus, OO_MinusMinus,
3857 OO_Amp, OO_Star,
3858 OO_Plus, OO_Minus,
3859 OO_Tilde, OO_Exclaim,
3860 OO_None, OO_None,
3861 OO_None,
3862 OO_None
3863 };
3864 OverloadedOperatorKind OverOp = OverOps[Opc];
3865
3866 // Add the appropriate overloaded operators (C++ [over.match.oper])
3867 // to the candidate set.
3868 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003869 if (OverOp != OO_None &&
3870 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3871 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003872
3873 // Perform overload resolution.
3874 OverloadCandidateSet::iterator Best;
3875 switch (BestViableFunction(CandidateSet, Best)) {
3876 case OR_Success: {
3877 // We found a built-in operator or an overloaded operator.
3878 FunctionDecl *FnDecl = Best->Function;
3879
3880 if (FnDecl) {
3881 // We matched an overloaded operator. Build a call to that
3882 // operator.
3883
3884 // Convert the arguments.
3885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3886 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003887 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003888 } else {
3889 // Convert the arguments.
3890 if (PerformCopyInitialization(Input,
3891 FnDecl->getParamDecl(0)->getType(),
3892 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003893 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003894 }
3895
3896 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003897 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003898 = FnDecl->getType()->getAsFunctionType()->getResultType();
3899 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003900
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003901 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003902 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3903 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003904 UsualUnaryConversions(FnExpr);
3905
Sebastian Redl8b769972009-01-19 00:08:26 +00003906 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003907 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003908 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003909 } else {
3910 // We matched a built-in operator. Convert the arguments, then
3911 // break out so that we will build the appropriate built-in
3912 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003913 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3914 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003915 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003916
3917 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003918 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003919 }
3920
3921 case OR_No_Viable_Function:
3922 // No viable function; fall through to handling this as a
3923 // built-in operator, which will produce an error message for us.
3924 break;
3925
3926 case OR_Ambiguous:
3927 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3928 << UnaryOperator::getOpcodeStr(Opc)
3929 << Input->getSourceRange();
3930 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003931 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003932 }
3933
3934 // Either we found no viable overloaded operator or we matched a
3935 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003936 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003937 }
3938
Chris Lattner4b009652007-07-25 00:24:17 +00003939 QualType resultType;
3940 switch (Opc) {
3941 default:
3942 assert(0 && "Unimplemented unary expr!");
3943 case UnaryOperator::PreInc:
3944 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003945 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3946 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003947 break;
3948 case UnaryOperator::AddrOf:
3949 resultType = CheckAddressOfOperand(Input, OpLoc);
3950 break;
3951 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003952 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003953 resultType = CheckIndirectionOperand(Input, OpLoc);
3954 break;
3955 case UnaryOperator::Plus:
3956 case UnaryOperator::Minus:
3957 UsualUnaryConversions(Input);
3958 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003959 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3960 break;
3961 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3962 resultType->isEnumeralType())
3963 break;
3964 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3965 Opc == UnaryOperator::Plus &&
3966 resultType->isPointerType())
3967 break;
3968
Sebastian Redl8b769972009-01-19 00:08:26 +00003969 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3970 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003971 case UnaryOperator::Not: // bitwise complement
3972 UsualUnaryConversions(Input);
3973 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003974 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3975 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3976 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003977 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003978 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003979 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003980 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3981 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003982 break;
3983 case UnaryOperator::LNot: // logical negation
3984 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3985 DefaultFunctionArrayConversion(Input);
3986 resultType = Input->getType();
3987 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003988 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3989 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003990 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003991 // In C++, it's bool. C++ 5.3.1p8
3992 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003993 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003994 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003995 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003996 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003997 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003998 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003999 resultType = Input->getType();
4000 break;
4001 }
4002 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004003 return ExprError();
4004 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004005 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004006}
4007
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004008/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4009Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004010 SourceLocation LabLoc,
4011 IdentifierInfo *LabelII) {
4012 // Look up the record for this label identifier.
4013 LabelStmt *&LabelDecl = LabelMap[LabelII];
4014
Daniel Dunbar879788d2008-08-04 16:51:22 +00004015 // If we haven't seen this label yet, create a forward reference. It
4016 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004017 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004018 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004019
4020 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004021 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4022 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004023}
4024
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004025Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004026 SourceLocation RPLoc) { // "({..})"
4027 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4028 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4029 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4030
Eli Friedmanbc941e12009-01-24 23:09:00 +00004031 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4032 if (isFileScope) {
4033 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4034 }
4035
Chris Lattner4b009652007-07-25 00:24:17 +00004036 // FIXME: there are a variety of strange constraints to enforce here, for
4037 // example, it is not possible to goto into a stmt expression apparently.
4038 // More semantic analysis is needed.
4039
4040 // FIXME: the last statement in the compount stmt has its value used. We
4041 // should not warn about it being unused.
4042
4043 // If there are sub stmts in the compound stmt, take the type of the last one
4044 // as the type of the stmtexpr.
4045 QualType Ty = Context.VoidTy;
4046
Chris Lattner200964f2008-07-26 19:51:01 +00004047 if (!Compound->body_empty()) {
4048 Stmt *LastStmt = Compound->body_back();
4049 // If LastStmt is a label, skip down through into the body.
4050 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4051 LastStmt = Label->getSubStmt();
4052
4053 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004054 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004055 }
Chris Lattner4b009652007-07-25 00:24:17 +00004056
Steve Naroff774e4152009-01-21 00:14:39 +00004057 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004058}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004059
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004060Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4061 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004062 SourceLocation TypeLoc,
4063 TypeTy *argty,
4064 OffsetOfComponent *CompPtr,
4065 unsigned NumComponents,
4066 SourceLocation RPLoc) {
4067 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4068 assert(!ArgTy.isNull() && "Missing type argument!");
4069
4070 // We must have at least one component that refers to the type, and the first
4071 // one is known to be a field designator. Verify that the ArgTy represents
4072 // a struct/union/class.
4073 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004074 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004075
4076 // Otherwise, create a compound literal expression as the base, and
4077 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004078 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004079 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004080 IList->setType(ArgTy);
4081 Expr *Res =
4082 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4083
Chris Lattnerb37522e2007-08-31 21:49:13 +00004084 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4085 // GCC extension, diagnose them.
4086 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004087 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4088 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004089
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004090 for (unsigned i = 0; i != NumComponents; ++i) {
4091 const OffsetOfComponent &OC = CompPtr[i];
4092 if (OC.isBrackets) {
4093 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004094 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004095 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004096 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004097 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004098 }
4099
Chris Lattner2af6a802007-08-30 17:59:59 +00004100 // FIXME: C++: Verify that operator[] isn't overloaded.
4101
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004102 // C99 6.5.2.1p1
4103 Expr *Idx = static_cast<Expr*>(OC.U.E);
4104 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004105 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4106 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004107
Steve Naroff774e4152009-01-21 00:14:39 +00004108 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4109 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004110 continue;
4111 }
4112
4113 const RecordType *RC = Res->getType()->getAsRecordType();
4114 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004115 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004116 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004117 }
4118
4119 // Get the decl corresponding to this.
4120 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004121 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004122 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4123 LookupMemberName)
4124 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004125 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004126 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4127 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004128
4129 // FIXME: C++: Verify that MemberDecl isn't a static field.
4130 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004131 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4132 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004133 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4134 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004135 }
4136
Steve Naroff774e4152009-01-21 00:14:39 +00004137 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4138 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004139}
4140
4141
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004142Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004143 TypeTy *arg1, TypeTy *arg2,
4144 SourceLocation RPLoc) {
4145 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4146 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4147
4148 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4149
Steve Naroff774e4152009-01-21 00:14:39 +00004150 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4151 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004152}
4153
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004154Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004155 ExprTy *expr1, ExprTy *expr2,
4156 SourceLocation RPLoc) {
4157 Expr *CondExpr = static_cast<Expr*>(cond);
4158 Expr *LHSExpr = static_cast<Expr*>(expr1);
4159 Expr *RHSExpr = static_cast<Expr*>(expr2);
4160
4161 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4162
4163 // The conditional expression is required to be a constant expression.
4164 llvm::APSInt condEval(32);
4165 SourceLocation ExpLoc;
4166 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004167 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4168 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004169
4170 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4171 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4172 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004173 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4174 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004175}
4176
Steve Naroff52a81c02008-09-03 18:15:37 +00004177//===----------------------------------------------------------------------===//
4178// Clang Extensions.
4179//===----------------------------------------------------------------------===//
4180
4181/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004182void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004183 // Analyze block parameters.
4184 BlockSemaInfo *BSI = new BlockSemaInfo();
4185
4186 // Add BSI to CurBlock.
4187 BSI->PrevBlockInfo = CurBlock;
4188 CurBlock = BSI;
4189
4190 BSI->ReturnType = 0;
4191 BSI->TheScope = BlockScope;
4192
Steve Naroff52059382008-10-10 01:28:17 +00004193 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004194 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004195}
4196
Mike Stumpc1fddff2009-02-04 22:31:32 +00004197void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4198 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4199
4200 if (ParamInfo.getNumTypeObjects() == 0
4201 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4202 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4203
4204 // The type is entirely optional as well, if none, use DependentTy.
4205 if (T.isNull())
4206 T = Context.DependentTy;
4207
4208 // The parameter list is optional, if there was none, assume ().
4209 if (!T->isFunctionType())
4210 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4211
4212 CurBlock->hasPrototype = true;
4213 CurBlock->isVariadic = false;
4214 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4215 .getTypePtr();
4216
4217 if (!RetTy->isDependentType())
4218 CurBlock->ReturnType = RetTy;
4219 return;
4220 }
4221
Steve Naroff52a81c02008-09-03 18:15:37 +00004222 // Analyze arguments to block.
4223 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4224 "Not a function declarator!");
4225 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004226
Steve Naroff52059382008-10-10 01:28:17 +00004227 CurBlock->hasPrototype = FTI.hasPrototype;
4228 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004229
4230 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4231 // no arguments, not a function that takes a single void argument.
4232 if (FTI.hasPrototype &&
4233 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4234 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4235 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4236 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004237 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004238 } else if (FTI.hasPrototype) {
4239 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004240 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4241 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004242 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4243
4244 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4245 .getTypePtr();
4246
4247 if (!RetTy->isDependentType())
4248 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004249 }
Steve Naroff52059382008-10-10 01:28:17 +00004250 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4251
4252 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4253 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4254 // If this has an identifier, add it to the scope stack.
4255 if ((*AI)->getIdentifier())
4256 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004257}
4258
4259/// ActOnBlockError - If there is an error parsing a block, this callback
4260/// is invoked to pop the information about the block from the action impl.
4261void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4262 // Ensure that CurBlock is deleted.
4263 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4264
4265 // Pop off CurBlock, handle nested blocks.
4266 CurBlock = CurBlock->PrevBlockInfo;
4267
4268 // FIXME: Delete the ParmVarDecl objects as well???
4269
4270}
4271
4272/// ActOnBlockStmtExpr - This is called when the body of a block statement
4273/// literal was successfully completed. ^(int x){...}
4274Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4275 Scope *CurScope) {
4276 // Ensure that CurBlock is deleted.
4277 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004278 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004279
Steve Naroff52059382008-10-10 01:28:17 +00004280 PopDeclContext();
4281
Steve Naroff52a81c02008-09-03 18:15:37 +00004282 // Pop off CurBlock, handle nested blocks.
4283 CurBlock = CurBlock->PrevBlockInfo;
4284
4285 QualType RetTy = Context.VoidTy;
4286 if (BSI->ReturnType)
4287 RetTy = QualType(BSI->ReturnType, 0);
4288
4289 llvm::SmallVector<QualType, 8> ArgTypes;
4290 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4291 ArgTypes.push_back(BSI->Params[i]->getType());
4292
4293 QualType BlockTy;
4294 if (!BSI->hasPrototype)
4295 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4296 else
4297 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004298 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004299
4300 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004301
Steve Naroff95029d92008-10-08 18:44:00 +00004302 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004303 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004304}
4305
Nate Begemanbd881ef2008-01-30 20:50:20 +00004306/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004307/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004308/// The number of arguments has already been validated to match the number of
4309/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004310static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4311 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004312 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004313 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004314 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4315 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004316
4317 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004318 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004319 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004320 return true;
4321}
4322
4323Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4324 SourceLocation *CommaLocs,
4325 SourceLocation BuiltinLoc,
4326 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004327 // __builtin_overload requires at least 2 arguments
4328 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004329 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4330 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004331
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004332 // The first argument is required to be a constant expression. It tells us
4333 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004334 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004335 Expr *NParamsExpr = Args[0];
4336 llvm::APSInt constEval(32);
4337 SourceLocation ExpLoc;
4338 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004339 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4340 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004341
4342 // Verify that the number of parameters is > 0
4343 unsigned NumParams = constEval.getZExtValue();
4344 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004345 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4346 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004347 // Verify that we have at least 1 + NumParams arguments to the builtin.
4348 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004349 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4350 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004351
4352 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004353 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004354 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004355 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4356 // UsualUnaryConversions will convert the function DeclRefExpr into a
4357 // pointer to function.
4358 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004359 const FunctionTypeProto *FnType = 0;
4360 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4361 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004362
4363 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4364 // parameters, and the number of parameters must match the value passed to
4365 // the builtin.
4366 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004367 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4368 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004369
4370 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004371 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004372 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004373 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004374 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004375 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4376 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004377 // Remember our match, and continue processing the remaining arguments
4378 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004379 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004380 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004381 BuiltinLoc, RParenLoc);
4382 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004383 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004384 // Return the newly created OverloadExpr node, if we succeded in matching
4385 // exactly one of the candidate functions.
4386 if (OE)
4387 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004388
4389 // If we didn't find a matching function Expr in the __builtin_overload list
4390 // the return an error.
4391 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004392 for (unsigned i = 0; i != NumParams; ++i) {
4393 if (i != 0) typeNames += ", ";
4394 typeNames += Args[i+1]->getType().getAsString();
4395 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004396
Chris Lattner77d52da2008-11-20 06:06:08 +00004397 return Diag(BuiltinLoc, diag::err_overload_no_match)
4398 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004399}
4400
Anders Carlsson36760332007-10-15 20:28:48 +00004401Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4402 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004403 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004404 Expr *E = static_cast<Expr*>(expr);
4405 QualType T = QualType::getFromOpaquePtr(type);
4406
4407 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004408
4409 // Get the va_list type
4410 QualType VaListType = Context.getBuiltinVaListType();
4411 // Deal with implicit array decay; for example, on x86-64,
4412 // va_list is an array, but it's supposed to decay to
4413 // a pointer for va_arg.
4414 if (VaListType->isArrayType())
4415 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004416 // Make sure the input expression also decays appropriately.
4417 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004418
4419 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004420 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004421 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004422 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004423
4424 // FIXME: Warn if a non-POD type is passed in.
4425
Steve Naroff774e4152009-01-21 00:14:39 +00004426 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004427}
4428
Douglas Gregorad4b3792008-11-29 04:51:27 +00004429Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4430 // The type of __null will be int or long, depending on the size of
4431 // pointers on the target.
4432 QualType Ty;
4433 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4434 Ty = Context.IntTy;
4435 else
4436 Ty = Context.LongTy;
4437
Steve Naroff774e4152009-01-21 00:14:39 +00004438 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004439}
4440
Chris Lattner005ed752008-01-04 18:04:52 +00004441bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4442 SourceLocation Loc,
4443 QualType DstType, QualType SrcType,
4444 Expr *SrcExpr, const char *Flavor) {
4445 // Decode the result (notice that AST's are still created for extensions).
4446 bool isInvalid = false;
4447 unsigned DiagKind;
4448 switch (ConvTy) {
4449 default: assert(0 && "Unknown conversion type");
4450 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004451 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004452 DiagKind = diag::ext_typecheck_convert_pointer_int;
4453 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004454 case IntToPointer:
4455 DiagKind = diag::ext_typecheck_convert_int_pointer;
4456 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004457 case IncompatiblePointer:
4458 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4459 break;
4460 case FunctionVoidPointer:
4461 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4462 break;
4463 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004464 // If the qualifiers lost were because we were applying the
4465 // (deprecated) C++ conversion from a string literal to a char*
4466 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4467 // Ideally, this check would be performed in
4468 // CheckPointerTypesForAssignment. However, that would require a
4469 // bit of refactoring (so that the second argument is an
4470 // expression, rather than a type), which should be done as part
4471 // of a larger effort to fix CheckPointerTypesForAssignment for
4472 // C++ semantics.
4473 if (getLangOptions().CPlusPlus &&
4474 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4475 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004476 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4477 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004478 case IntToBlockPointer:
4479 DiagKind = diag::err_int_to_block_pointer;
4480 break;
4481 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004482 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004483 break;
Steve Naroff19608432008-10-14 22:18:38 +00004484 case IncompatibleObjCQualifiedId:
4485 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4486 // it can give a more specific diagnostic.
4487 DiagKind = diag::warn_incompatible_qualified_id;
4488 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004489 case IncompatibleVectors:
4490 DiagKind = diag::warn_incompatible_vectors;
4491 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004492 case Incompatible:
4493 DiagKind = diag::err_typecheck_convert_incompatible;
4494 isInvalid = true;
4495 break;
4496 }
4497
Chris Lattner271d4c22008-11-24 05:29:24 +00004498 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4499 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004500 return isInvalid;
4501}
Anders Carlssond5201b92008-11-30 19:50:32 +00004502
4503bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4504{
4505 Expr::EvalResult EvalResult;
4506
4507 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4508 EvalResult.HasSideEffects) {
4509 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4510
4511 if (EvalResult.Diag) {
4512 // We only show the note if it's not the usual "invalid subexpression"
4513 // or if it's actually in a subexpression.
4514 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4515 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4516 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4517 }
4518
4519 return true;
4520 }
4521
4522 if (EvalResult.Diag) {
4523 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4524 E->getSourceRange();
4525
4526 // Print the reason it's not a constant.
4527 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4528 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4529 }
4530
4531 if (Result)
4532 *Result = EvalResult.Val.getInt();
4533 return false;
4534}