blob: 6ec4d4a61f348fc7d067c075e48441414a3e92d4 [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"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#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!
Steve Naroff774e4152009-01-21 00:14:39 +0000322 return Owned(new (Context) StringLiteral(Literal.GetString(),
323 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,
367 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000368 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
369}
370
Douglas Gregor566782a2009-01-06 05:10:23 +0000371/// BuildDeclRefExpr - Build either a DeclRefExpr or a
372/// QualifiedDeclRefExpr based on whether or not SS is a
373/// nested-name-specifier.
374DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
375 bool TypeDependent, bool ValueDependent,
376 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000377 if (SS && !SS->isEmpty())
378 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000379 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000380 else
381 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000382}
383
Douglas Gregor723d3332009-01-07 00:43:41 +0000384/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
385/// variable corresponding to the anonymous union or struct whose type
386/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000387static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000388 assert(Record->isAnonymousStructOrUnion() &&
389 "Record must be an anonymous struct or union!");
390
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000391 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000392 // be an O(1) operation rather than a slow walk through DeclContext's
393 // vector (which itself will be eliminated). DeclGroups might make
394 // this even better.
395 DeclContext *Ctx = Record->getDeclContext();
396 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
397 DEnd = Ctx->decls_end();
398 D != DEnd; ++D) {
399 if (*D == Record) {
400 // The object for the anonymous struct/union directly
401 // follows its type in the list of declarations.
402 ++D;
403 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000404 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000405 return *D;
406 }
407 }
408
409 assert(false && "Missing object for anonymous record");
410 return 0;
411}
412
Sebastian Redlcd883f72009-01-18 18:53:16 +0000413Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000414Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
415 FieldDecl *Field,
416 Expr *BaseObjectExpr,
417 SourceLocation OpLoc) {
418 assert(Field->getDeclContext()->isRecord() &&
419 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
420 && "Field must be stored inside an anonymous struct or union");
421
422 // Construct the sequence of field member references
423 // we'll have to perform to get to the field in the anonymous
424 // union/struct. The list of members is built from the field
425 // outward, so traverse it backwards to go from an object in
426 // the current context to the field we found.
427 llvm::SmallVector<FieldDecl *, 4> AnonFields;
428 AnonFields.push_back(Field);
429 VarDecl *BaseObject = 0;
430 DeclContext *Ctx = Field->getDeclContext();
431 do {
432 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000433 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000434 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
435 AnonFields.push_back(AnonField);
436 else {
437 BaseObject = cast<VarDecl>(AnonObject);
438 break;
439 }
440 Ctx = Ctx->getParent();
441 } while (Ctx->isRecord() &&
442 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
443
444 // Build the expression that refers to the base object, from
445 // which we will build a sequence of member references to each
446 // of the anonymous union objects and, eventually, the field we
447 // found via name lookup.
448 bool BaseObjectIsPointer = false;
449 unsigned ExtraQuals = 0;
450 if (BaseObject) {
451 // BaseObject is an anonymous struct/union variable (and is,
452 // therefore, not part of another non-anonymous record).
453 delete BaseObjectExpr;
454
Steve Naroff774e4152009-01-21 00:14:39 +0000455 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000456 SourceLocation());
457 ExtraQuals
458 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
459 } else if (BaseObjectExpr) {
460 // The caller provided the base object expression. Determine
461 // whether its a pointer and whether it adds any qualifiers to the
462 // anonymous struct/union fields we're looking into.
463 QualType ObjectType = BaseObjectExpr->getType();
464 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
465 BaseObjectIsPointer = true;
466 ObjectType = ObjectPtr->getPointeeType();
467 }
468 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
469 } else {
470 // We've found a member of an anonymous struct/union that is
471 // inside a non-anonymous struct/union, so in a well-formed
472 // program our base object expression is "this".
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
474 if (!MD->isStatic()) {
475 QualType AnonFieldType
476 = Context.getTagDeclType(
477 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
478 QualType ThisType = Context.getTagDeclType(MD->getParent());
479 if ((Context.getCanonicalType(AnonFieldType)
480 == Context.getCanonicalType(ThisType)) ||
481 IsDerivedFrom(ThisType, AnonFieldType)) {
482 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000483 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000484 MD->getThisType(Context));
485 BaseObjectIsPointer = true;
486 }
487 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000488 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
489 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000490 }
491 ExtraQuals = MD->getTypeQualifiers();
492 }
493
494 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000495 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
496 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000497 }
498
499 // Build the implicit member references to the field of the
500 // anonymous struct/union.
501 Expr *Result = BaseObjectExpr;
502 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
503 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
504 FI != FIEnd; ++FI) {
505 QualType MemberType = (*FI)->getType();
506 if (!(*FI)->isMutable()) {
507 unsigned combinedQualifiers
508 = MemberType.getCVRQualifiers() | ExtraQuals;
509 MemberType = MemberType.getQualifiedType(combinedQualifiers);
510 }
Steve Naroff774e4152009-01-21 00:14:39 +0000511 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
512 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000513 BaseObjectIsPointer = false;
514 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
515 OpLoc = SourceLocation();
516 }
517
Sebastian Redlcd883f72009-01-18 18:53:16 +0000518 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000519}
520
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000521/// ActOnDeclarationNameExpr - The parser has read some kind of name
522/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
523/// performs lookup on that name and returns an expression that refers
524/// to that name. This routine isn't directly called from the parser,
525/// because the parser doesn't know about DeclarationName. Rather,
526/// this routine is called by ActOnIdentifierExpr,
527/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
528/// which form the DeclarationName from the corresponding syntactic
529/// forms.
530///
531/// HasTrailingLParen indicates whether this identifier is used in a
532/// function call context. LookupCtx is only used for a C++
533/// qualified-id (foo::bar) to indicate the class or namespace that
534/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000535///
536/// If ForceResolution is true, then we will attempt to resolve the
537/// name even if it looks like a dependent name. This option is off by
538/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000539Sema::OwningExprResult
540Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
541 DeclarationName Name, bool HasTrailingLParen,
542 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000543 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
544 HasTrailingLParen && !SS && !ForceResolution) {
545 // We've seen something of the form
546 // identifier(
547 // and we are in a template, so it is likely that 's' is a
548 // dependent name. However, we won't know until we've parsed all
549 // of the call arguments. So, build a CXXDependentNameExpr node
550 // to represent this name. Then, if it turns out that none of the
551 // arguments are type-dependent, we'll force the resolution of the
552 // dependent name at that point.
Steve Naroff774e4152009-01-21 00:14:39 +0000553 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
554 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000555 }
556
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000557 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000558 Decl *D = 0;
559 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000560 if (SS && !SS->isEmpty()) {
561 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
562 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000563 return ExprError();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000564 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000565 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000566 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
567
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
627 // We may have found a field within an anonymous union or struct
628 // (C++ [class.union]).
629 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
631 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000632
Douglas Gregor3257fb52008-12-22 05:46:06 +0000633 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
634 if (!MD->isStatic()) {
635 // C++ [class.mfct.nonstatic]p2:
636 // [...] if name lookup (3.4.1) resolves the name in the
637 // id-expression to a nonstatic nontype member of class X or of
638 // a base class of X, the id-expression is transformed into a
639 // class member access expression (5.2.5) using (*this) (9.3.2)
640 // as the postfix-expression to the left of the '.' operator.
641 DeclContext *Ctx = 0;
642 QualType MemberType;
643 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
644 Ctx = FD->getDeclContext();
645 MemberType = FD->getType();
646
647 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
648 MemberType = RefType->getPointeeType();
649 else if (!FD->isMutable()) {
650 unsigned combinedQualifiers
651 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
652 MemberType = MemberType.getQualifiedType(combinedQualifiers);
653 }
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 if (!Method->isStatic()) {
656 Ctx = Method->getParent();
657 MemberType = Method->getType();
658 }
659 } else if (OverloadedFunctionDecl *Ovl
660 = dyn_cast<OverloadedFunctionDecl>(D)) {
661 for (OverloadedFunctionDecl::function_iterator
662 Func = Ovl->function_begin(),
663 FuncEnd = Ovl->function_end();
664 Func != FuncEnd; ++Func) {
665 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
666 if (!DMethod->isStatic()) {
667 Ctx = Ovl->getDeclContext();
668 MemberType = Context.OverloadTy;
669 break;
670 }
671 }
672 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000673
674 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000675 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
676 QualType ThisType = Context.getTagDeclType(MD->getParent());
677 if ((Context.getCanonicalType(CtxType)
678 == Context.getCanonicalType(ThisType)) ||
679 IsDerivedFrom(ThisType, CtxType)) {
680 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000681 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000682 MD->getThisType(Context));
Steve Naroff774e4152009-01-21 00:14:39 +0000683 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000684 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000685 }
686 }
687 }
688 }
689
Douglas Gregor8acb7272008-12-11 16:49:14 +0000690 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
692 if (MD->isStatic())
693 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000694 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
695 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000696 }
697
Douglas Gregor3257fb52008-12-22 05:46:06 +0000698 // Any other ways we could have found the field in a well-formed
699 // program would have been turned into implicit member expressions
700 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000701 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
702 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000703 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000704
Chris Lattner4b009652007-07-25 00:24:17 +0000705 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000708 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000709 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000711
Steve Naroffd6163f32008-09-05 22:11:13 +0000712 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000713 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000714 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
715 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000716
Steve Naroffd6163f32008-09-05 22:11:13 +0000717 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718
Steve Naroffd6163f32008-09-05 22:11:13 +0000719 // check if referencing an identifier with __attribute__((deprecated)).
720 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000721 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
722
Douglas Gregor48840c72008-12-10 23:01:14 +0000723 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
724 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
725 Scope *CheckS = S;
726 while (CheckS) {
727 if (CheckS->isWithinElse() &&
728 CheckS->getControlParent()->isDeclScope(Var)) {
729 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000730 ExprError(Diag(Loc, diag::warn_value_always_false)
731 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000732 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_zero)
734 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000735 break;
736 }
737
738 // Move up one more control parent to check again.
739 CheckS = CheckS->getControlParent();
740 if (CheckS)
741 CheckS = CheckS->getParent();
742 }
743 }
744 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000745
746 // Only create DeclRefExpr's for valid Decl's.
747 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return ExprError();
749
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000750 // If the identifier reference is inside a block, and it refers to a value
751 // that is outside the block, create a BlockDeclRefExpr instead of a
752 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
753 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000754 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000755 // We do not do this for things like enum constants, global variables, etc,
756 // as they do not get snapshotted.
757 //
758 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000759 // The BlocksAttr indicates the variable is bound by-reference.
760 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000761 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000762 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000763
Steve Naroff52059382008-10-10 01:28:17 +0000764 // Variable will be bound by-copy, make it const within the closure.
765 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000766 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000767 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000768 }
769 // If this reference is not in a block or if the referenced variable is
770 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000771
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000772 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000773 bool ValueDependent = false;
774 if (getLangOptions().CPlusPlus) {
775 // C++ [temp.dep.expr]p3:
776 // An id-expression is type-dependent if it contains:
777 // - an identifier that was declared with a dependent type,
778 if (VD->getType()->isDependentType())
779 TypeDependent = true;
780 // - FIXME: a template-id that is dependent,
781 // - a conversion-function-id that specifies a dependent type,
782 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
783 Name.getCXXNameType()->isDependentType())
784 TypeDependent = true;
785 // - a nested-name-specifier that contains a class-name that
786 // names a dependent type.
787 else if (SS && !SS->isEmpty()) {
788 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
789 DC; DC = DC->getParent()) {
790 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000791 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000792 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
793 if (Context.getTypeDeclType(Record)->isDependentType()) {
794 TypeDependent = true;
795 break;
796 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000797 }
798 }
799 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000800
Douglas Gregora5d84612008-12-10 20:57:37 +0000801 // C++ [temp.dep.constexpr]p2:
802 //
803 // An identifier is value-dependent if it is:
804 // - a name declared with a dependent type,
805 if (TypeDependent)
806 ValueDependent = true;
807 // - the name of a non-type template parameter,
808 else if (isa<NonTypeTemplateParmDecl>(VD))
809 ValueDependent = true;
810 // - a constant with integral or enumeration type and is
811 // initialized with an expression that is value-dependent
812 // (FIXME!).
813 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000814
Sebastian Redlcd883f72009-01-18 18:53:16 +0000815 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
816 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000817}
818
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
820 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000821 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000822
Chris Lattner4b009652007-07-25 00:24:17 +0000823 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000824 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000825 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
826 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
827 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000828 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000829
Chris Lattner7e637512008-01-12 08:14:25 +0000830 // Pre-defined identifiers are of type char[x], where x is the length of the
831 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000832 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000833 if (FunctionDecl *FD = getCurFunctionDecl())
834 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000835 else if (ObjCMethodDecl *MD = getCurMethodDecl())
836 Length = MD->getSynthesizedMethodSize();
837 else {
838 Diag(Loc, diag::ext_predef_outside_function);
839 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
840 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
841 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000842
843
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000844 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000845 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000846 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000847 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000848}
849
Sebastian Redlcd883f72009-01-18 18:53:16 +0000850Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000851 llvm::SmallString<16> CharBuffer;
852 CharBuffer.resize(Tok.getLength());
853 const char *ThisTokBegin = &CharBuffer[0];
854 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000855
Chris Lattner4b009652007-07-25 00:24:17 +0000856 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
857 Tok.getLocation(), PP);
858 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000859 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000860
861 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
862
Sebastian Redl75324932009-01-20 22:23:13 +0000863 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
864 Literal.isWide(),
865 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
Sebastian Redlcd883f72009-01-18 18:53:16 +0000868Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
869 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000870 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
871 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000872 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
873 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000874 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000875 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000876 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000877
Chris Lattner4b009652007-07-25 00:24:17 +0000878 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000879 // Add padding so that NumericLiteralParser can overread by one character.
880 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000881 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000882
Chris Lattner4b009652007-07-25 00:24:17 +0000883 // Get the spelling of the token, which eliminates trigraphs, etc.
884 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000885
Chris Lattner4b009652007-07-25 00:24:17 +0000886 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
887 Tok.getLocation(), PP);
888 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000889 return ExprError();
890
Chris Lattner1de66eb2007-08-26 03:42:43 +0000891 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892
Chris Lattner1de66eb2007-08-26 03:42:43 +0000893 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000894 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000895 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000896 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000897 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000898 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000899 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000900 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000901
902 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
903
Ted Kremenekddedbe22007-11-29 00:56:49 +0000904 // isExact will be set by GetFloatValue().
905 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000906 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
907 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000908
Chris Lattner1de66eb2007-08-26 03:42:43 +0000909 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000910 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000911 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000912 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000913
Neil Booth7421e9c2007-08-29 22:00:19 +0000914 // long long is a C99 feature.
915 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000916 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000917 Diag(Tok.getLocation(), diag::ext_longlong);
918
Chris Lattner4b009652007-07-25 00:24:17 +0000919 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000920 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000921
Chris Lattner4b009652007-07-25 00:24:17 +0000922 if (Literal.GetIntegerValue(ResultVal)) {
923 // If this value didn't fit into uintmax_t, warn and force to ull.
924 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000925 Ty = Context.UnsignedLongLongTy;
926 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000927 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000928 } else {
929 // If this value fits into a ULL, try to figure out what else it fits into
930 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931
Chris Lattner4b009652007-07-25 00:24:17 +0000932 // Octal, Hexadecimal, and integers with a U suffix are allowed to
933 // be an unsigned int.
934 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
935
936 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000937 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000938 if (!Literal.isLong && !Literal.isLongLong) {
939 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000940 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000941
Chris Lattner4b009652007-07-25 00:24:17 +0000942 // Does it fit in a unsigned int?
943 if (ResultVal.isIntN(IntSize)) {
944 // Does it fit in a signed int?
945 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000946 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000947 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000948 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000949 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000950 }
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000952
Chris Lattner4b009652007-07-25 00:24:17 +0000953 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000954 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000955 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000956
Chris Lattner4b009652007-07-25 00:24:17 +0000957 // Does it fit in a unsigned long?
958 if (ResultVal.isIntN(LongSize)) {
959 // Does it fit in a signed long?
960 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000961 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000962 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000963 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000964 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966 }
967
Chris Lattner4b009652007-07-25 00:24:17 +0000968 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000969 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000970 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971
Chris Lattner4b009652007-07-25 00:24:17 +0000972 // Does it fit in a unsigned long long?
973 if (ResultVal.isIntN(LongLongSize)) {
974 // Does it fit in a signed long long?
975 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000976 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000977 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000978 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000979 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000980 }
981 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000982
Chris Lattner4b009652007-07-25 00:24:17 +0000983 // If we still couldn't decide a type, we probably have something that
984 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000985 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000986 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000987 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000988 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattnere4068872008-05-09 05:59:00 +0000991 if (ResultVal.getBitWidth() != Width)
992 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000993 }
Sebastian Redl75324932009-01-20 22:23:13 +0000994 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000996
Chris Lattner1de66eb2007-08-26 03:42:43 +0000997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
998 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +0000999 Res = new (Context) ImaginaryLiteral(Res,
1000 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001
1002 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001003}
1004
Sebastian Redlcd883f72009-01-18 18:53:16 +00001005Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1006 SourceLocation R, ExprArg Val) {
1007 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001008 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001009 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001010}
1011
1012/// The UsualUnaryConversions() function is *not* called by this routine.
1013/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001014bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1015 SourceLocation OpLoc,
1016 const SourceRange &ExprRange,
1017 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // C99 6.5.3.4p1:
1019 if (isa<FunctionType>(exprType) && isSizeof)
1020 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001021 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001022 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001023 Diag(OpLoc, diag::ext_sizeof_void_type)
1024 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001025 else
1026 return DiagnoseIncompleteType(OpLoc, exprType,
1027 isSizeof ? diag::err_sizeof_incomplete_type :
1028 diag::err_alignof_incomplete_type,
1029 ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001030
1031 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001032}
1033
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001034/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1035/// the same for @c alignof and @c __alignof
1036/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001037Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001038Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1039 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001041 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001042
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001043 QualType ArgTy;
1044 SourceRange Range;
1045 if (isType) {
1046 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1047 Range = ArgRange;
1048 } else {
1049 // Get the end location.
1050 Expr *ArgEx = (Expr *)TyOrEx;
1051 Range = ArgEx->getSourceRange();
1052 ArgTy = ArgEx->getType();
1053 }
1054
1055 // Verify that the operand is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00001056 // FIXME: This might leak the expression.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001057 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Sebastian Redl8b769972009-01-19 00:08:26 +00001058 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001059
1060 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001061 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Sebastian Redl8b769972009-01-19 00:08:26 +00001062 Context.getSizeType(), OpLoc,
1063 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001064}
1065
Chris Lattner5110ad52007-08-24 21:41:10 +00001066QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001067 DefaultFunctionArrayConversion(V);
1068
Chris Lattnera16e42d2007-08-26 05:39:26 +00001069 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001070 if (const ComplexType *CT = V->getType()->getAsComplexType())
1071 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001072
1073 // Otherwise they pass through real integer and floating point types here.
1074 if (V->getType()->isArithmeticType())
1075 return V->getType();
1076
1077 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001078 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001079 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001080}
1081
1082
Chris Lattner4b009652007-07-25 00:24:17 +00001083
Sebastian Redl8b769972009-01-19 00:08:26 +00001084Action::OwningExprResult
1085Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1086 tok::TokenKind Kind, ExprArg Input) {
1087 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001088
Chris Lattner4b009652007-07-25 00:24:17 +00001089 UnaryOperator::Opcode Opc;
1090 switch (Kind) {
1091 default: assert(0 && "Unknown unary op!");
1092 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1093 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1094 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001095
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001096 if (getLangOptions().CPlusPlus &&
1097 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1098 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001099 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001100 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1101
1102 // C++ [over.inc]p1:
1103 //
1104 // [...] If the function is a member function with one
1105 // parameter (which shall be of type int) or a non-member
1106 // function with two parameters (the second of which shall be
1107 // of type int), it defines the postfix increment operator ++
1108 // for objects of that type. When the postfix increment is
1109 // called as a result of using the ++ operator, the int
1110 // argument will have value zero.
1111 Expr *Args[2] = {
1112 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001113 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1114 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001115 };
1116
1117 // Build the candidate set for overloading
1118 OverloadCandidateSet CandidateSet;
1119 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1120
1121 // Perform overload resolution.
1122 OverloadCandidateSet::iterator Best;
1123 switch (BestViableFunction(CandidateSet, Best)) {
1124 case OR_Success: {
1125 // We found a built-in operator or an overloaded operator.
1126 FunctionDecl *FnDecl = Best->Function;
1127
1128 if (FnDecl) {
1129 // We matched an overloaded operator. Build a call to that
1130 // operator.
1131
1132 // Convert the arguments.
1133 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1134 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001135 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001136 } else {
1137 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001138 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001139 FnDecl->getParamDecl(0)->getType(),
1140 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001141 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001142 }
1143
1144 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001145 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001146 = FnDecl->getType()->getAsFunctionType()->getResultType();
1147 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001148
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001149 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001150 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001151 SourceLocation());
1152 UsualUnaryConversions(FnExpr);
1153
Sebastian Redl8b769972009-01-19 00:08:26 +00001154 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001155 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001156 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001157 } else {
1158 // We matched a built-in operator. Convert the arguments, then
1159 // break out so that we will build the appropriate built-in
1160 // operator node.
1161 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1162 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001163 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001164
1165 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001166 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001167 }
1168
1169 case OR_No_Viable_Function:
1170 // No viable function; fall through to handling this as a
1171 // built-in operator, which will produce an error message for us.
1172 break;
1173
1174 case OR_Ambiguous:
1175 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1176 << UnaryOperator::getOpcodeStr(Opc)
1177 << Arg->getSourceRange();
1178 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001179 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001180 }
1181
1182 // Either we found no viable overloaded operator or we matched a
1183 // built-in operator. In either case, fall through to trying to
1184 // build a built-in operation.
1185 }
1186
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001187 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1188 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001189 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001190 return ExprError();
1191 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001192 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001193}
1194
Sebastian Redl8b769972009-01-19 00:08:26 +00001195Action::OwningExprResult
1196Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1197 ExprArg Idx, SourceLocation RLoc) {
1198 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1199 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001200
Douglas Gregor80723c52008-11-19 17:17:41 +00001201 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001202 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001203 LHSExp->getType()->isEnumeralType() ||
1204 RHSExp->getType()->isRecordType() ||
1205 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001206 // Add the appropriate overloaded operators (C++ [over.match.oper])
1207 // to the candidate set.
1208 OverloadCandidateSet CandidateSet;
1209 Expr *Args[2] = { LHSExp, RHSExp };
1210 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001211
Douglas Gregor80723c52008-11-19 17:17:41 +00001212 // Perform overload resolution.
1213 OverloadCandidateSet::iterator Best;
1214 switch (BestViableFunction(CandidateSet, Best)) {
1215 case OR_Success: {
1216 // We found a built-in operator or an overloaded operator.
1217 FunctionDecl *FnDecl = Best->Function;
1218
1219 if (FnDecl) {
1220 // We matched an overloaded operator. Build a call to that
1221 // operator.
1222
1223 // Convert the arguments.
1224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1225 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1226 PerformCopyInitialization(RHSExp,
1227 FnDecl->getParamDecl(0)->getType(),
1228 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001229 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001230 } else {
1231 // Convert the arguments.
1232 if (PerformCopyInitialization(LHSExp,
1233 FnDecl->getParamDecl(0)->getType(),
1234 "passing") ||
1235 PerformCopyInitialization(RHSExp,
1236 FnDecl->getParamDecl(1)->getType(),
1237 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001238 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001239 }
1240
1241 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001242 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001243 = FnDecl->getType()->getAsFunctionType()->getResultType();
1244 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001245
Douglas Gregor80723c52008-11-19 17:17:41 +00001246 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001247 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001248 SourceLocation());
1249 UsualUnaryConversions(FnExpr);
1250
Sebastian Redl8b769972009-01-19 00:08:26 +00001251 Base.release();
1252 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001253 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1254 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001255 } else {
1256 // We matched a built-in operator. Convert the arguments, then
1257 // break out so that we will build the appropriate built-in
1258 // operator node.
1259 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1260 "passing") ||
1261 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1262 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001263 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001264
1265 break;
1266 }
1267 }
1268
1269 case OR_No_Viable_Function:
1270 // No viable function; fall through to handling this as a
1271 // built-in operator, which will produce an error message for us.
1272 break;
1273
1274 case OR_Ambiguous:
1275 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1276 << "[]"
1277 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1278 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001279 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001280 }
1281
1282 // Either we found no viable overloaded operator or we matched a
1283 // built-in operator. In either case, fall through to trying to
1284 // build a built-in operation.
1285 }
1286
Chris Lattner4b009652007-07-25 00:24:17 +00001287 // Perform default conversions.
1288 DefaultFunctionArrayConversion(LHSExp);
1289 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1292
1293 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001294 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // in the subscript position. As a result, we need to derive the array base
1296 // and index from the expression types.
1297 Expr *BaseExpr, *IndexExpr;
1298 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001299 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001300 BaseExpr = LHSExp;
1301 IndexExpr = RHSExp;
1302 // FIXME: need to deal with const...
1303 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001304 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // Handle the uncommon case of "123[Ptr]".
1306 BaseExpr = RHSExp;
1307 IndexExpr = LHSExp;
1308 // FIXME: need to deal with const...
1309 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001310 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1311 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001312 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001313
Chris Lattner4b009652007-07-25 00:24:17 +00001314 // FIXME: need to deal with const...
1315 ResultType = VTy->getElementType();
1316 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001317 return ExprError(Diag(LHSExp->getLocStart(),
1318 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1319 }
Chris Lattner4b009652007-07-25 00:24:17 +00001320 // C99 6.5.2.1p1
1321 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001322 return ExprError(Diag(IndexExpr->getLocStart(),
1323 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001324
1325 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1326 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001327 // void (*)(int)) and pointers to incomplete types. Functions are not
1328 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001329 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001330 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001331 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001332 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001333
Sebastian Redl8b769972009-01-19 00:08:26 +00001334 Base.release();
1335 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001336 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1337 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001338}
1339
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001340QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001341CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001342 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001343 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001344
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001345 // The vector accessor can't exceed the number of elements.
1346 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001347
1348 // This flag determines whether or not the component is one of the four
1349 // special names that indicate a subset of exactly half the elements are
1350 // to be selected.
1351 bool HalvingSwizzle = false;
1352
1353 // This flag determines whether or not CompName has an 's' char prefix,
1354 // indicating that it is a string of hex values to be used as vector indices.
1355 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001356
1357 // Check that we've found one of the special components, or that the component
1358 // names must come from the same set.
1359 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001360 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1361 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001362 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001363 do
1364 compStr++;
1365 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001366 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001367 do
1368 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001369 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001370 }
Nate Begeman1486b502009-01-18 01:47:54 +00001371
1372 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001373 // We didn't get to the end of the string. This means the component names
1374 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001375 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1376 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001377 return QualType();
1378 }
Nate Begeman1486b502009-01-18 01:47:54 +00001379
1380 // Ensure no component accessor exceeds the width of the vector type it
1381 // operates on.
1382 if (!HalvingSwizzle) {
1383 compStr = CompName.getName();
1384
1385 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001386 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001387
1388 while (*compStr) {
1389 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1390 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1391 << baseType << SourceRange(CompLoc);
1392 return QualType();
1393 }
1394 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001395 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001396
Nate Begeman1486b502009-01-18 01:47:54 +00001397 // If this is a halving swizzle, verify that the base type has an even
1398 // number of elements.
1399 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001400 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001401 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001402 return QualType();
1403 }
1404
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001405 // The component accessor looks fine - now we need to compute the actual type.
1406 // The vector type is implied by the component accessor. For example,
1407 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001408 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001409 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001410 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1411 : CompName.getLength();
1412 if (HexSwizzle)
1413 CompSize--;
1414
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001415 if (CompSize == 1)
1416 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001417
Nate Begemanaf6ed502008-04-18 23:10:10 +00001418 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001419 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001420 // diagostics look bad. We want extended vector types to appear built-in.
1421 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1422 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1423 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001424 }
1425 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001426}
1427
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001428/// constructSetterName - Return the setter name for the given
1429/// identifier, i.e. "set" + Name where the initial character of Name
1430/// has been capitalized.
1431// FIXME: Merge with same routine in Parser. But where should this
1432// live?
1433static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1434 const IdentifierInfo *Name) {
1435 llvm::SmallString<100> SelectorName;
1436 SelectorName = "set";
1437 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1438 SelectorName[3] = toupper(SelectorName[3]);
1439 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1440}
1441
Sebastian Redl8b769972009-01-19 00:08:26 +00001442Action::OwningExprResult
1443Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1444 tok::TokenKind OpKind, SourceLocation MemberLoc,
1445 IdentifierInfo &Member) {
1446 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001447 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001448
1449 // Perform default conversions.
1450 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001451
Steve Naroff2cb66382007-07-26 03:11:44 +00001452 QualType BaseType = BaseExpr->getType();
1453 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001454
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001455 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1456 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001457 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001458 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001459 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001460 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001461 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1462 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001463 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001464 return ExprError(Diag(MemberLoc,
1465 diag::err_typecheck_member_reference_arrow)
1466 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001467 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001468
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001469 // Handle field access to simple records. This also handles access to fields
1470 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001471 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001472 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001473 if (DiagnoseIncompleteType(OpLoc, BaseType,
1474 diag::err_typecheck_incomplete_tag,
1475 BaseExpr->getSourceRange()))
1476 return ExprError();
1477
Steve Naroff2cb66382007-07-26 03:11:44 +00001478 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001479 // FIXME: Qualified name lookup for C++ is a bit more complicated
1480 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001481 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001482 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1483 LookupCriteria(LookupCriteria::Member,
1484 /*RedeclarationOnly=*/false,
1485 getLangOptions().CPlusPlus));
1486
1487 Decl *MemberDecl = 0;
1488 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001489 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1490 << &Member << BaseExpr->getSourceRange());
1491 else if (Result.isAmbiguous()) {
1492 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1493 MemberLoc, BaseExpr->getSourceRange());
1494 return ExprError();
1495 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001496 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001497
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001498 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001499 // We may have found a field within an anonymous union or struct
1500 // (C++ [class.union]).
1501 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001502 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001503 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001504
Douglas Gregor82d44772008-12-20 23:49:58 +00001505 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1506 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001507 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001508 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1509 MemberType = Ref->getPointeeType();
1510 else {
1511 unsigned combinedQualifiers =
1512 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001513 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001514 combinedQualifiers &= ~QualType::Const;
1515 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1516 }
Eli Friedman76b49832008-02-06 22:48:16 +00001517
Steve Naroff774e4152009-01-21 00:14:39 +00001518 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1519 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001520 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001521 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001522 Var, MemberLoc,
1523 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001524 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001525 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1526 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001527 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001528 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001529 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001530 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001531 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001532 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001533 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001534 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001535 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1536 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001537
Douglas Gregor82d44772008-12-20 23:49:58 +00001538 // We found a declaration kind that we didn't expect. This is a
1539 // generic error message that tells the user that she can't refer
1540 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001541 return ExprError(Diag(MemberLoc,
1542 diag::err_typecheck_member_reference_unknown)
1543 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001544 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001545
Chris Lattnere9d71612008-07-21 04:59:05 +00001546 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1547 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001548 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001549 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001550 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1551 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001552 OpKind == tok::arrow);
1553 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001554 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001555 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1557 << IFTy->getDecl()->getDeclName() << &Member
1558 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001559 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001560
Chris Lattnere9d71612008-07-21 04:59:05 +00001561 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1562 // pointer to a (potentially qualified) interface type.
1563 const PointerType *PTy;
1564 const ObjCInterfaceType *IFTy;
1565 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1566 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1567 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001568
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001569 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001570 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001571 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001572 MemberLoc, BaseExpr));
1573
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001574 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001575 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1576 E = IFTy->qual_end(); I != E; ++I)
1577 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001578 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001580
1581 // If that failed, look for an "implicit" property by seeing if the nullary
1582 // selector is implemented.
1583
1584 // FIXME: The logic for looking up nullary and unary selectors should be
1585 // shared with the code in ActOnInstanceMessage.
1586
1587 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1588 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001589
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001590 // If this reference is in an @implementation, check for 'private' methods.
1591 if (!Getter)
1592 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1593 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1594 if (ObjCImplementationDecl *ImpDecl =
1595 ObjCImplementations[ClassDecl->getIdentifier()])
1596 Getter = ImpDecl->getInstanceMethod(Sel);
1597
Steve Naroff04151f32008-10-22 19:16:27 +00001598 // Look through local category implementations associated with the class.
1599 if (!Getter) {
1600 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1601 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1602 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1603 }
1604 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001605 if (Getter) {
1606 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001607 // will look for the matching setter, in case it is needed.
1608 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1609 &Member);
1610 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1611 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1612 if (!Setter) {
1613 // If this reference is in an @implementation, also check for 'private'
1614 // methods.
1615 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1616 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1617 if (ObjCImplementationDecl *ImpDecl =
1618 ObjCImplementations[ClassDecl->getIdentifier()])
1619 Setter = ImpDecl->getInstanceMethod(SetterSel);
1620 }
1621 // Look through local category implementations associated with the class.
1622 if (!Setter) {
1623 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1624 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1625 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1626 }
1627 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001628
1629 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001630 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1631 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001632 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001633
1634 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1635 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001636 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001637 // Handle properties on qualified "id" protocols.
1638 const ObjCQualifiedIdType *QIdTy;
1639 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1640 // Check protocols on qualified interfaces.
1641 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001642 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001643 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001644 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001645 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001646 // Also must look for a getter name which uses property syntax.
1647 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1648 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001649 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1650 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001651 }
1652 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001653
1654 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1655 << &Member << BaseType);
1656 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001657 // Handle 'field access' to vectors, such as 'V.xx'.
1658 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001659 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1660 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001661 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001662 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1663 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001664 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001665
1666 return ExprError(Diag(MemberLoc,
1667 diag::err_typecheck_member_reference_struct_union)
1668 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001669}
1670
Douglas Gregor3257fb52008-12-22 05:46:06 +00001671/// ConvertArgumentsForCall - Converts the arguments specified in
1672/// Args/NumArgs to the parameter types of the function FDecl with
1673/// function prototype Proto. Call is the call expression itself, and
1674/// Fn is the function expression. For a C++ member function, this
1675/// routine does not attempt to convert the object argument. Returns
1676/// true if the call is ill-formed.
1677bool
1678Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1679 FunctionDecl *FDecl,
1680 const FunctionTypeProto *Proto,
1681 Expr **Args, unsigned NumArgs,
1682 SourceLocation RParenLoc) {
1683 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1684 // assignment, to the types of the corresponding parameter, ...
1685 unsigned NumArgsInProto = Proto->getNumArgs();
1686 unsigned NumArgsToCheck = NumArgs;
1687
1688 // If too few arguments are available (and we don't have default
1689 // arguments for the remaining parameters), don't make the call.
1690 if (NumArgs < NumArgsInProto) {
1691 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1692 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1693 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1694 // Use default arguments for missing arguments
1695 NumArgsToCheck = NumArgsInProto;
1696 Call->setNumArgs(NumArgsInProto);
1697 }
1698
1699 // If too many are passed and not variadic, error on the extras and drop
1700 // them.
1701 if (NumArgs > NumArgsInProto) {
1702 if (!Proto->isVariadic()) {
1703 Diag(Args[NumArgsInProto]->getLocStart(),
1704 diag::err_typecheck_call_too_many_args)
1705 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1706 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1707 Args[NumArgs-1]->getLocEnd());
1708 // This deletes the extra arguments.
1709 Call->setNumArgs(NumArgsInProto);
1710 }
1711 NumArgsToCheck = NumArgsInProto;
1712 }
1713
1714 // Continue to check argument types (even if we have too few/many args).
1715 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1716 QualType ProtoArgType = Proto->getArgType(i);
1717
1718 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001719 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001720 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001721
1722 // Pass the argument.
1723 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1724 return true;
1725 } else
1726 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001727 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001728 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001729
Douglas Gregor3257fb52008-12-22 05:46:06 +00001730 Call->setArg(i, Arg);
1731 }
1732
1733 // If this is a variadic call, handle args passed through "...".
1734 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001735 VariadicCallType CallType = VariadicFunction;
1736 if (Fn->getType()->isBlockPointerType())
1737 CallType = VariadicBlock; // Block
1738 else if (isa<MemberExpr>(Fn))
1739 CallType = VariadicMethod;
1740
Douglas Gregor3257fb52008-12-22 05:46:06 +00001741 // Promote the arguments (C99 6.5.2.2p7).
1742 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1743 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001744 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001745 Call->setArg(i, Arg);
1746 }
1747 }
1748
1749 return false;
1750}
1751
Steve Naroff87d58b42007-09-16 03:34:24 +00001752/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001753/// This provides the location of the left/right parens and a list of comma
1754/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001755Action::OwningExprResult
1756Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1757 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001758 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001759 unsigned NumArgs = args.size();
1760 Expr *Fn = static_cast<Expr *>(fn.release());
1761 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001762 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001763 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001764 OverloadedFunctionDecl *Ovl = NULL;
1765
Douglas Gregora133e262008-12-06 00:22:45 +00001766 // Determine whether this is a dependent call inside a C++ template,
1767 // in which case we won't do any semantic analysis now.
1768 bool Dependent = false;
1769 if (Fn->isTypeDependent()) {
1770 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1771 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1772 Dependent = true;
1773 else {
1774 // Resolve the CXXDependentNameExpr to an actual identifier;
1775 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001776 OwningExprResult Resolved
1777 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1778 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001779 /*HasTrailingLParen=*/true,
1780 /*SS=*/0,
1781 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001782 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001784 else {
1785 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001786 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001787 }
1788 }
1789 } else
1790 Dependent = true;
1791 } else
1792 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1793
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001794 // FIXME: Will need to cache the results of name lookup (including
1795 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001796 if (Dependent)
Steve Naroff774e4152009-01-21 00:14:39 +00001797 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1798 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001799
Douglas Gregor3257fb52008-12-22 05:46:06 +00001800 // Determine whether this is a call to an object (C++ [over.call.object]).
1801 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001802 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1803 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001804
1805 // Determine whether this is a call to a member function.
1806 if (getLangOptions().CPlusPlus) {
1807 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1808 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1809 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001810 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1811 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001812 }
1813
Douglas Gregord2baafd2008-10-21 16:13:35 +00001814 // If we're directly calling a function or a set of overloaded
1815 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001816 DeclRefExpr *DRExpr = NULL;
1817 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1818 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1819 else
1820 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001821
Douglas Gregor566782a2009-01-06 05:10:23 +00001822 if (DRExpr) {
1823 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1824 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001825 }
1826
Douglas Gregord2baafd2008-10-21 16:13:35 +00001827 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001828 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1829 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001830 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001831 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001832
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001833 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001834 Expr *NewFn = 0;
1835 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff774e4152009-01-21 00:14:39 +00001836 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor566782a2009-01-06 05:10:23 +00001837 QDRExpr->getLocation(), false, false,
1838 QDRExpr->getSourceRange().getBegin());
1839 else
Steve Naroff774e4152009-01-21 00:14:39 +00001840 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1841 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001842 Fn->Destroy(Context);
1843 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001844 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001845
1846 // Promote the function operand.
1847 UsualUnaryConversions(Fn);
1848
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001849 // Make the call expr early, before semantic checks. This guarantees cleanup
1850 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001851 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1852 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001853 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001854 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001855
Steve Naroffd6163f32008-09-05 22:11:13 +00001856 const FunctionType *FuncT;
1857 if (!Fn->getType()->isBlockPointerType()) {
1858 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1859 // have type pointer to function".
1860 const PointerType *PT = Fn->getType()->getAsPointerType();
1861 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001862 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1863 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001864 FuncT = PT->getPointeeType()->getAsFunctionType();
1865 } else { // This is a block call.
1866 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1867 getAsFunctionType();
1868 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001869 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001870 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1871 << Fn->getType() << Fn->getSourceRange());
1872
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001873 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001874 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001875
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001876 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001877 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1878 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001879 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001880 } else {
1881 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001882
Steve Naroffdb65e052007-08-28 23:30:39 +00001883 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001884 for (unsigned i = 0; i != NumArgs; i++) {
1885 Expr *Arg = Args[i];
1886 DefaultArgumentPromotion(Arg);
1887 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001888 }
Chris Lattner4b009652007-07-25 00:24:17 +00001889 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001890
Douglas Gregor3257fb52008-12-22 05:46:06 +00001891 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1892 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001893 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1894 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001895
Chris Lattner2e64c072007-08-10 20:18:51 +00001896 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001897 if (FDecl)
1898 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001899
Sebastian Redl8b769972009-01-19 00:08:26 +00001900 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001901}
1902
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001903Action::OwningExprResult
1904Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1905 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001906 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001907 QualType literalType = QualType::getFromOpaquePtr(Ty);
1908 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001909 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001910 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001911
Eli Friedman8c2173d2008-05-20 05:22:08 +00001912 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001913 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001914 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1915 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001916 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1917 diag::err_typecheck_decl_incomplete_type,
1918 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001919 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001920
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001921 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001922 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001923 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001924
Chris Lattnere5cb5862008-12-04 23:50:19 +00001925 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001926 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001927 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001928 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001929 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001930 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001931 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1932 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001933}
1934
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001935Action::OwningExprResult
1936Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1937 InitListDesignations &Designators,
1938 SourceLocation RBraceLoc) {
1939 unsigned NumInit = initlist.size();
1940 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001941
Steve Naroff0acc9c92007-09-15 18:49:24 +00001942 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001943 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001944
Steve Naroff774e4152009-01-21 00:14:39 +00001945 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
1946 RBraceLoc, Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001947 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001948 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001949}
1950
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001951/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001952bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001953 UsualUnaryConversions(castExpr);
1954
1955 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1956 // type needs to be scalar.
1957 if (castType->isVoidType()) {
1958 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001959 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1960 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001961 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001962 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1963 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1964 (castType->isStructureType() || castType->isUnionType())) {
1965 // GCC struct/union extension: allow cast to self.
1966 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1967 << castType << castExpr->getSourceRange();
1968 } else if (castType->isUnionType()) {
1969 // GCC cast to union extension
1970 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1971 RecordDecl::field_iterator Field, FieldEnd;
1972 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1973 Field != FieldEnd; ++Field) {
1974 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1975 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1976 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1977 << castExpr->getSourceRange();
1978 break;
1979 }
1980 }
1981 if (Field == FieldEnd)
1982 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1983 << castExpr->getType() << castExpr->getSourceRange();
1984 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001985 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001986 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001987 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001988 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001989 } else if (!castExpr->getType()->isScalarType() &&
1990 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001991 return Diag(castExpr->getLocStart(),
1992 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001993 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001994 } else if (castExpr->getType()->isVectorType()) {
1995 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1996 return true;
1997 } else if (castType->isVectorType()) {
1998 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1999 return true;
2000 }
2001 return false;
2002}
2003
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002004bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002005 assert(VectorTy->isVectorType() && "Not a vector type!");
2006
2007 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002008 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002009 return Diag(R.getBegin(),
2010 Ty->isVectorType() ?
2011 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002012 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002013 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002014 } else
2015 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002016 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002017 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002018
2019 return false;
2020}
2021
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002022Action::OwningExprResult
2023Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2024 SourceLocation RParenLoc, ExprArg Op) {
2025 assert((Ty != 0) && (Op.get() != 0) &&
2026 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002027
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002028 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002029 QualType castType = QualType::getFromOpaquePtr(Ty);
2030
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002031 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002032 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002033 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002034 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002035}
2036
Chris Lattner98a425c2007-11-26 01:40:58 +00002037/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2038/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002039inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2040 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2041 UsualUnaryConversions(cond);
2042 UsualUnaryConversions(lex);
2043 UsualUnaryConversions(rex);
2044 QualType condT = cond->getType();
2045 QualType lexT = lex->getType();
2046 QualType rexT = rex->getType();
2047
2048 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002049 if (!cond->isTypeDependent()) {
2050 if (!condT->isScalarType()) { // C99 6.5.15p2
2051 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2052 return QualType();
2053 }
Chris Lattner4b009652007-07-25 00:24:17 +00002054 }
Chris Lattner992ae932008-01-06 22:42:25 +00002055
2056 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002057 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2058 return Context.DependentTy;
2059
Chris Lattner992ae932008-01-06 22:42:25 +00002060 // If both operands have arithmetic type, do the usual arithmetic conversions
2061 // to find a common type: C99 6.5.15p3,5.
2062 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002063 UsualArithmeticConversions(lex, rex);
2064 return lex->getType();
2065 }
Chris Lattner992ae932008-01-06 22:42:25 +00002066
2067 // If both operands are the same structure or union type, the result is that
2068 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002069 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002070 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002071 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002072 // "If both the operands have structure or union type, the result has
2073 // that type." This implies that CV qualifiers are dropped.
2074 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002075 }
Chris Lattner992ae932008-01-06 22:42:25 +00002076
2077 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002078 // The following || allows only one side to be void (a GCC-ism).
2079 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002080 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002081 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2082 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002083 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002084 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2085 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002086 ImpCastExprToType(lex, Context.VoidTy);
2087 ImpCastExprToType(rex, Context.VoidTy);
2088 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002089 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002090 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2091 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002092 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2093 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002094 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002095 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002096 return lexT;
2097 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002098 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2099 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002100 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002101 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002102 return rexT;
2103 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002104 // Handle the case where both operands are pointers before we handle null
2105 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002106 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2107 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2108 // get the "pointed to" types
2109 QualType lhptee = LHSPT->getPointeeType();
2110 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002111
Chris Lattner71225142007-07-31 21:27:01 +00002112 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2113 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002114 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002115 // Figure out necessary qualifiers (C99 6.5.15p6)
2116 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002117 QualType destType = Context.getPointerType(destPointee);
2118 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2119 ImpCastExprToType(rex, destType); // promote to void*
2120 return destType;
2121 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002122 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002123 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002124 QualType destType = Context.getPointerType(destPointee);
2125 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2126 ImpCastExprToType(rex, destType); // promote to void*
2127 return destType;
2128 }
Chris Lattner4b009652007-07-25 00:24:17 +00002129
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002130 QualType compositeType = lexT;
2131
2132 // If either type is an Objective-C object type then check
2133 // compatibility according to Objective-C.
2134 if (Context.isObjCObjectPointerType(lexT) ||
2135 Context.isObjCObjectPointerType(rexT)) {
2136 // If both operands are interfaces and either operand can be
2137 // assigned to the other, use that type as the composite
2138 // type. This allows
2139 // xxx ? (A*) a : (B*) b
2140 // where B is a subclass of A.
2141 //
2142 // Additionally, as for assignment, if either type is 'id'
2143 // allow silent coercion. Finally, if the types are
2144 // incompatible then make sure to use 'id' as the composite
2145 // type so the result is acceptable for sending messages to.
2146
2147 // FIXME: This code should not be localized to here. Also this
2148 // should use a compatible check instead of abusing the
2149 // canAssignObjCInterfaces code.
2150 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2151 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2152 if (LHSIface && RHSIface &&
2153 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2154 compositeType = lexT;
2155 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002156 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002157 compositeType = rexT;
2158 } else if (Context.isObjCIdType(lhptee) ||
2159 Context.isObjCIdType(rhptee)) {
2160 // FIXME: This code looks wrong, because isObjCIdType checks
2161 // the struct but getObjCIdType returns the pointer to
2162 // struct. This is horrible and should be fixed.
2163 compositeType = Context.getObjCIdType();
2164 } else {
2165 QualType incompatTy = Context.getObjCIdType();
2166 ImpCastExprToType(lex, incompatTy);
2167 ImpCastExprToType(rex, incompatTy);
2168 return incompatTy;
2169 }
2170 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2171 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002172 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002173 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002174 // In this situation, we assume void* type. No especially good
2175 // reason, but this is what gcc does, and we do have to pick
2176 // to get a consistent AST.
2177 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002178 ImpCastExprToType(lex, incompatTy);
2179 ImpCastExprToType(rex, incompatTy);
2180 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002181 }
2182 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002183 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2184 // differently qualified versions of compatible types, the result type is
2185 // a pointer to an appropriately qualified version of the *composite*
2186 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002187 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002188 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002189 ImpCastExprToType(lex, compositeType);
2190 ImpCastExprToType(rex, compositeType);
2191 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002192 }
Chris Lattner4b009652007-07-25 00:24:17 +00002193 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002194 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2195 // evaluates to "struct objc_object *" (and is handled above when comparing
2196 // id with statically typed objects).
2197 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2198 // GCC allows qualified id and any Objective-C type to devolve to
2199 // id. Currently localizing to here until clear this should be
2200 // part of ObjCQualifiedIdTypesAreCompatible.
2201 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2202 (lexT->isObjCQualifiedIdType() &&
2203 Context.isObjCObjectPointerType(rexT)) ||
2204 (rexT->isObjCQualifiedIdType() &&
2205 Context.isObjCObjectPointerType(lexT))) {
2206 // FIXME: This is not the correct composite type. This only
2207 // happens to work because id can more or less be used anywhere,
2208 // however this may change the type of method sends.
2209 // FIXME: gcc adds some type-checking of the arguments and emits
2210 // (confusing) incompatible comparison warnings in some
2211 // cases. Investigate.
2212 QualType compositeType = Context.getObjCIdType();
2213 ImpCastExprToType(lex, compositeType);
2214 ImpCastExprToType(rex, compositeType);
2215 return compositeType;
2216 }
2217 }
2218
Steve Naroff3eac7692008-09-10 19:17:48 +00002219 // Selection between block pointer types is ok as long as they are the same.
2220 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2221 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2222 return lexT;
2223
Chris Lattner992ae932008-01-06 22:42:25 +00002224 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002225 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002226 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002227 return QualType();
2228}
2229
Steve Naroff87d58b42007-09-16 03:34:24 +00002230/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002231/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002232Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2233 SourceLocation ColonLoc,
2234 ExprArg Cond, ExprArg LHS,
2235 ExprArg RHS) {
2236 Expr *CondExpr = (Expr *) Cond.get();
2237 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002238
2239 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2240 // was the condition.
2241 bool isLHSNull = LHSExpr == 0;
2242 if (isLHSNull)
2243 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002244
2245 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002246 RHSExpr, QuestionLoc);
2247 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002248 return ExprError();
2249
2250 Cond.release();
2251 LHS.release();
2252 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002253 return Owned(new (Context) ConditionalOperator(CondExpr,
2254 isLHSNull ? 0 : LHSExpr,
2255 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002256}
2257
Chris Lattner4b009652007-07-25 00:24:17 +00002258
2259// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2260// being closely modeled after the C99 spec:-). The odd characteristic of this
2261// routine is it effectively iqnores the qualifiers on the top level pointee.
2262// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2263// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002264Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002265Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2266 QualType lhptee, rhptee;
2267
2268 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002269 lhptee = lhsType->getAsPointerType()->getPointeeType();
2270 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002271
2272 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002273 lhptee = Context.getCanonicalType(lhptee);
2274 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002275
Chris Lattner005ed752008-01-04 18:04:52 +00002276 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002277
2278 // C99 6.5.16.1p1: This following citation is common to constraints
2279 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2280 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002281 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002282 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002283 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002284
2285 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2286 // incomplete type and the other is a pointer to a qualified or unqualified
2287 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002288 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002289 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002290 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002291
2292 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002293 assert(rhptee->isFunctionType());
2294 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002295 }
2296
2297 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002298 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002299 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002300
2301 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002302 assert(lhptee->isFunctionType());
2303 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002304 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002305
2306 // Check for ObjC interfaces
2307 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2308 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2309 if (LHSIface && RHSIface &&
2310 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2311 return ConvTy;
2312
2313 // ID acts sort of like void* for ObjC interfaces
2314 if (LHSIface && Context.isObjCIdType(rhptee))
2315 return ConvTy;
2316 if (RHSIface && Context.isObjCIdType(lhptee))
2317 return ConvTy;
2318
Chris Lattner4b009652007-07-25 00:24:17 +00002319 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2320 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002321 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2322 rhptee.getUnqualifiedType()))
2323 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002324 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002325}
2326
Steve Naroff3454b6c2008-09-04 15:10:53 +00002327/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2328/// block pointer types are compatible or whether a block and normal pointer
2329/// are compatible. It is more restrict than comparing two function pointer
2330// types.
2331Sema::AssignConvertType
2332Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2333 QualType rhsType) {
2334 QualType lhptee, rhptee;
2335
2336 // get the "pointed to" type (ignoring qualifiers at the top level)
2337 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2338 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2339
2340 // make sure we operate on the canonical type
2341 lhptee = Context.getCanonicalType(lhptee);
2342 rhptee = Context.getCanonicalType(rhptee);
2343
2344 AssignConvertType ConvTy = Compatible;
2345
2346 // For blocks we enforce that qualifiers are identical.
2347 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2348 ConvTy = CompatiblePointerDiscardsQualifiers;
2349
2350 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2351 return IncompatibleBlockPointer;
2352 return ConvTy;
2353}
2354
Chris Lattner4b009652007-07-25 00:24:17 +00002355/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2356/// has code to accommodate several GCC extensions when type checking
2357/// pointers. Here are some objectionable examples that GCC considers warnings:
2358///
2359/// int a, *pint;
2360/// short *pshort;
2361/// struct foo *pfoo;
2362///
2363/// pint = pshort; // warning: assignment from incompatible pointer type
2364/// a = pint; // warning: assignment makes integer from pointer without a cast
2365/// pint = a; // warning: assignment makes pointer from integer without a cast
2366/// pint = pfoo; // warning: assignment from incompatible pointer type
2367///
2368/// As a result, the code for dealing with pointers is more complex than the
2369/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002370///
Chris Lattner005ed752008-01-04 18:04:52 +00002371Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002372Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002373 // Get canonical types. We're not formatting these types, just comparing
2374 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002375 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2376 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002377
2378 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002379 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002380
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002381 // If the left-hand side is a reference type, then we are in a
2382 // (rare!) case where we've allowed the use of references in C,
2383 // e.g., as a parameter type in a built-in function. In this case,
2384 // just make sure that the type referenced is compatible with the
2385 // right-hand side type. The caller is responsible for adjusting
2386 // lhsType so that the resulting expression does not have reference
2387 // type.
2388 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2389 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002390 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002391 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002392 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002393
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002394 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2395 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002396 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002397 // Relax integer conversions like we do for pointers below.
2398 if (rhsType->isIntegerType())
2399 return IntToPointer;
2400 if (lhsType->isIntegerType())
2401 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002402 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002403 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002404
Nate Begemanc5f0f652008-07-14 18:02:46 +00002405 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002406 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002407 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2408 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002409 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002410
Nate Begemanc5f0f652008-07-14 18:02:46 +00002411 // If we are allowing lax vector conversions, and LHS and RHS are both
2412 // vectors, the total size only needs to be the same. This is a bitcast;
2413 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002414 if (getLangOptions().LaxVectorConversions &&
2415 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002416 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2417 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002418 }
2419 return Incompatible;
2420 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002421
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002422 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002423 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002424
Chris Lattner390564e2008-04-07 06:49:41 +00002425 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002426 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002427 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002428
Chris Lattner390564e2008-04-07 06:49:41 +00002429 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002430 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002431
Steve Naroffa982c712008-09-29 18:10:17 +00002432 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002433 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002434 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002435
2436 // Treat block pointers as objects.
2437 if (getLangOptions().ObjC1 &&
2438 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2439 return Compatible;
2440 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002441 return Incompatible;
2442 }
2443
2444 if (isa<BlockPointerType>(lhsType)) {
2445 if (rhsType->isIntegerType())
2446 return IntToPointer;
2447
Steve Naroffa982c712008-09-29 18:10:17 +00002448 // Treat block pointers as objects.
2449 if (getLangOptions().ObjC1 &&
2450 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2451 return Compatible;
2452
Steve Naroff3454b6c2008-09-04 15:10:53 +00002453 if (rhsType->isBlockPointerType())
2454 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2455
2456 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2457 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002458 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002459 }
Chris Lattner1853da22008-01-04 23:18:45 +00002460 return Incompatible;
2461 }
2462
Chris Lattner390564e2008-04-07 06:49:41 +00002463 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002464 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002465 if (lhsType == Context.BoolTy)
2466 return Compatible;
2467
2468 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002469 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002470
Chris Lattner390564e2008-04-07 06:49:41 +00002471 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002472 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002473
2474 if (isa<BlockPointerType>(lhsType) &&
2475 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002476 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002477 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002478 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002479
Chris Lattner1853da22008-01-04 23:18:45 +00002480 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002481 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002482 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002483 }
2484 return Incompatible;
2485}
2486
Chris Lattner005ed752008-01-04 18:04:52 +00002487Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002488Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002489 if (getLangOptions().CPlusPlus) {
2490 if (!lhsType->isRecordType()) {
2491 // C++ 5.17p3: If the left operand is not of class type, the
2492 // expression is implicitly converted (C++ 4) to the
2493 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002494 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2495 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002496 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002497 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002498 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002499 }
2500
2501 // FIXME: Currently, we fall through and treat C++ classes like C
2502 // structures.
2503 }
2504
Steve Naroffcdee22d2007-11-27 17:58:44 +00002505 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2506 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002507 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2508 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002509 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002510 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002511 return Compatible;
2512 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002513
2514 // We don't allow conversion of non-null-pointer constants to integers.
2515 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2516 return IntToBlockPointer;
2517
Chris Lattner5f505bf2007-10-16 02:55:40 +00002518 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002519 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002520 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002521 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002522 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002523 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002524 if (!lhsType->isReferenceType())
2525 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002526
Chris Lattner005ed752008-01-04 18:04:52 +00002527 Sema::AssignConvertType result =
2528 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002529
2530 // C99 6.5.16.1p2: The value of the right operand is converted to the
2531 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002532 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2533 // so that we can use references in built-in functions even in C.
2534 // The getNonReferenceType() call makes sure that the resulting expression
2535 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002536 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002537 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002538 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002539}
2540
Chris Lattner005ed752008-01-04 18:04:52 +00002541Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002542Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2543 return CheckAssignmentConstraints(lhsType, rhsType);
2544}
2545
Chris Lattner1eafdea2008-11-18 01:30:42 +00002546QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002547 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002548 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002549 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002550 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002551}
2552
Chris Lattner1eafdea2008-11-18 01:30:42 +00002553inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002554 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002555 // For conversion purposes, we ignore any qualifiers.
2556 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002557 QualType lhsType =
2558 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2559 QualType rhsType =
2560 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002561
Nate Begemanc5f0f652008-07-14 18:02:46 +00002562 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002563 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002564 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002565
Nate Begemanc5f0f652008-07-14 18:02:46 +00002566 // Handle the case of a vector & extvector type of the same size and element
2567 // type. It would be nice if we only had one vector type someday.
2568 if (getLangOptions().LaxVectorConversions)
2569 if (const VectorType *LV = lhsType->getAsVectorType())
2570 if (const VectorType *RV = rhsType->getAsVectorType())
2571 if (LV->getElementType() == RV->getElementType() &&
2572 LV->getNumElements() == RV->getNumElements())
2573 return lhsType->isExtVectorType() ? lhsType : rhsType;
2574
2575 // If the lhs is an extended vector and the rhs is a scalar of the same type
2576 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002577 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002578 QualType eltType = V->getElementType();
2579
2580 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2581 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2582 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002583 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002584 return lhsType;
2585 }
2586 }
2587
Nate Begemanc5f0f652008-07-14 18:02:46 +00002588 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002589 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002590 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002591 QualType eltType = V->getElementType();
2592
2593 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2594 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2595 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002596 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002597 return rhsType;
2598 }
2599 }
2600
Chris Lattner4b009652007-07-25 00:24:17 +00002601 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002602 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002603 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002604 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002605 return QualType();
2606}
2607
2608inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002609 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002610{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002611 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002612 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002613
Steve Naroff8f708362007-08-24 19:07:16 +00002614 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002615
Chris Lattner4b009652007-07-25 00:24:17 +00002616 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002617 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002618 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002619}
2620
2621inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002622 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002623{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002624 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2625 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2626 return CheckVectorOperands(Loc, lex, rex);
2627 return InvalidOperands(Loc, lex, rex);
2628 }
Chris Lattner4b009652007-07-25 00:24:17 +00002629
Steve Naroff8f708362007-08-24 19:07:16 +00002630 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002631
Chris Lattner4b009652007-07-25 00:24:17 +00002632 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002633 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002634 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002635}
2636
2637inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002638 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002639{
2640 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002641 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002642
Steve Naroff8f708362007-08-24 19:07:16 +00002643 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002644
Chris Lattner4b009652007-07-25 00:24:17 +00002645 // handle the common case first (both operands are arithmetic).
2646 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002647 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002648
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002649 // Put any potential pointer into PExp
2650 Expr* PExp = lex, *IExp = rex;
2651 if (IExp->getType()->isPointerType())
2652 std::swap(PExp, IExp);
2653
2654 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2655 if (IExp->getType()->isIntegerType()) {
2656 // Check for arithmetic on pointers to incomplete types
2657 if (!PTy->getPointeeType()->isObjectType()) {
2658 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002659 if (getLangOptions().CPlusPlus) {
2660 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2661 << lex->getSourceRange() << rex->getSourceRange();
2662 return QualType();
2663 }
2664
2665 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002666 Diag(Loc, diag::ext_gnu_void_ptr)
2667 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002668 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002669 if (getLangOptions().CPlusPlus) {
2670 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2671 << lex->getType() << lex->getSourceRange();
2672 return QualType();
2673 }
2674
2675 // GNU extension: arithmetic on pointer to function
2676 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002677 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002678 } else {
2679 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2680 diag::err_typecheck_arithmetic_incomplete_type,
2681 lex->getSourceRange(), SourceRange(),
2682 lex->getType());
2683 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002684 }
2685 }
2686 return PExp->getType();
2687 }
2688 }
2689
Chris Lattner1eafdea2008-11-18 01:30:42 +00002690 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002691}
2692
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002693// C99 6.5.6
2694QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002695 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002696 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002697 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002698
Steve Naroff8f708362007-08-24 19:07:16 +00002699 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002700
Chris Lattnerf6da2912007-12-09 21:53:25 +00002701 // Enforce type constraints: C99 6.5.6p3.
2702
2703 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002704 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002705 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002706
2707 // Either ptr - int or ptr - ptr.
2708 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002709 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002710
Chris Lattnerf6da2912007-12-09 21:53:25 +00002711 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002712 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002713 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002714 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002715 Diag(Loc, diag::ext_gnu_void_ptr)
2716 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002717 } else if (lpointee->isFunctionType()) {
2718 if (getLangOptions().CPlusPlus) {
2719 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2720 << lex->getType() << lex->getSourceRange();
2721 return QualType();
2722 }
2723
2724 // GNU extension: arithmetic on pointer to function
2725 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2726 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002727 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002728 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002729 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002730 return QualType();
2731 }
2732 }
2733
2734 // The result type of a pointer-int computation is the pointer type.
2735 if (rex->getType()->isIntegerType())
2736 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002737
Chris Lattnerf6da2912007-12-09 21:53:25 +00002738 // Handle pointer-pointer subtractions.
2739 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002740 QualType rpointee = RHSPTy->getPointeeType();
2741
Chris Lattnerf6da2912007-12-09 21:53:25 +00002742 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002743 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002744 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002745 if (rpointee->isVoidType()) {
2746 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002747 Diag(Loc, diag::ext_gnu_void_ptr)
2748 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002749 } else if (rpointee->isFunctionType()) {
2750 if (getLangOptions().CPlusPlus) {
2751 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2752 << rex->getType() << rex->getSourceRange();
2753 return QualType();
2754 }
2755
2756 // GNU extension: arithmetic on pointer to function
2757 if (!lpointee->isFunctionType())
2758 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2759 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002760 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002761 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002762 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002763 return QualType();
2764 }
2765 }
2766
2767 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002768 if (!Context.typesAreCompatible(
2769 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2770 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002771 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002772 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002773 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002774 return QualType();
2775 }
2776
2777 return Context.getPointerDiffType();
2778 }
2779 }
2780
Chris Lattner1eafdea2008-11-18 01:30:42 +00002781 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002782}
2783
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002784// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002785QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002786 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002787 // C99 6.5.7p2: Each of the operands shall have integer type.
2788 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002789 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002790
Chris Lattner2c8bff72007-12-12 05:47:28 +00002791 // Shifts don't perform usual arithmetic conversions, they just do integer
2792 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002793 if (!isCompAssign)
2794 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002795 UsualUnaryConversions(rex);
2796
2797 // "The type of the result is that of the promoted left operand."
2798 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002799}
2800
Eli Friedman0d9549b2008-08-22 00:56:42 +00002801static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2802 ASTContext& Context) {
2803 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2804 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2805 // ID acts sort of like void* for ObjC interfaces
2806 if (LHSIface && Context.isObjCIdType(RHS))
2807 return true;
2808 if (RHSIface && Context.isObjCIdType(LHS))
2809 return true;
2810 if (!LHSIface || !RHSIface)
2811 return false;
2812 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2813 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2814}
2815
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002816// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002817QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002818 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002819 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002820 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002821
Chris Lattner254f3bc2007-08-26 01:18:55 +00002822 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002823 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2824 UsualArithmeticConversions(lex, rex);
2825 else {
2826 UsualUnaryConversions(lex);
2827 UsualUnaryConversions(rex);
2828 }
Chris Lattner4b009652007-07-25 00:24:17 +00002829 QualType lType = lex->getType();
2830 QualType rType = rex->getType();
2831
Ted Kremenek486509e2007-10-29 17:13:39 +00002832 // For non-floating point types, check for self-comparisons of the form
2833 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2834 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002835 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002836 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2837 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002838 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002839 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002840 }
2841
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002842 // The result of comparisons is 'bool' in C++, 'int' in C.
2843 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2844
Chris Lattner254f3bc2007-08-26 01:18:55 +00002845 if (isRelational) {
2846 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002847 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002848 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002849 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002850 if (lType->isFloatingType()) {
2851 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002852 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002853 }
2854
Chris Lattner254f3bc2007-08-26 01:18:55 +00002855 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002856 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002857 }
Chris Lattner4b009652007-07-25 00:24:17 +00002858
Chris Lattner22be8422007-08-26 01:10:14 +00002859 bool LHSIsNull = lex->isNullPointerConstant(Context);
2860 bool RHSIsNull = rex->isNullPointerConstant(Context);
2861
Chris Lattner254f3bc2007-08-26 01:18:55 +00002862 // All of the following pointer related warnings are GCC extensions, except
2863 // when handling null pointer constants. One day, we can consider making them
2864 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002865 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002866 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002867 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002868 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002869 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002870
Steve Naroff3b435622007-11-13 14:57:38 +00002871 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002872 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2873 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002874 RCanPointeeTy.getUnqualifiedType()) &&
2875 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002876 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002877 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002878 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002879 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002880 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002881 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002882 // Handle block pointer types.
2883 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2884 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2885 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2886
2887 if (!LHSIsNull && !RHSIsNull &&
2888 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002889 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002890 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002891 }
2892 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002893 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002894 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002895 // Allow block pointers to be compared with null pointer constants.
2896 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2897 (lType->isPointerType() && rType->isBlockPointerType())) {
2898 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002899 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002900 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002901 }
2902 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002903 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002904 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002905
Steve Naroff936c4362008-06-03 14:04:54 +00002906 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002907 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002908 const PointerType *LPT = lType->getAsPointerType();
2909 const PointerType *RPT = rType->getAsPointerType();
2910 bool LPtrToVoid = LPT ?
2911 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2912 bool RPtrToVoid = RPT ?
2913 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2914
2915 if (!LPtrToVoid && !RPtrToVoid &&
2916 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002917 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002918 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002919 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002920 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002921 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002922 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002923 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002924 }
Steve Naroff936c4362008-06-03 14:04:54 +00002925 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2926 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002927 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002928 } else {
2929 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002930 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002931 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002932 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002933 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002934 }
Steve Naroff936c4362008-06-03 14:04:54 +00002935 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002936 }
Steve Naroff936c4362008-06-03 14:04:54 +00002937 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2938 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002939 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002940 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002941 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002942 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002943 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002944 }
Steve Naroff936c4362008-06-03 14:04:54 +00002945 if (lType->isIntegerType() &&
2946 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002947 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002948 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002949 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002950 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002951 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002952 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002953 // Handle block pointers.
2954 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2955 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002956 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002957 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002958 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002959 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002960 }
2961 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2962 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002963 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002964 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002965 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002966 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002967 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002968 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002969}
2970
Nate Begemanc5f0f652008-07-14 18:02:46 +00002971/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2972/// operates on extended vector types. Instead of producing an IntTy result,
2973/// like a scalar comparison, a vector comparison produces a vector of integer
2974/// types.
2975QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002976 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002977 bool isRelational) {
2978 // Check to make sure we're operating on vectors of the same type and width,
2979 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002980 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002981 if (vType.isNull())
2982 return vType;
2983
2984 QualType lType = lex->getType();
2985 QualType rType = rex->getType();
2986
2987 // For non-floating point types, check for self-comparisons of the form
2988 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2989 // often indicate logic errors in the program.
2990 if (!lType->isFloatingType()) {
2991 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2992 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2993 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002994 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002995 }
2996
2997 // Check for comparisons of floating point operands using != and ==.
2998 if (!isRelational && lType->isFloatingType()) {
2999 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003000 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003001 }
3002
3003 // Return the type for the comparison, which is the same as vector type for
3004 // integer vectors, or an integer type of identical size and number of
3005 // elements for floating point vectors.
3006 if (lType->isIntegerType())
3007 return lType;
3008
3009 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003010 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003011 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003012 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003013 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3014 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3015
3016 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3017 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003018 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3019}
3020
Chris Lattner4b009652007-07-25 00:24:17 +00003021inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003022 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003023{
3024 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003025 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003026
Steve Naroff8f708362007-08-24 19:07:16 +00003027 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003028
3029 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003030 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003031 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003032}
3033
3034inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003035 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003036{
3037 UsualUnaryConversions(lex);
3038 UsualUnaryConversions(rex);
3039
Eli Friedmanbea3f842008-05-13 20:16:47 +00003040 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003041 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003042 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003043}
3044
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003045/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3046/// is a read-only property; return true if so. A readonly property expression
3047/// depends on various declarations and thus must be treated specially.
3048///
3049static bool IsReadonlyProperty(Expr *E, Sema &S)
3050{
3051 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3052 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3053 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3054 QualType BaseType = PropExpr->getBase()->getType();
3055 if (const PointerType *PTy = BaseType->getAsPointerType())
3056 if (const ObjCInterfaceType *IFTy =
3057 PTy->getPointeeType()->getAsObjCInterfaceType())
3058 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3059 if (S.isPropertyReadonly(PDecl, IFace))
3060 return true;
3061 }
3062 }
3063 return false;
3064}
3065
Chris Lattner4c2642c2008-11-18 01:22:49 +00003066/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3067/// emit an error and return true. If so, return false.
3068static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003069 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3070 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3071 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003072 if (IsLV == Expr::MLV_Valid)
3073 return false;
3074
3075 unsigned Diag = 0;
3076 bool NeedType = false;
3077 switch (IsLV) { // C99 6.5.16p2
3078 default: assert(0 && "Unknown result from isModifiableLvalue!");
3079 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003080 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003081 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3082 NeedType = true;
3083 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003084 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003085 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3086 NeedType = true;
3087 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003088 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003089 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3090 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003091 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003092 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3093 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003094 case Expr::MLV_IncompleteType:
3095 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003096 return S.DiagnoseIncompleteType(Loc, E->getType(),
3097 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3098 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003099 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003100 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3101 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003102 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003103 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3104 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003105 case Expr::MLV_ReadonlyProperty:
3106 Diag = diag::error_readonly_property_assignment;
3107 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003108 case Expr::MLV_NoSetterProperty:
3109 Diag = diag::error_nosetter_property_assignment;
3110 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003111 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003112
Chris Lattner4c2642c2008-11-18 01:22:49 +00003113 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003114 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003115 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003116 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003117 return true;
3118}
3119
3120
3121
3122// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003123QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3124 SourceLocation Loc,
3125 QualType CompoundType) {
3126 // Verify that LHS is a modifiable lvalue, and emit error if not.
3127 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003128 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003129
3130 QualType LHSType = LHS->getType();
3131 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003132
Chris Lattner005ed752008-01-04 18:04:52 +00003133 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003134 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003135 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003136 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003137 // Special case of NSObject attributes on c-style pointer types.
3138 if (ConvTy == IncompatiblePointer &&
3139 ((Context.isObjCNSObjectType(LHSType) &&
3140 Context.isObjCObjectPointerType(RHSType)) ||
3141 (Context.isObjCNSObjectType(RHSType) &&
3142 Context.isObjCObjectPointerType(LHSType))))
3143 ConvTy = Compatible;
3144
Chris Lattner34c85082008-08-21 18:04:13 +00003145 // If the RHS is a unary plus or minus, check to see if they = and + are
3146 // right next to each other. If so, the user may have typo'd "x =+ 4"
3147 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003148 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003149 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3150 RHSCheck = ICE->getSubExpr();
3151 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3152 if ((UO->getOpcode() == UnaryOperator::Plus ||
3153 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003154 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003155 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003156 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003157 Diag(Loc, diag::warn_not_compound_assign)
3158 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3159 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003160 }
3161 } else {
3162 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003163 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003164 }
Chris Lattner005ed752008-01-04 18:04:52 +00003165
Chris Lattner1eafdea2008-11-18 01:30:42 +00003166 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3167 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003168 return QualType();
3169
Chris Lattner4b009652007-07-25 00:24:17 +00003170 // C99 6.5.16p3: The type of an assignment expression is the type of the
3171 // left operand unless the left operand has qualified type, in which case
3172 // it is the unqualified version of the type of the left operand.
3173 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3174 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003175 // C++ 5.17p1: the type of the assignment expression is that of its left
3176 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003177 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003178}
3179
Chris Lattner1eafdea2008-11-18 01:30:42 +00003180// C99 6.5.17
3181QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3182 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003183
3184 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003185 DefaultFunctionArrayConversion(RHS);
3186 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003187}
3188
3189/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3190/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003191QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3192 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003193 QualType ResType = Op->getType();
3194 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003195
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003196 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3197 // Decrement of bool is not allowed.
3198 if (!isInc) {
3199 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3200 return QualType();
3201 }
3202 // Increment of bool sets it to true, but is deprecated.
3203 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3204 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003205 // OK!
3206 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3207 // C99 6.5.2.4p2, 6.5.6p2
3208 if (PT->getPointeeType()->isObjectType()) {
3209 // Pointer to object is ok!
3210 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003211 if (getLangOptions().CPlusPlus) {
3212 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3213 << Op->getSourceRange();
3214 return QualType();
3215 }
3216
3217 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003218 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003219 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003220 if (getLangOptions().CPlusPlus) {
3221 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3222 << Op->getType() << Op->getSourceRange();
3223 return QualType();
3224 }
3225
3226 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003227 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003228 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003229 } else {
3230 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3231 diag::err_typecheck_arithmetic_incomplete_type,
3232 Op->getSourceRange(), SourceRange(),
3233 ResType);
3234 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003235 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003236 } else if (ResType->isComplexType()) {
3237 // C99 does not support ++/-- on complex types, we allow as an extension.
3238 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003239 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003240 } else {
3241 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003242 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003243 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003244 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003245 // At this point, we know we have a real, complex or pointer type.
3246 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003247 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003248 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003249 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003250}
3251
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003252/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003253/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003254/// where the declaration is needed for type checking. We only need to
3255/// handle cases when the expression references a function designator
3256/// or is an lvalue. Here are some examples:
3257/// - &(x) => x
3258/// - &*****f => f for f a function designator.
3259/// - &s.xx => s
3260/// - &s.zz[1].yy -> s, if zz is an array
3261/// - *(x + 1) -> x, if x is an array
3262/// - &"123"[2] -> 0
3263/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003264static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003265 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003266 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003267 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003268 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003269 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003270 // Fields cannot be declared with a 'register' storage class.
3271 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003272 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003273 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003274 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003275 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003276 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003277
Douglas Gregord2baafd2008-10-21 16:13:35 +00003278 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003279 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003280 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003281 return 0;
3282 else
3283 return VD;
3284 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003285 case Stmt::UnaryOperatorClass: {
3286 UnaryOperator *UO = cast<UnaryOperator>(E);
3287
3288 switch(UO->getOpcode()) {
3289 case UnaryOperator::Deref: {
3290 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003291 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3292 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3293 if (!VD || VD->getType()->isPointerType())
3294 return 0;
3295 return VD;
3296 }
3297 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003298 }
3299 case UnaryOperator::Real:
3300 case UnaryOperator::Imag:
3301 case UnaryOperator::Extension:
3302 return getPrimaryDecl(UO->getSubExpr());
3303 default:
3304 return 0;
3305 }
3306 }
3307 case Stmt::BinaryOperatorClass: {
3308 BinaryOperator *BO = cast<BinaryOperator>(E);
3309
3310 // Handle cases involving pointer arithmetic. The result of an
3311 // Assign or AddAssign is not an lvalue so they can be ignored.
3312
3313 // (x + n) or (n + x) => x
3314 if (BO->getOpcode() == BinaryOperator::Add) {
3315 if (BO->getLHS()->getType()->isPointerType()) {
3316 return getPrimaryDecl(BO->getLHS());
3317 } else if (BO->getRHS()->getType()->isPointerType()) {
3318 return getPrimaryDecl(BO->getRHS());
3319 }
3320 }
3321
3322 return 0;
3323 }
Chris Lattner4b009652007-07-25 00:24:17 +00003324 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003325 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003326 case Stmt::ImplicitCastExprClass:
3327 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003328 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003329 default:
3330 return 0;
3331 }
3332}
3333
3334/// CheckAddressOfOperand - The operand of & must be either a function
3335/// designator or an lvalue designating an object. If it is an lvalue, the
3336/// object cannot be declared with storage class register or be a bit field.
3337/// Note: The usual conversions are *not* applied to the operand of the &
3338/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003339/// In C++, the operand might be an overloaded function name, in which case
3340/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003341QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003342 if (op->isTypeDependent())
3343 return Context.DependentTy;
3344
Steve Naroff9c6c3592008-01-13 17:10:08 +00003345 if (getLangOptions().C99) {
3346 // Implement C99-only parts of addressof rules.
3347 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3348 if (uOp->getOpcode() == UnaryOperator::Deref)
3349 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3350 // (assuming the deref expression is valid).
3351 return uOp->getSubExpr()->getType();
3352 }
3353 // Technically, there should be a check for array subscript
3354 // expressions here, but the result of one is always an lvalue anyway.
3355 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003356 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003357 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003358
Chris Lattner4b009652007-07-25 00:24:17 +00003359 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003360 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3361 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003362 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3363 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003364 return QualType();
3365 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003366 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003367 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3368 if (Field->isBitField()) {
3369 Diag(OpLoc, diag::err_typecheck_address_of)
3370 << "bit-field" << op->getSourceRange();
3371 return QualType();
3372 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003373 }
3374 // Check for Apple extension for accessing vector components.
3375 } else if (isa<ArraySubscriptExpr>(op) &&
3376 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003377 Diag(OpLoc, diag::err_typecheck_address_of)
3378 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003379 return QualType();
3380 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003381 // We have an lvalue with a decl. Make sure the decl is not declared
3382 // with the register storage-class specifier.
3383 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3384 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003385 Diag(OpLoc, diag::err_typecheck_address_of)
3386 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003387 return QualType();
3388 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003389 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003390 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003391 } else if (isa<FieldDecl>(dcl)) {
3392 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003393 } else if (isa<FunctionDecl>(dcl)) {
3394 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003395 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003396 else
Chris Lattner4b009652007-07-25 00:24:17 +00003397 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003398 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003399
Chris Lattner4b009652007-07-25 00:24:17 +00003400 // If the operand has type "type", the result has type "pointer to type".
3401 return Context.getPointerType(op->getType());
3402}
3403
Chris Lattnerda5c0872008-11-23 09:13:29 +00003404QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3405 UsualUnaryConversions(Op);
3406 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003407
Chris Lattnerda5c0872008-11-23 09:13:29 +00003408 // Note that per both C89 and C99, this is always legal, even if ptype is an
3409 // incomplete type or void. It would be possible to warn about dereferencing
3410 // a void pointer, but it's completely well-defined, and such a warning is
3411 // unlikely to catch any mistakes.
3412 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003413 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003414
Chris Lattner77d52da2008-11-20 06:06:08 +00003415 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003416 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003417 return QualType();
3418}
3419
3420static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3421 tok::TokenKind Kind) {
3422 BinaryOperator::Opcode Opc;
3423 switch (Kind) {
3424 default: assert(0 && "Unknown binop!");
3425 case tok::star: Opc = BinaryOperator::Mul; break;
3426 case tok::slash: Opc = BinaryOperator::Div; break;
3427 case tok::percent: Opc = BinaryOperator::Rem; break;
3428 case tok::plus: Opc = BinaryOperator::Add; break;
3429 case tok::minus: Opc = BinaryOperator::Sub; break;
3430 case tok::lessless: Opc = BinaryOperator::Shl; break;
3431 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3432 case tok::lessequal: Opc = BinaryOperator::LE; break;
3433 case tok::less: Opc = BinaryOperator::LT; break;
3434 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3435 case tok::greater: Opc = BinaryOperator::GT; break;
3436 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3437 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3438 case tok::amp: Opc = BinaryOperator::And; break;
3439 case tok::caret: Opc = BinaryOperator::Xor; break;
3440 case tok::pipe: Opc = BinaryOperator::Or; break;
3441 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3442 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3443 case tok::equal: Opc = BinaryOperator::Assign; break;
3444 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3445 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3446 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3447 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3448 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3449 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3450 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3451 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3452 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3453 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3454 case tok::comma: Opc = BinaryOperator::Comma; break;
3455 }
3456 return Opc;
3457}
3458
3459static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3460 tok::TokenKind Kind) {
3461 UnaryOperator::Opcode Opc;
3462 switch (Kind) {
3463 default: assert(0 && "Unknown unary op!");
3464 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3465 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3466 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3467 case tok::star: Opc = UnaryOperator::Deref; break;
3468 case tok::plus: Opc = UnaryOperator::Plus; break;
3469 case tok::minus: Opc = UnaryOperator::Minus; break;
3470 case tok::tilde: Opc = UnaryOperator::Not; break;
3471 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003472 case tok::kw___real: Opc = UnaryOperator::Real; break;
3473 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3474 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3475 }
3476 return Opc;
3477}
3478
Douglas Gregord7f915e2008-11-06 23:29:22 +00003479/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3480/// operator @p Opc at location @c TokLoc. This routine only supports
3481/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003482Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3483 unsigned Op,
3484 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003485 QualType ResultTy; // Result type of the binary operator.
3486 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3487 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3488
3489 switch (Opc) {
3490 default:
3491 assert(0 && "Unknown binary expr!");
3492 case BinaryOperator::Assign:
3493 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3494 break;
3495 case BinaryOperator::Mul:
3496 case BinaryOperator::Div:
3497 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3498 break;
3499 case BinaryOperator::Rem:
3500 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3501 break;
3502 case BinaryOperator::Add:
3503 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3504 break;
3505 case BinaryOperator::Sub:
3506 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3507 break;
3508 case BinaryOperator::Shl:
3509 case BinaryOperator::Shr:
3510 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3511 break;
3512 case BinaryOperator::LE:
3513 case BinaryOperator::LT:
3514 case BinaryOperator::GE:
3515 case BinaryOperator::GT:
3516 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3517 break;
3518 case BinaryOperator::EQ:
3519 case BinaryOperator::NE:
3520 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3521 break;
3522 case BinaryOperator::And:
3523 case BinaryOperator::Xor:
3524 case BinaryOperator::Or:
3525 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3526 break;
3527 case BinaryOperator::LAnd:
3528 case BinaryOperator::LOr:
3529 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3530 break;
3531 case BinaryOperator::MulAssign:
3532 case BinaryOperator::DivAssign:
3533 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3534 if (!CompTy.isNull())
3535 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3536 break;
3537 case BinaryOperator::RemAssign:
3538 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3539 if (!CompTy.isNull())
3540 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3541 break;
3542 case BinaryOperator::AddAssign:
3543 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3544 if (!CompTy.isNull())
3545 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3546 break;
3547 case BinaryOperator::SubAssign:
3548 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3549 if (!CompTy.isNull())
3550 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3551 break;
3552 case BinaryOperator::ShlAssign:
3553 case BinaryOperator::ShrAssign:
3554 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3555 if (!CompTy.isNull())
3556 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3557 break;
3558 case BinaryOperator::AndAssign:
3559 case BinaryOperator::XorAssign:
3560 case BinaryOperator::OrAssign:
3561 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3562 if (!CompTy.isNull())
3563 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3564 break;
3565 case BinaryOperator::Comma:
3566 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3567 break;
3568 }
3569 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003570 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003571 if (CompTy.isNull())
3572 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3573 else
3574 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003575 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003576}
3577
Chris Lattner4b009652007-07-25 00:24:17 +00003578// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003579Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3580 tok::TokenKind Kind,
3581 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003582 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003583 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003584
Steve Naroff87d58b42007-09-16 03:34:24 +00003585 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3586 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003587
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003588 // If either expression is type-dependent, just build the AST.
3589 // FIXME: We'll need to perform some caching of the result of name
3590 // lookup for operator+.
3591 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003592 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3593 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003594 Context.DependentTy,
3595 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003596 else
3597 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3598 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003599 }
3600
Douglas Gregord7f915e2008-11-06 23:29:22 +00003601 if (getLangOptions().CPlusPlus &&
3602 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3603 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003604 // If this is one of the assignment operators, we only perform
3605 // overload resolution if the left-hand side is a class or
3606 // enumeration type (C++ [expr.ass]p3).
3607 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3608 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3609 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3610 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003611
Douglas Gregord7f915e2008-11-06 23:29:22 +00003612 // Determine which overloaded operator we're dealing with.
3613 static const OverloadedOperatorKind OverOps[] = {
3614 OO_Star, OO_Slash, OO_Percent,
3615 OO_Plus, OO_Minus,
3616 OO_LessLess, OO_GreaterGreater,
3617 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3618 OO_EqualEqual, OO_ExclaimEqual,
3619 OO_Amp,
3620 OO_Caret,
3621 OO_Pipe,
3622 OO_AmpAmp,
3623 OO_PipePipe,
3624 OO_Equal, OO_StarEqual,
3625 OO_SlashEqual, OO_PercentEqual,
3626 OO_PlusEqual, OO_MinusEqual,
3627 OO_LessLessEqual, OO_GreaterGreaterEqual,
3628 OO_AmpEqual, OO_CaretEqual,
3629 OO_PipeEqual,
3630 OO_Comma
3631 };
3632 OverloadedOperatorKind OverOp = OverOps[Opc];
3633
Douglas Gregor5ed15042008-11-18 23:14:02 +00003634 // Add the appropriate overloaded operators (C++ [over.match.oper])
3635 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003636 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003637 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003638 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003639
3640 // Perform overload resolution.
3641 OverloadCandidateSet::iterator Best;
3642 switch (BestViableFunction(CandidateSet, Best)) {
3643 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003644 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003645 FunctionDecl *FnDecl = Best->Function;
3646
Douglas Gregor70d26122008-11-12 17:17:38 +00003647 if (FnDecl) {
3648 // We matched an overloaded operator. Build a call to that
3649 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003650
Douglas Gregor70d26122008-11-12 17:17:38 +00003651 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3653 if (PerformObjectArgumentInitialization(lhs, Method) ||
3654 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3655 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003656 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003657 } else {
3658 // Convert the arguments.
3659 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3660 "passing") ||
3661 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3662 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003663 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003664 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003665
Douglas Gregor70d26122008-11-12 17:17:38 +00003666 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003667 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003668 = FnDecl->getType()->getAsFunctionType()->getResultType();
3669 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003670
Douglas Gregor70d26122008-11-12 17:17:38 +00003671 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003672 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3673 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003674 UsualUnaryConversions(FnExpr);
3675
Steve Naroff774e4152009-01-21 00:14:39 +00003676 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3677 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003678 } else {
3679 // We matched a built-in operator. Convert the arguments, then
3680 // break out so that we will build the appropriate built-in
3681 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003682 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3683 Best->Conversions[0], "passing") ||
3684 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3685 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003686 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003687
3688 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003689 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003690 }
3691
3692 case OR_No_Viable_Function:
3693 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003694 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003695 break;
3696
3697 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003698 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3699 << BinaryOperator::getOpcodeStr(Opc)
3700 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003701 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003702 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003703 }
3704
Douglas Gregor70d26122008-11-12 17:17:38 +00003705 // Either we found no viable overloaded operator or we matched a
3706 // built-in operator. In either case, fall through to trying to
3707 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003708 }
3709
Douglas Gregord7f915e2008-11-06 23:29:22 +00003710 // Build a built-in binary operation.
3711 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003712}
3713
3714// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003715Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3716 tok::TokenKind Op, ExprArg input) {
3717 // FIXME: Input is modified later, but smart pointer not reassigned.
3718 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003719 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003720
3721 if (getLangOptions().CPlusPlus &&
3722 (Input->getType()->isRecordType()
3723 || Input->getType()->isEnumeralType())) {
3724 // Determine which overloaded operator we're dealing with.
3725 static const OverloadedOperatorKind OverOps[] = {
3726 OO_None, OO_None,
3727 OO_PlusPlus, OO_MinusMinus,
3728 OO_Amp, OO_Star,
3729 OO_Plus, OO_Minus,
3730 OO_Tilde, OO_Exclaim,
3731 OO_None, OO_None,
3732 OO_None,
3733 OO_None
3734 };
3735 OverloadedOperatorKind OverOp = OverOps[Opc];
3736
3737 // Add the appropriate overloaded operators (C++ [over.match.oper])
3738 // to the candidate set.
3739 OverloadCandidateSet CandidateSet;
3740 if (OverOp != OO_None)
3741 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3742
3743 // Perform overload resolution.
3744 OverloadCandidateSet::iterator Best;
3745 switch (BestViableFunction(CandidateSet, Best)) {
3746 case OR_Success: {
3747 // We found a built-in operator or an overloaded operator.
3748 FunctionDecl *FnDecl = Best->Function;
3749
3750 if (FnDecl) {
3751 // We matched an overloaded operator. Build a call to that
3752 // operator.
3753
3754 // Convert the arguments.
3755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3756 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003757 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003758 } else {
3759 // Convert the arguments.
3760 if (PerformCopyInitialization(Input,
3761 FnDecl->getParamDecl(0)->getType(),
3762 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003763 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003764 }
3765
3766 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003767 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003768 = FnDecl->getType()->getAsFunctionType()->getResultType();
3769 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003770
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003771 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003772 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3773 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003774 UsualUnaryConversions(FnExpr);
3775
Sebastian Redl8b769972009-01-19 00:08:26 +00003776 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003777 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3778 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003779 } else {
3780 // We matched a built-in operator. Convert the arguments, then
3781 // break out so that we will build the appropriate built-in
3782 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003783 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3784 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003785 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003786
3787 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003788 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003789 }
3790
3791 case OR_No_Viable_Function:
3792 // No viable function; fall through to handling this as a
3793 // built-in operator, which will produce an error message for us.
3794 break;
3795
3796 case OR_Ambiguous:
3797 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3798 << UnaryOperator::getOpcodeStr(Opc)
3799 << Input->getSourceRange();
3800 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003801 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003802 }
3803
3804 // Either we found no viable overloaded operator or we matched a
3805 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003806 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003807 }
3808
Chris Lattner4b009652007-07-25 00:24:17 +00003809 QualType resultType;
3810 switch (Opc) {
3811 default:
3812 assert(0 && "Unimplemented unary expr!");
3813 case UnaryOperator::PreInc:
3814 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003815 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3816 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003817 break;
3818 case UnaryOperator::AddrOf:
3819 resultType = CheckAddressOfOperand(Input, OpLoc);
3820 break;
3821 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003822 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003823 resultType = CheckIndirectionOperand(Input, OpLoc);
3824 break;
3825 case UnaryOperator::Plus:
3826 case UnaryOperator::Minus:
3827 UsualUnaryConversions(Input);
3828 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003829 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3830 break;
3831 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3832 resultType->isEnumeralType())
3833 break;
3834 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3835 Opc == UnaryOperator::Plus &&
3836 resultType->isPointerType())
3837 break;
3838
Sebastian Redl8b769972009-01-19 00:08:26 +00003839 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3840 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003841 case UnaryOperator::Not: // bitwise complement
3842 UsualUnaryConversions(Input);
3843 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003844 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3845 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3846 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003847 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003848 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003849 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003850 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3851 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003852 break;
3853 case UnaryOperator::LNot: // logical negation
3854 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3855 DefaultFunctionArrayConversion(Input);
3856 resultType = Input->getType();
3857 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003858 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3859 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003860 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003861 // In C++, it's bool. C++ 5.3.1p8
3862 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003863 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003864 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003865 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003866 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003867 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003868 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003869 resultType = Input->getType();
3870 break;
3871 }
3872 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003873 return ExprError();
3874 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003875 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003876}
3877
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003878/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3879Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003880 SourceLocation LabLoc,
3881 IdentifierInfo *LabelII) {
3882 // Look up the record for this label identifier.
3883 LabelStmt *&LabelDecl = LabelMap[LabelII];
3884
Daniel Dunbar879788d2008-08-04 16:51:22 +00003885 // If we haven't seen this label yet, create a forward reference. It
3886 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003887 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00003888 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00003889
3890 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00003891 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3892 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003893}
3894
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003895Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003896 SourceLocation RPLoc) { // "({..})"
3897 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3898 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3899 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3900
3901 // FIXME: there are a variety of strange constraints to enforce here, for
3902 // example, it is not possible to goto into a stmt expression apparently.
3903 // More semantic analysis is needed.
3904
3905 // FIXME: the last statement in the compount stmt has its value used. We
3906 // should not warn about it being unused.
3907
3908 // If there are sub stmts in the compound stmt, take the type of the last one
3909 // as the type of the stmtexpr.
3910 QualType Ty = Context.VoidTy;
3911
Chris Lattner200964f2008-07-26 19:51:01 +00003912 if (!Compound->body_empty()) {
3913 Stmt *LastStmt = Compound->body_back();
3914 // If LastStmt is a label, skip down through into the body.
3915 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3916 LastStmt = Label->getSubStmt();
3917
3918 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003919 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003920 }
Chris Lattner4b009652007-07-25 00:24:17 +00003921
Steve Naroff774e4152009-01-21 00:14:39 +00003922 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00003923}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003924
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003925Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3926 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003927 SourceLocation TypeLoc,
3928 TypeTy *argty,
3929 OffsetOfComponent *CompPtr,
3930 unsigned NumComponents,
3931 SourceLocation RPLoc) {
3932 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3933 assert(!ArgTy.isNull() && "Missing type argument!");
3934
3935 // We must have at least one component that refers to the type, and the first
3936 // one is known to be a field designator. Verify that the ArgTy represents
3937 // a struct/union/class.
3938 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003939 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003940
3941 // Otherwise, create a compound literal expression as the base, and
3942 // iteratively process the offsetof designators.
Steve Naroff774e4152009-01-21 00:14:39 +00003943 Expr *Res = new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, 0,
3944 false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003945
Chris Lattnerb37522e2007-08-31 21:49:13 +00003946 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3947 // GCC extension, diagnose them.
3948 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003949 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3950 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003951
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003952 for (unsigned i = 0; i != NumComponents; ++i) {
3953 const OffsetOfComponent &OC = CompPtr[i];
3954 if (OC.isBrackets) {
3955 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003956 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003957 if (!AT) {
3958 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003959 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003960 }
3961
Chris Lattner2af6a802007-08-30 17:59:59 +00003962 // FIXME: C++: Verify that operator[] isn't overloaded.
3963
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003964 // C99 6.5.2.1p1
3965 Expr *Idx = static_cast<Expr*>(OC.U.E);
3966 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003967 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3968 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003969
Steve Naroff774e4152009-01-21 00:14:39 +00003970 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
3971 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003972 continue;
3973 }
3974
3975 const RecordType *RC = Res->getType()->getAsRecordType();
3976 if (!RC) {
3977 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003978 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003979 }
3980
3981 // Get the decl corresponding to this.
3982 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003983 FieldDecl *MemberDecl
3984 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3985 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003986 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003987 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003988 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3989 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003990
3991 // FIXME: C++: Verify that MemberDecl isn't a static field.
3992 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003993 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3994 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00003995 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3996 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003997 }
3998
Steve Naroff774e4152009-01-21 00:14:39 +00003999 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4000 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004001}
4002
4003
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004004Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004005 TypeTy *arg1, TypeTy *arg2,
4006 SourceLocation RPLoc) {
4007 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4008 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4009
4010 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4011
Steve Naroff774e4152009-01-21 00:14:39 +00004012 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4013 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004014}
4015
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004016Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004017 ExprTy *expr1, ExprTy *expr2,
4018 SourceLocation RPLoc) {
4019 Expr *CondExpr = static_cast<Expr*>(cond);
4020 Expr *LHSExpr = static_cast<Expr*>(expr1);
4021 Expr *RHSExpr = static_cast<Expr*>(expr2);
4022
4023 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4024
4025 // The conditional expression is required to be a constant expression.
4026 llvm::APSInt condEval(32);
4027 SourceLocation ExpLoc;
4028 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004029 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4030 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004031
4032 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4033 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4034 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004035 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4036 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004037}
4038
Steve Naroff52a81c02008-09-03 18:15:37 +00004039//===----------------------------------------------------------------------===//
4040// Clang Extensions.
4041//===----------------------------------------------------------------------===//
4042
4043/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004044void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004045 // Analyze block parameters.
4046 BlockSemaInfo *BSI = new BlockSemaInfo();
4047
4048 // Add BSI to CurBlock.
4049 BSI->PrevBlockInfo = CurBlock;
4050 CurBlock = BSI;
4051
4052 BSI->ReturnType = 0;
4053 BSI->TheScope = BlockScope;
4054
Steve Naroff52059382008-10-10 01:28:17 +00004055 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004056 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004057}
4058
4059void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004060 // Analyze arguments to block.
4061 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4062 "Not a function declarator!");
4063 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4064
Steve Naroff52059382008-10-10 01:28:17 +00004065 CurBlock->hasPrototype = FTI.hasPrototype;
4066 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004067
4068 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4069 // no arguments, not a function that takes a single void argument.
4070 if (FTI.hasPrototype &&
4071 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4072 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4073 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4074 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004075 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004076 } else if (FTI.hasPrototype) {
4077 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004078 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4079 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004080 }
Steve Naroff52059382008-10-10 01:28:17 +00004081 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4082
4083 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4084 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4085 // If this has an identifier, add it to the scope stack.
4086 if ((*AI)->getIdentifier())
4087 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004088}
4089
4090/// ActOnBlockError - If there is an error parsing a block, this callback
4091/// is invoked to pop the information about the block from the action impl.
4092void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4093 // Ensure that CurBlock is deleted.
4094 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4095
4096 // Pop off CurBlock, handle nested blocks.
4097 CurBlock = CurBlock->PrevBlockInfo;
4098
4099 // FIXME: Delete the ParmVarDecl objects as well???
4100
4101}
4102
4103/// ActOnBlockStmtExpr - This is called when the body of a block statement
4104/// literal was successfully completed. ^(int x){...}
4105Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4106 Scope *CurScope) {
4107 // Ensure that CurBlock is deleted.
4108 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4109 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4110
Steve Naroff52059382008-10-10 01:28:17 +00004111 PopDeclContext();
4112
Steve Naroff52a81c02008-09-03 18:15:37 +00004113 // Pop off CurBlock, handle nested blocks.
4114 CurBlock = CurBlock->PrevBlockInfo;
4115
4116 QualType RetTy = Context.VoidTy;
4117 if (BSI->ReturnType)
4118 RetTy = QualType(BSI->ReturnType, 0);
4119
4120 llvm::SmallVector<QualType, 8> ArgTypes;
4121 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4122 ArgTypes.push_back(BSI->Params[i]->getType());
4123
4124 QualType BlockTy;
4125 if (!BSI->hasPrototype)
4126 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4127 else
4128 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004129 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004130
4131 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004132
Steve Naroff95029d92008-10-08 18:44:00 +00004133 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004134 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004135}
4136
Nate Begemanbd881ef2008-01-30 20:50:20 +00004137/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004138/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004139/// The number of arguments has already been validated to match the number of
4140/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004141static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4142 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004143 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004144 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004145 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4146 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004147
4148 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004149 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004150 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004151 return true;
4152}
4153
4154Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4155 SourceLocation *CommaLocs,
4156 SourceLocation BuiltinLoc,
4157 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004158 // __builtin_overload requires at least 2 arguments
4159 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004160 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4161 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004162
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004163 // The first argument is required to be a constant expression. It tells us
4164 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004165 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004166 Expr *NParamsExpr = Args[0];
4167 llvm::APSInt constEval(32);
4168 SourceLocation ExpLoc;
4169 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004170 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4171 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004172
4173 // Verify that the number of parameters is > 0
4174 unsigned NumParams = constEval.getZExtValue();
4175 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004176 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4177 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004178 // Verify that we have at least 1 + NumParams arguments to the builtin.
4179 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004180 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4181 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004182
4183 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004184 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004185 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004186 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4187 // UsualUnaryConversions will convert the function DeclRefExpr into a
4188 // pointer to function.
4189 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004190 const FunctionTypeProto *FnType = 0;
4191 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4192 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004193
4194 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4195 // parameters, and the number of parameters must match the value passed to
4196 // the builtin.
4197 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004198 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4199 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004200
4201 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004202 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004203 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004204 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004205 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004206 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4207 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004208 // Remember our match, and continue processing the remaining arguments
4209 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004210 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004211 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004212 BuiltinLoc, RParenLoc);
4213 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004214 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004215 // Return the newly created OverloadExpr node, if we succeded in matching
4216 // exactly one of the candidate functions.
4217 if (OE)
4218 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004219
4220 // If we didn't find a matching function Expr in the __builtin_overload list
4221 // the return an error.
4222 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004223 for (unsigned i = 0; i != NumParams; ++i) {
4224 if (i != 0) typeNames += ", ";
4225 typeNames += Args[i+1]->getType().getAsString();
4226 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004227
Chris Lattner77d52da2008-11-20 06:06:08 +00004228 return Diag(BuiltinLoc, diag::err_overload_no_match)
4229 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004230}
4231
Anders Carlsson36760332007-10-15 20:28:48 +00004232Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4233 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004234 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004235 Expr *E = static_cast<Expr*>(expr);
4236 QualType T = QualType::getFromOpaquePtr(type);
4237
4238 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004239
4240 // Get the va_list type
4241 QualType VaListType = Context.getBuiltinVaListType();
4242 // Deal with implicit array decay; for example, on x86-64,
4243 // va_list is an array, but it's supposed to decay to
4244 // a pointer for va_arg.
4245 if (VaListType->isArrayType())
4246 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004247 // Make sure the input expression also decays appropriately.
4248 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004249
4250 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004251 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004252 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004253 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004254
4255 // FIXME: Warn if a non-POD type is passed in.
4256
Steve Naroff774e4152009-01-21 00:14:39 +00004257 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004258}
4259
Douglas Gregorad4b3792008-11-29 04:51:27 +00004260Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4261 // The type of __null will be int or long, depending on the size of
4262 // pointers on the target.
4263 QualType Ty;
4264 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4265 Ty = Context.IntTy;
4266 else
4267 Ty = Context.LongTy;
4268
Steve Naroff774e4152009-01-21 00:14:39 +00004269 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004270}
4271
Chris Lattner005ed752008-01-04 18:04:52 +00004272bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4273 SourceLocation Loc,
4274 QualType DstType, QualType SrcType,
4275 Expr *SrcExpr, const char *Flavor) {
4276 // Decode the result (notice that AST's are still created for extensions).
4277 bool isInvalid = false;
4278 unsigned DiagKind;
4279 switch (ConvTy) {
4280 default: assert(0 && "Unknown conversion type");
4281 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004282 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004283 DiagKind = diag::ext_typecheck_convert_pointer_int;
4284 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004285 case IntToPointer:
4286 DiagKind = diag::ext_typecheck_convert_int_pointer;
4287 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004288 case IncompatiblePointer:
4289 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4290 break;
4291 case FunctionVoidPointer:
4292 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4293 break;
4294 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004295 // If the qualifiers lost were because we were applying the
4296 // (deprecated) C++ conversion from a string literal to a char*
4297 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4298 // Ideally, this check would be performed in
4299 // CheckPointerTypesForAssignment. However, that would require a
4300 // bit of refactoring (so that the second argument is an
4301 // expression, rather than a type), which should be done as part
4302 // of a larger effort to fix CheckPointerTypesForAssignment for
4303 // C++ semantics.
4304 if (getLangOptions().CPlusPlus &&
4305 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4306 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004307 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4308 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004309 case IntToBlockPointer:
4310 DiagKind = diag::err_int_to_block_pointer;
4311 break;
4312 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004313 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004314 break;
Steve Naroff19608432008-10-14 22:18:38 +00004315 case IncompatibleObjCQualifiedId:
4316 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4317 // it can give a more specific diagnostic.
4318 DiagKind = diag::warn_incompatible_qualified_id;
4319 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004320 case Incompatible:
4321 DiagKind = diag::err_typecheck_convert_incompatible;
4322 isInvalid = true;
4323 break;
4324 }
4325
Chris Lattner271d4c22008-11-24 05:29:24 +00004326 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4327 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004328 return isInvalid;
4329}
Anders Carlssond5201b92008-11-30 19:50:32 +00004330
4331bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4332{
4333 Expr::EvalResult EvalResult;
4334
4335 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4336 EvalResult.HasSideEffects) {
4337 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4338
4339 if (EvalResult.Diag) {
4340 // We only show the note if it's not the usual "invalid subexpression"
4341 // or if it's actually in a subexpression.
4342 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4343 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4344 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4345 }
4346
4347 return true;
4348 }
4349
4350 if (EvalResult.Diag) {
4351 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4352 E->getSourceRange();
4353
4354 // Print the reason it's not a constant.
4355 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4356 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4357 }
4358
4359 if (Result)
4360 *Result = EvalResult.Val.getInt();
4361 return false;
4362}