blob: b332b557a835aeb5dbb3cbc808ba2221d9c78a95 [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!
Sebastian Redlcd883f72009-01-18 18:53:16 +0000322 return Owned(new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff0acc9c92007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
366 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor566782a2009-01-06 05:10:23 +0000370/// BuildDeclRefExpr - Build either a DeclRefExpr or a
371/// QualifiedDeclRefExpr based on whether or not SS is a
372/// nested-name-specifier.
373DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
374 bool TypeDependent, bool ValueDependent,
375 const CXXScopeSpec *SS) {
Steve Naroffe5f128a2009-01-20 19:53:53 +0000376 if (SS && !SS->isEmpty()) {
377 void *Mem = Context.getAllocator().Allocate<QualifiedDeclRefExpr>();
378 return new (Mem) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
379 ValueDependent, SS->getRange().getBegin());
380 } else {
381 void *Mem = Context.getAllocator().Allocate<DeclRefExpr>();
382 return new (Mem) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
383 }
Douglas Gregor566782a2009-01-06 05:10:23 +0000384}
385
Douglas Gregor723d3332009-01-07 00:43:41 +0000386/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
387/// variable corresponding to the anonymous union or struct whose type
388/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000389static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000390 assert(Record->isAnonymousStructOrUnion() &&
391 "Record must be an anonymous struct or union!");
392
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000393 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000394 // be an O(1) operation rather than a slow walk through DeclContext's
395 // vector (which itself will be eliminated). DeclGroups might make
396 // this even better.
397 DeclContext *Ctx = Record->getDeclContext();
398 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
399 DEnd = Ctx->decls_end();
400 D != DEnd; ++D) {
401 if (*D == Record) {
402 // The object for the anonymous struct/union directly
403 // follows its type in the list of declarations.
404 ++D;
405 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000406 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000407 return *D;
408 }
409 }
410
411 assert(false && "Missing object for anonymous record");
412 return 0;
413}
414
Sebastian Redlcd883f72009-01-18 18:53:16 +0000415Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000416Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
417 FieldDecl *Field,
418 Expr *BaseObjectExpr,
419 SourceLocation OpLoc) {
420 assert(Field->getDeclContext()->isRecord() &&
421 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
422 && "Field must be stored inside an anonymous struct or union");
423
424 // Construct the sequence of field member references
425 // we'll have to perform to get to the field in the anonymous
426 // union/struct. The list of members is built from the field
427 // outward, so traverse it backwards to go from an object in
428 // the current context to the field we found.
429 llvm::SmallVector<FieldDecl *, 4> AnonFields;
430 AnonFields.push_back(Field);
431 VarDecl *BaseObject = 0;
432 DeclContext *Ctx = Field->getDeclContext();
433 do {
434 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000435 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000436 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
437 AnonFields.push_back(AnonField);
438 else {
439 BaseObject = cast<VarDecl>(AnonObject);
440 break;
441 }
442 Ctx = Ctx->getParent();
443 } while (Ctx->isRecord() &&
444 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
445
446 // Build the expression that refers to the base object, from
447 // which we will build a sequence of member references to each
448 // of the anonymous union objects and, eventually, the field we
449 // found via name lookup.
450 bool BaseObjectIsPointer = false;
451 unsigned ExtraQuals = 0;
452 if (BaseObject) {
453 // BaseObject is an anonymous struct/union variable (and is,
454 // therefore, not part of another non-anonymous record).
455 delete BaseObjectExpr;
456
457 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
458 SourceLocation());
459 ExtraQuals
460 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
461 } else if (BaseObjectExpr) {
462 // The caller provided the base object expression. Determine
463 // whether its a pointer and whether it adds any qualifiers to the
464 // anonymous struct/union fields we're looking into.
465 QualType ObjectType = BaseObjectExpr->getType();
466 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
467 BaseObjectIsPointer = true;
468 ObjectType = ObjectPtr->getPointeeType();
469 }
470 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
471 } else {
472 // We've found a member of an anonymous struct/union that is
473 // inside a non-anonymous struct/union, so in a well-formed
474 // program our base object expression is "this".
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
476 if (!MD->isStatic()) {
477 QualType AnonFieldType
478 = Context.getTagDeclType(
479 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
480 QualType ThisType = Context.getTagDeclType(MD->getParent());
481 if ((Context.getCanonicalType(AnonFieldType)
482 == Context.getCanonicalType(ThisType)) ||
483 IsDerivedFrom(ThisType, AnonFieldType)) {
484 // Our base object expression is "this".
485 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
486 MD->getThisType(Context));
487 BaseObjectIsPointer = true;
488 }
489 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 }
500
501 // Build the implicit member references to the field of the
502 // anonymous struct/union.
503 Expr *Result = BaseObjectExpr;
504 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
505 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
506 FI != FIEnd; ++FI) {
507 QualType MemberType = (*FI)->getType();
508 if (!(*FI)->isMutable()) {
509 unsigned combinedQualifiers
510 = MemberType.getCVRQualifiers() | ExtraQuals;
511 MemberType = MemberType.getQualifiedType(combinedQualifiers);
512 }
513 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
514 OpLoc, MemberType);
515 BaseObjectIsPointer = false;
516 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517 OpLoc = SourceLocation();
518 }
519
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000521}
522
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000523/// ActOnDeclarationNameExpr - The parser has read some kind of name
524/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
525/// performs lookup on that name and returns an expression that refers
526/// to that name. This routine isn't directly called from the parser,
527/// because the parser doesn't know about DeclarationName. Rather,
528/// this routine is called by ActOnIdentifierExpr,
529/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
530/// which form the DeclarationName from the corresponding syntactic
531/// forms.
532///
533/// HasTrailingLParen indicates whether this identifier is used in a
534/// function call context. LookupCtx is only used for a C++
535/// qualified-id (foo::bar) to indicate the class or namespace that
536/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000537///
538/// If ForceResolution is true, then we will attempt to resolve the
539/// name even if it looks like a dependent name. This option is off by
540/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000541Sema::OwningExprResult
542Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
543 DeclarationName Name, bool HasTrailingLParen,
544 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000545 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
546 HasTrailingLParen && !SS && !ForceResolution) {
547 // We've seen something of the form
548 // identifier(
549 // and we are in a template, so it is likely that 's' is a
550 // dependent name. However, we won't know until we've parsed all
551 // of the call arguments. So, build a CXXDependentNameExpr node
552 // to represent this name. Then, if it turns out that none of the
553 // arguments are type-dependent, we'll force the resolution of the
554 // dependent name at that point.
Steve Naroffe5f128a2009-01-20 19:53:53 +0000555 void *Mem = Context.getAllocator().Allocate<CXXDependentNameExpr>();
556 return Owned(new (Mem) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
557 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000558 }
559
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000560 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000561 Decl *D = 0;
562 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000563 if (SS && !SS->isEmpty()) {
564 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
565 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000566 return ExprError();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000567 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000568 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000569 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
570
Sebastian Redlcd883f72009-01-18 18:53:16 +0000571 if (Lookup.isAmbiguous()) {
572 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
573 SS && SS->isSet() ? SS->getRange()
574 : SourceRange());
575 return ExprError();
576 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000577 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000578
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000579 // If this reference is in an Objective-C method, then ivar lookup happens as
580 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000581 IdentifierInfo *II = Name.getAsIdentifierInfo();
582 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000583 // There are two cases to handle here. 1) scoped lookup could have failed,
584 // in which case we should look for an ivar. 2) scoped lookup could have
585 // found a decl, but that decl is outside the current method (i.e. a global
586 // variable). In these two cases, we do a lookup for an ivar with this
587 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000588 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000589 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000590 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000591 // FIXME: This should use a new expr for a direct reference, don't turn
592 // this into Self->ivar, just return a BareIVarExpr or something.
593 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
595 ObjCIvarRefExpr *MRef = new ObjCIvarRefExpr(IV, IV->getType(), Loc,
596 static_cast<Expr*>(SelfExpr.release()),
597 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000598 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000599 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000600 }
601 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000602 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000603 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000604 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000605 getCurMethodDecl()->getClassInterface()));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000606 return Owned(new ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000607 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000608 }
Chris Lattner4b009652007-07-25 00:24:17 +0000609 if (D == 0) {
610 // Otherwise, this could be an implicitly declared function reference (legal
611 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000612 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000613 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000614 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000615 else {
616 // If this name wasn't predeclared and if this is not a function call,
617 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000618 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
620 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000621 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
622 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_use)
624 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000625 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000626 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 }
628 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000629
630 // We may have found a field within an anonymous union or struct
631 // (C++ [class.union]).
632 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
633 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
634 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635
Douglas Gregor3257fb52008-12-22 05:46:06 +0000636 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
637 if (!MD->isStatic()) {
638 // C++ [class.mfct.nonstatic]p2:
639 // [...] if name lookup (3.4.1) resolves the name in the
640 // id-expression to a nonstatic nontype member of class X or of
641 // a base class of X, the id-expression is transformed into a
642 // class member access expression (5.2.5) using (*this) (9.3.2)
643 // as the postfix-expression to the left of the '.' operator.
644 DeclContext *Ctx = 0;
645 QualType MemberType;
646 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
647 Ctx = FD->getDeclContext();
648 MemberType = FD->getType();
649
650 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
651 MemberType = RefType->getPointeeType();
652 else if (!FD->isMutable()) {
653 unsigned combinedQualifiers
654 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
655 MemberType = MemberType.getQualifiedType(combinedQualifiers);
656 }
657 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
658 if (!Method->isStatic()) {
659 Ctx = Method->getParent();
660 MemberType = Method->getType();
661 }
662 } else if (OverloadedFunctionDecl *Ovl
663 = dyn_cast<OverloadedFunctionDecl>(D)) {
664 for (OverloadedFunctionDecl::function_iterator
665 Func = Ovl->function_begin(),
666 FuncEnd = Ovl->function_end();
667 Func != FuncEnd; ++Func) {
668 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
669 if (!DMethod->isStatic()) {
670 Ctx = Ovl->getDeclContext();
671 MemberType = Context.OverloadTy;
672 break;
673 }
674 }
675 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000676
677 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000678 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
679 QualType ThisType = Context.getTagDeclType(MD->getParent());
680 if ((Context.getCanonicalType(CtxType)
681 == Context.getCanonicalType(ThisType)) ||
682 IsDerivedFrom(ThisType, CtxType)) {
683 // Build the implicit member access expression.
684 Expr *This = new CXXThisExpr(SourceLocation(),
685 MD->getThisType(Context));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000686 return Owned(new MemberExpr(This, true, cast<NamedDecl>(D),
687 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000688 }
689 }
690 }
691 }
692
Douglas Gregor8acb7272008-12-11 16:49:14 +0000693 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000694 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
695 if (MD->isStatic())
696 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000697 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
698 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000699 }
700
Douglas Gregor3257fb52008-12-22 05:46:06 +0000701 // Any other ways we could have found the field in a well-formed
702 // program would have been turned into implicit member expressions
703 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000704 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
705 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000706 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000707
Chris Lattner4b009652007-07-25 00:24:17 +0000708 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000710 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000711 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000712 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000713 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000714
Steve Naroffd6163f32008-09-05 22:11:13 +0000715 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000716 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000717 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
718 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000719
Steve Naroffd6163f32008-09-05 22:11:13 +0000720 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000721
Steve Naroffd6163f32008-09-05 22:11:13 +0000722 // check if referencing an identifier with __attribute__((deprecated)).
723 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000724 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
725
Douglas Gregor48840c72008-12-10 23:01:14 +0000726 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
727 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
728 Scope *CheckS = S;
729 while (CheckS) {
730 if (CheckS->isWithinElse() &&
731 CheckS->getControlParent()->isDeclScope(Var)) {
732 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_false)
734 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000735 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000736 ExprError(Diag(Loc, diag::warn_value_always_zero)
737 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000738 break;
739 }
740
741 // Move up one more control parent to check again.
742 CheckS = CheckS->getControlParent();
743 if (CheckS)
744 CheckS = CheckS->getParent();
745 }
746 }
747 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000748
749 // Only create DeclRefExpr's for valid Decl's.
750 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000751 return ExprError();
752
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000753 // If the identifier reference is inside a block, and it refers to a value
754 // that is outside the block, create a BlockDeclRefExpr instead of a
755 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
756 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000757 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000758 // We do not do this for things like enum constants, global variables, etc,
759 // as they do not get snapshotted.
760 //
761 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000762 // The BlocksAttr indicates the variable is bound by-reference.
Steve Naroffe5f128a2009-01-20 19:53:53 +0000763 void *Mem = Context.getAllocator().Allocate<BlockDeclRefExpr>();
Steve Naroff52059382008-10-10 01:28:17 +0000764 if (VD->getAttr<BlocksAttr>())
Steve Naroffe5f128a2009-01-20 19:53:53 +0000765 return Owned(new (Mem) BlockDeclRefExpr(VD,
766 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000767
Steve Naroff52059382008-10-10 01:28:17 +0000768 // Variable will be bound by-copy, make it const within the closure.
769 VD->getType().addConst();
Steve Naroffe5f128a2009-01-20 19:53:53 +0000770 return Owned(new (Mem) BlockDeclRefExpr(VD,
771 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000772 }
773 // If this reference is not in a block or if the referenced variable is
774 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000775
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000776 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000777 bool ValueDependent = false;
778 if (getLangOptions().CPlusPlus) {
779 // C++ [temp.dep.expr]p3:
780 // An id-expression is type-dependent if it contains:
781 // - an identifier that was declared with a dependent type,
782 if (VD->getType()->isDependentType())
783 TypeDependent = true;
784 // - FIXME: a template-id that is dependent,
785 // - a conversion-function-id that specifies a dependent type,
786 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
787 Name.getCXXNameType()->isDependentType())
788 TypeDependent = true;
789 // - a nested-name-specifier that contains a class-name that
790 // names a dependent type.
791 else if (SS && !SS->isEmpty()) {
792 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
793 DC; DC = DC->getParent()) {
794 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000795 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000796 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
797 if (Context.getTypeDeclType(Record)->isDependentType()) {
798 TypeDependent = true;
799 break;
800 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000801 }
802 }
803 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000804
Douglas Gregora5d84612008-12-10 20:57:37 +0000805 // C++ [temp.dep.constexpr]p2:
806 //
807 // An identifier is value-dependent if it is:
808 // - a name declared with a dependent type,
809 if (TypeDependent)
810 ValueDependent = true;
811 // - the name of a non-type template parameter,
812 else if (isa<NonTypeTemplateParmDecl>(VD))
813 ValueDependent = true;
814 // - a constant with integral or enumeration type and is
815 // initialized with an expression that is value-dependent
816 // (FIXME!).
817 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000818
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
820 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000821}
822
Sebastian Redlcd883f72009-01-18 18:53:16 +0000823Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
824 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000825 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000826
Chris Lattner4b009652007-07-25 00:24:17 +0000827 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000828 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000829 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
830 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
831 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000832 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000833
Chris Lattner7e637512008-01-12 08:14:25 +0000834 // Pre-defined identifiers are of type char[x], where x is the length of the
835 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000836 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000837 if (FunctionDecl *FD = getCurFunctionDecl())
838 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000839 else if (ObjCMethodDecl *MD = getCurMethodDecl())
840 Length = MD->getSynthesizedMethodSize();
841 else {
842 Diag(Loc, diag::ext_predef_outside_function);
843 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
844 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
845 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000846
847
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000848 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000849 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000850 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000851 return Owned(new PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000852}
853
Sebastian Redlcd883f72009-01-18 18:53:16 +0000854Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000855 llvm::SmallString<16> CharBuffer;
856 CharBuffer.resize(Tok.getLength());
857 const char *ThisTokBegin = &CharBuffer[0];
858 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000859
Chris Lattner4b009652007-07-25 00:24:17 +0000860 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
861 Tok.getLocation(), PP);
862 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000863 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000864
865 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
866
Sebastian Redl75324932009-01-20 22:23:13 +0000867 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
868 Literal.isWide(),
869 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000870}
871
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
873 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000874 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
875 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000876 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
877 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroffe5f128a2009-01-20 19:53:53 +0000878 void *Mem = Context.getAllocator().Allocate<IntegerLiteral>();
879 return Owned(new (Mem) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
880 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000881 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000882
Chris Lattner4b009652007-07-25 00:24:17 +0000883 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000884 // Add padding so that NumericLiteralParser can overread by one character.
885 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000886 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000887
Chris Lattner4b009652007-07-25 00:24:17 +0000888 // Get the spelling of the token, which eliminates trigraphs, etc.
889 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000890
Chris Lattner4b009652007-07-25 00:24:17 +0000891 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
892 Tok.getLocation(), PP);
893 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000894 return ExprError();
895
Chris Lattner1de66eb2007-08-26 03:42:43 +0000896 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000897
Chris Lattner1de66eb2007-08-26 03:42:43 +0000898 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000899 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000900 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000901 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000902 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000903 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000904 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000905 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000906
907 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
908
Ted Kremenekddedbe22007-11-29 00:56:49 +0000909 // isExact will be set by GetFloatValue().
910 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000911 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
912 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000913
Chris Lattner1de66eb2007-08-26 03:42:43 +0000914 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000915 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000916 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000917 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000918
Neil Booth7421e9c2007-08-29 22:00:19 +0000919 // long long is a C99 feature.
920 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000921 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000922 Diag(Tok.getLocation(), diag::ext_longlong);
923
Chris Lattner4b009652007-07-25 00:24:17 +0000924 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000925 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000926
Chris Lattner4b009652007-07-25 00:24:17 +0000927 if (Literal.GetIntegerValue(ResultVal)) {
928 // If this value didn't fit into uintmax_t, warn and force to ull.
929 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000930 Ty = Context.UnsignedLongLongTy;
931 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000932 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000933 } else {
934 // If this value fits into a ULL, try to figure out what else it fits into
935 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000936
Chris Lattner4b009652007-07-25 00:24:17 +0000937 // Octal, Hexadecimal, and integers with a U suffix are allowed to
938 // be an unsigned int.
939 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
940
941 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000942 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000943 if (!Literal.isLong && !Literal.isLongLong) {
944 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000945 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000946
Chris Lattner4b009652007-07-25 00:24:17 +0000947 // Does it fit in a unsigned int?
948 if (ResultVal.isIntN(IntSize)) {
949 // Does it fit in a signed int?
950 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000951 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000952 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000953 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000954 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
Chris Lattner4b009652007-07-25 00:24:17 +0000956 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000957
Chris Lattner4b009652007-07-25 00:24:17 +0000958 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000959 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000960 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000961
Chris Lattner4b009652007-07-25 00:24:17 +0000962 // Does it fit in a unsigned long?
963 if (ResultVal.isIntN(LongSize)) {
964 // Does it fit in a signed long?
965 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000966 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000967 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000968 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000969 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000970 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971 }
972
Chris Lattner4b009652007-07-25 00:24:17 +0000973 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000974 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000975 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976
Chris Lattner4b009652007-07-25 00:24:17 +0000977 // Does it fit in a unsigned long long?
978 if (ResultVal.isIntN(LongLongSize)) {
979 // Does it fit in a signed long long?
980 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000981 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000982 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000983 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000984 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
986 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000987
Chris Lattner4b009652007-07-25 00:24:17 +0000988 // If we still couldn't decide a type, we probably have something that
989 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000990 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000991 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000992 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000993 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000995
Chris Lattnere4068872008-05-09 05:59:00 +0000996 if (ResultVal.getBitWidth() != Width)
997 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000998 }
Sebastian Redl75324932009-01-20 22:23:13 +0000999 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001
Chris Lattner1de66eb2007-08-26 03:42:43 +00001002 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1003 if (Literal.isImaginary)
1004 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001005
1006 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001007}
1008
Sebastian Redlcd883f72009-01-18 18:53:16 +00001009Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1010 SourceLocation R, ExprArg Val) {
1011 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001012 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroffe5f128a2009-01-20 19:53:53 +00001013 void *Mem = Context.getAllocator().Allocate<ParenExpr>();
1014 return Owned(new (Mem) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001015}
1016
1017/// The UsualUnaryConversions() function is *not* called by this routine.
1018/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001019bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1020 SourceLocation OpLoc,
1021 const SourceRange &ExprRange,
1022 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001023 // C99 6.5.3.4p1:
1024 if (isa<FunctionType>(exprType) && isSizeof)
1025 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001026 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001028 Diag(OpLoc, diag::ext_sizeof_void_type)
1029 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001030 else
1031 return DiagnoseIncompleteType(OpLoc, exprType,
1032 isSizeof ? diag::err_sizeof_incomplete_type :
1033 diag::err_alignof_incomplete_type,
1034 ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001035
1036 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001037}
1038
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001039/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1040/// the same for @c alignof and @c __alignof
1041/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001042Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001043Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1044 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001046 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001047
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001048 QualType ArgTy;
1049 SourceRange Range;
1050 if (isType) {
1051 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1052 Range = ArgRange;
1053 } else {
1054 // Get the end location.
1055 Expr *ArgEx = (Expr *)TyOrEx;
1056 Range = ArgEx->getSourceRange();
1057 ArgTy = ArgEx->getType();
1058 }
1059
1060 // Verify that the operand is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00001061 // FIXME: This might leak the expression.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001062 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Sebastian Redl8b769972009-01-19 00:08:26 +00001063 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001064
1065 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroffe5f128a2009-01-20 19:53:53 +00001066 void *Mem = Context.getAllocator().Allocate<SizeOfAlignOfExpr>();
1067 return Owned(new (Mem) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Sebastian Redl8b769972009-01-19 00:08:26 +00001068 Context.getSizeType(), OpLoc,
1069 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001070}
1071
Chris Lattner5110ad52007-08-24 21:41:10 +00001072QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001073 DefaultFunctionArrayConversion(V);
1074
Chris Lattnera16e42d2007-08-26 05:39:26 +00001075 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001076 if (const ComplexType *CT = V->getType()->getAsComplexType())
1077 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001078
1079 // Otherwise they pass through real integer and floating point types here.
1080 if (V->getType()->isArithmeticType())
1081 return V->getType();
1082
1083 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001084 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001085 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001086}
1087
1088
Chris Lattner4b009652007-07-25 00:24:17 +00001089
Sebastian Redl8b769972009-01-19 00:08:26 +00001090Action::OwningExprResult
1091Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1092 tok::TokenKind Kind, ExprArg Input) {
1093 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001094
Chris Lattner4b009652007-07-25 00:24:17 +00001095 UnaryOperator::Opcode Opc;
1096 switch (Kind) {
1097 default: assert(0 && "Unknown unary op!");
1098 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1099 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1100 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001101
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001102 if (getLangOptions().CPlusPlus &&
1103 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1104 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001105 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001106 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1107
1108 // C++ [over.inc]p1:
1109 //
1110 // [...] If the function is a member function with one
1111 // parameter (which shall be of type int) or a non-member
1112 // function with two parameters (the second of which shall be
1113 // of type int), it defines the postfix increment operator ++
1114 // for objects of that type. When the postfix increment is
1115 // called as a result of using the ++ operator, the int
1116 // argument will have value zero.
1117 Expr *Args[2] = {
1118 Arg,
1119 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1120 /*isSigned=*/true),
1121 Context.IntTy, SourceLocation())
1122 };
1123
1124 // Build the candidate set for overloading
1125 OverloadCandidateSet CandidateSet;
1126 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1127
1128 // Perform overload resolution.
1129 OverloadCandidateSet::iterator Best;
1130 switch (BestViableFunction(CandidateSet, Best)) {
1131 case OR_Success: {
1132 // We found a built-in operator or an overloaded operator.
1133 FunctionDecl *FnDecl = Best->Function;
1134
1135 if (FnDecl) {
1136 // We matched an overloaded operator. Build a call to that
1137 // operator.
1138
1139 // Convert the arguments.
1140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1141 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001142 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001143 } else {
1144 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001145 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001146 FnDecl->getParamDecl(0)->getType(),
1147 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001148 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001149 }
1150
1151 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001152 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001153 = FnDecl->getType()->getAsFunctionType()->getResultType();
1154 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001155
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001156 // Build the actual expression node.
Steve Naroffe5f128a2009-01-20 19:53:53 +00001157 void *Mem = Context.getAllocator().Allocate<DeclRefExpr>();
1158 Expr *FnExpr = new (Mem) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001159 SourceLocation());
1160 UsualUnaryConversions(FnExpr);
1161
Sebastian Redl8b769972009-01-19 00:08:26 +00001162 Input.release();
Steve Naroffe5f128a2009-01-20 19:53:53 +00001163 Mem = Context.getAllocator().Allocate<CXXOperatorCallExpr>();
1164 return Owned(new (Mem) CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
1165 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001166 } else {
1167 // We matched a built-in operator. Convert the arguments, then
1168 // break out so that we will build the appropriate built-in
1169 // operator node.
1170 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1171 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001172 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001173
1174 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001175 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001176 }
1177
1178 case OR_No_Viable_Function:
1179 // No viable function; fall through to handling this as a
1180 // built-in operator, which will produce an error message for us.
1181 break;
1182
1183 case OR_Ambiguous:
1184 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1185 << UnaryOperator::getOpcodeStr(Opc)
1186 << Arg->getSourceRange();
1187 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001188 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001189 }
1190
1191 // Either we found no viable overloaded operator or we matched a
1192 // built-in operator. In either case, fall through to trying to
1193 // build a built-in operation.
1194 }
1195
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001196 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1197 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001198 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001199 return ExprError();
1200 Input.release();
1201 return Owned(new UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001202}
1203
Sebastian Redl8b769972009-01-19 00:08:26 +00001204Action::OwningExprResult
1205Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1206 ExprArg Idx, SourceLocation RLoc) {
1207 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1208 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001209
Douglas Gregor80723c52008-11-19 17:17:41 +00001210 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001211 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001212 LHSExp->getType()->isEnumeralType() ||
1213 RHSExp->getType()->isRecordType() ||
1214 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001215 // Add the appropriate overloaded operators (C++ [over.match.oper])
1216 // to the candidate set.
1217 OverloadCandidateSet CandidateSet;
1218 Expr *Args[2] = { LHSExp, RHSExp };
1219 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001220
Douglas Gregor80723c52008-11-19 17:17:41 +00001221 // Perform overload resolution.
1222 OverloadCandidateSet::iterator Best;
1223 switch (BestViableFunction(CandidateSet, Best)) {
1224 case OR_Success: {
1225 // We found a built-in operator or an overloaded operator.
1226 FunctionDecl *FnDecl = Best->Function;
1227
1228 if (FnDecl) {
1229 // We matched an overloaded operator. Build a call to that
1230 // operator.
1231
1232 // Convert the arguments.
1233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1234 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1235 PerformCopyInitialization(RHSExp,
1236 FnDecl->getParamDecl(0)->getType(),
1237 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001238 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001239 } else {
1240 // Convert the arguments.
1241 if (PerformCopyInitialization(LHSExp,
1242 FnDecl->getParamDecl(0)->getType(),
1243 "passing") ||
1244 PerformCopyInitialization(RHSExp,
1245 FnDecl->getParamDecl(1)->getType(),
1246 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001247 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001248 }
1249
1250 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001251 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001252 = FnDecl->getType()->getAsFunctionType()->getResultType();
1253 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001254
Douglas Gregor80723c52008-11-19 17:17:41 +00001255 // Build the actual expression node.
1256 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1257 SourceLocation());
1258 UsualUnaryConversions(FnExpr);
1259
Sebastian Redl8b769972009-01-19 00:08:26 +00001260 Base.release();
1261 Idx.release();
1262 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001263 } else {
1264 // We matched a built-in operator. Convert the arguments, then
1265 // break out so that we will build the appropriate built-in
1266 // operator node.
1267 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1268 "passing") ||
1269 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1270 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001271 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001272
1273 break;
1274 }
1275 }
1276
1277 case OR_No_Viable_Function:
1278 // No viable function; fall through to handling this as a
1279 // built-in operator, which will produce an error message for us.
1280 break;
1281
1282 case OR_Ambiguous:
1283 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1284 << "[]"
1285 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1286 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001287 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001288 }
1289
1290 // Either we found no viable overloaded operator or we matched a
1291 // built-in operator. In either case, fall through to trying to
1292 // build a built-in operation.
1293 }
1294
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // Perform default conversions.
1296 DefaultFunctionArrayConversion(LHSExp);
1297 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001298
Chris Lattner4b009652007-07-25 00:24:17 +00001299 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1300
1301 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001302 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001303 // in the subscript position. As a result, we need to derive the array base
1304 // and index from the expression types.
1305 Expr *BaseExpr, *IndexExpr;
1306 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001307 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001308 BaseExpr = LHSExp;
1309 IndexExpr = RHSExp;
1310 // FIXME: need to deal with const...
1311 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001312 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001313 // Handle the uncommon case of "123[Ptr]".
1314 BaseExpr = RHSExp;
1315 IndexExpr = LHSExp;
1316 // FIXME: need to deal with const...
1317 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001318 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1319 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001320 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001321
Chris Lattner4b009652007-07-25 00:24:17 +00001322 // FIXME: need to deal with const...
1323 ResultType = VTy->getElementType();
1324 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001325 return ExprError(Diag(LHSExp->getLocStart(),
1326 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1327 }
Chris Lattner4b009652007-07-25 00:24:17 +00001328 // C99 6.5.2.1p1
1329 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001330 return ExprError(Diag(IndexExpr->getLocStart(),
1331 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001332
1333 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1334 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001335 // void (*)(int)) and pointers to incomplete types. Functions are not
1336 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001337 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001338 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001339 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001340 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001341
Sebastian Redl8b769972009-01-19 00:08:26 +00001342 Base.release();
1343 Idx.release();
1344 return Owned(new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001345}
1346
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001347QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001348CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001349 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001350 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001351
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001352 // The vector accessor can't exceed the number of elements.
1353 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001354
1355 // This flag determines whether or not the component is one of the four
1356 // special names that indicate a subset of exactly half the elements are
1357 // to be selected.
1358 bool HalvingSwizzle = false;
1359
1360 // This flag determines whether or not CompName has an 's' char prefix,
1361 // indicating that it is a string of hex values to be used as vector indices.
1362 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001363
1364 // Check that we've found one of the special components, or that the component
1365 // names must come from the same set.
1366 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001367 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1368 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001369 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001370 do
1371 compStr++;
1372 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001373 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001374 do
1375 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001376 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001377 }
Nate Begeman1486b502009-01-18 01:47:54 +00001378
1379 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001380 // We didn't get to the end of the string. This means the component names
1381 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001382 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1383 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001384 return QualType();
1385 }
Nate Begeman1486b502009-01-18 01:47:54 +00001386
1387 // Ensure no component accessor exceeds the width of the vector type it
1388 // operates on.
1389 if (!HalvingSwizzle) {
1390 compStr = CompName.getName();
1391
1392 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001393 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001394
1395 while (*compStr) {
1396 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1397 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1398 << baseType << SourceRange(CompLoc);
1399 return QualType();
1400 }
1401 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001402 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001403
Nate Begeman1486b502009-01-18 01:47:54 +00001404 // If this is a halving swizzle, verify that the base type has an even
1405 // number of elements.
1406 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001407 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001408 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001409 return QualType();
1410 }
1411
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001412 // The component accessor looks fine - now we need to compute the actual type.
1413 // The vector type is implied by the component accessor. For example,
1414 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001415 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001416 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001417 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1418 : CompName.getLength();
1419 if (HexSwizzle)
1420 CompSize--;
1421
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001422 if (CompSize == 1)
1423 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001424
Nate Begemanaf6ed502008-04-18 23:10:10 +00001425 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001426 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001427 // diagostics look bad. We want extended vector types to appear built-in.
1428 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1429 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1430 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001431 }
1432 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001433}
1434
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001435/// constructSetterName - Return the setter name for the given
1436/// identifier, i.e. "set" + Name where the initial character of Name
1437/// has been capitalized.
1438// FIXME: Merge with same routine in Parser. But where should this
1439// live?
1440static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1441 const IdentifierInfo *Name) {
1442 llvm::SmallString<100> SelectorName;
1443 SelectorName = "set";
1444 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1445 SelectorName[3] = toupper(SelectorName[3]);
1446 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1447}
1448
Sebastian Redl8b769972009-01-19 00:08:26 +00001449Action::OwningExprResult
1450Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1451 tok::TokenKind OpKind, SourceLocation MemberLoc,
1452 IdentifierInfo &Member) {
1453 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001454 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001455
1456 // Perform default conversions.
1457 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001458
Steve Naroff2cb66382007-07-26 03:11:44 +00001459 QualType BaseType = BaseExpr->getType();
1460 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001461
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001462 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1463 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001464 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001465 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001466 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001467 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001468 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1469 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001470 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001471 return ExprError(Diag(MemberLoc,
1472 diag::err_typecheck_member_reference_arrow)
1473 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001474 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001475
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001476 // Handle field access to simple records. This also handles access to fields
1477 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001478 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001479 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001480 if (DiagnoseIncompleteType(OpLoc, BaseType,
1481 diag::err_typecheck_incomplete_tag,
1482 BaseExpr->getSourceRange()))
1483 return ExprError();
1484
Steve Naroff2cb66382007-07-26 03:11:44 +00001485 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001486 // FIXME: Qualified name lookup for C++ is a bit more complicated
1487 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001488 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001489 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1490 LookupCriteria(LookupCriteria::Member,
1491 /*RedeclarationOnly=*/false,
1492 getLangOptions().CPlusPlus));
1493
1494 Decl *MemberDecl = 0;
1495 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001496 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1497 << &Member << BaseExpr->getSourceRange());
1498 else if (Result.isAmbiguous()) {
1499 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1500 MemberLoc, BaseExpr->getSourceRange());
1501 return ExprError();
1502 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001503 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001504
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001505 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001506 // We may have found a field within an anonymous union or struct
1507 // (C++ [class.union]).
1508 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001509 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001510 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001511
Douglas Gregor82d44772008-12-20 23:49:58 +00001512 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1513 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001514 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001515 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1516 MemberType = Ref->getPointeeType();
1517 else {
1518 unsigned combinedQualifiers =
1519 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001520 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001521 combinedQualifiers &= ~QualType::Const;
1522 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1523 }
Eli Friedman76b49832008-02-06 22:48:16 +00001524
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1526 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001527 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001528 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow,
1529 Var, MemberLoc,
1530 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001531 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001532 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn,
1533 MemberLoc, MemberFn->getType()));
1534 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001535 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001536 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1537 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001538 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
1540 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001541 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1543 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001544
Douglas Gregor82d44772008-12-20 23:49:58 +00001545 // We found a declaration kind that we didn't expect. This is a
1546 // generic error message that tells the user that she can't refer
1547 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError(Diag(MemberLoc,
1549 diag::err_typecheck_member_reference_unknown)
1550 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001551 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001552
Chris Lattnere9d71612008-07-21 04:59:05 +00001553 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1554 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001555 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001556 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001557 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1558 BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001559 OpKind == tok::arrow);
1560 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001562 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001563 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1564 << IFTy->getDecl()->getDeclName() << &Member
1565 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001566 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001567
Chris Lattnere9d71612008-07-21 04:59:05 +00001568 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1569 // pointer to a (potentially qualified) interface type.
1570 const PointerType *PTy;
1571 const ObjCInterfaceType *IFTy;
1572 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1573 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1574 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001575
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001576 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001577 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001578 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1579 MemberLoc, BaseExpr));
1580
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001581 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001582 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1583 E = IFTy->qual_end(); I != E; ++I)
1584 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001585 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1586 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001587
1588 // If that failed, look for an "implicit" property by seeing if the nullary
1589 // selector is implemented.
1590
1591 // FIXME: The logic for looking up nullary and unary selectors should be
1592 // shared with the code in ActOnInstanceMessage.
1593
1594 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1595 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001596
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001597 // If this reference is in an @implementation, check for 'private' methods.
1598 if (!Getter)
1599 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1600 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1601 if (ObjCImplementationDecl *ImpDecl =
1602 ObjCImplementations[ClassDecl->getIdentifier()])
1603 Getter = ImpDecl->getInstanceMethod(Sel);
1604
Steve Naroff04151f32008-10-22 19:16:27 +00001605 // Look through local category implementations associated with the class.
1606 if (!Getter) {
1607 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1608 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1609 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1610 }
1611 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001612 if (Getter) {
1613 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001614 // will look for the matching setter, in case it is needed.
1615 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1616 &Member);
1617 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1618 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1619 if (!Setter) {
1620 // If this reference is in an @implementation, also check for 'private'
1621 // methods.
1622 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1623 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1624 if (ObjCImplementationDecl *ImpDecl =
1625 ObjCImplementations[ClassDecl->getIdentifier()])
1626 Setter = ImpDecl->getInstanceMethod(SetterSel);
1627 }
1628 // Look through local category implementations associated with the class.
1629 if (!Setter) {
1630 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1631 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1632 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1633 }
1634 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001635
1636 // FIXME: we must check that the setter has property type.
1637 return Owned(new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
1638 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001639 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001640
1641 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1642 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001643 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001644 // Handle properties on qualified "id" protocols.
1645 const ObjCQualifiedIdType *QIdTy;
1646 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1647 // Check protocols on qualified interfaces.
1648 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001649 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001650 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001651 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1652 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001653 // Also must look for a getter name which uses property syntax.
1654 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1655 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 return Owned(new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(),
1657 OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001658 }
1659 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001660
1661 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1662 << &Member << BaseType);
1663 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001664 // Handle 'field access' to vectors, such as 'V.xx'.
1665 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001666 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1667 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 return ExprError();
1669 return Owned(new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001670 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001671
1672 return ExprError(Diag(MemberLoc,
1673 diag::err_typecheck_member_reference_struct_union)
1674 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001675}
1676
Douglas Gregor3257fb52008-12-22 05:46:06 +00001677/// ConvertArgumentsForCall - Converts the arguments specified in
1678/// Args/NumArgs to the parameter types of the function FDecl with
1679/// function prototype Proto. Call is the call expression itself, and
1680/// Fn is the function expression. For a C++ member function, this
1681/// routine does not attempt to convert the object argument. Returns
1682/// true if the call is ill-formed.
1683bool
1684Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1685 FunctionDecl *FDecl,
1686 const FunctionTypeProto *Proto,
1687 Expr **Args, unsigned NumArgs,
1688 SourceLocation RParenLoc) {
1689 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1690 // assignment, to the types of the corresponding parameter, ...
1691 unsigned NumArgsInProto = Proto->getNumArgs();
1692 unsigned NumArgsToCheck = NumArgs;
1693
1694 // If too few arguments are available (and we don't have default
1695 // arguments for the remaining parameters), don't make the call.
1696 if (NumArgs < NumArgsInProto) {
1697 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1698 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1699 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1700 // Use default arguments for missing arguments
1701 NumArgsToCheck = NumArgsInProto;
1702 Call->setNumArgs(NumArgsInProto);
1703 }
1704
1705 // If too many are passed and not variadic, error on the extras and drop
1706 // them.
1707 if (NumArgs > NumArgsInProto) {
1708 if (!Proto->isVariadic()) {
1709 Diag(Args[NumArgsInProto]->getLocStart(),
1710 diag::err_typecheck_call_too_many_args)
1711 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1712 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1713 Args[NumArgs-1]->getLocEnd());
1714 // This deletes the extra arguments.
1715 Call->setNumArgs(NumArgsInProto);
1716 }
1717 NumArgsToCheck = NumArgsInProto;
1718 }
1719
1720 // Continue to check argument types (even if we have too few/many args).
1721 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1722 QualType ProtoArgType = Proto->getArgType(i);
1723
1724 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001725 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001726 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001727
1728 // Pass the argument.
1729 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1730 return true;
1731 } else
1732 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001733 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1734 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001735
Douglas Gregor3257fb52008-12-22 05:46:06 +00001736 Call->setArg(i, Arg);
1737 }
1738
1739 // If this is a variadic call, handle args passed through "...".
1740 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001741 VariadicCallType CallType = VariadicFunction;
1742 if (Fn->getType()->isBlockPointerType())
1743 CallType = VariadicBlock; // Block
1744 else if (isa<MemberExpr>(Fn))
1745 CallType = VariadicMethod;
1746
Douglas Gregor3257fb52008-12-22 05:46:06 +00001747 // Promote the arguments (C99 6.5.2.2p7).
1748 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1749 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001750 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001751 Call->setArg(i, Arg);
1752 }
1753 }
1754
1755 return false;
1756}
1757
Steve Naroff87d58b42007-09-16 03:34:24 +00001758/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001759/// This provides the location of the left/right parens and a list of comma
1760/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001761Action::OwningExprResult
1762Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1763 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001764 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001765 unsigned NumArgs = args.size();
1766 Expr *Fn = static_cast<Expr *>(fn.release());
1767 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001768 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001769 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001770 OverloadedFunctionDecl *Ovl = NULL;
1771
Douglas Gregora133e262008-12-06 00:22:45 +00001772 // Determine whether this is a dependent call inside a C++ template,
1773 // in which case we won't do any semantic analysis now.
1774 bool Dependent = false;
1775 if (Fn->isTypeDependent()) {
1776 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1777 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1778 Dependent = true;
1779 else {
1780 // Resolve the CXXDependentNameExpr to an actual identifier;
1781 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001782 OwningExprResult Resolved
1783 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1784 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001785 /*HasTrailingLParen=*/true,
1786 /*SS=*/0,
1787 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001788 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001789 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001790 else {
1791 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001792 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001793 }
1794 }
1795 } else
1796 Dependent = true;
1797 } else
1798 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1799
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001800 // FIXME: Will need to cache the results of name lookup (including
1801 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001802 if (Dependent)
Sebastian Redl8b769972009-01-19 00:08:26 +00001803 return Owned(new CallExpr(Fn, Args, NumArgs,
1804 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001805
Douglas Gregor3257fb52008-12-22 05:46:06 +00001806 // Determine whether this is a call to an object (C++ [over.call.object]).
1807 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001808 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1809 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001810
1811 // Determine whether this is a call to a member function.
1812 if (getLangOptions().CPlusPlus) {
1813 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1814 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1815 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001816 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1817 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001818 }
1819
Douglas Gregord2baafd2008-10-21 16:13:35 +00001820 // If we're directly calling a function or a set of overloaded
1821 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001822 DeclRefExpr *DRExpr = NULL;
1823 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1824 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1825 else
1826 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001827
Douglas Gregor566782a2009-01-06 05:10:23 +00001828 if (DRExpr) {
1829 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1830 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001831 }
1832
Douglas Gregord2baafd2008-10-21 16:13:35 +00001833 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001834 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1835 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001836 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001837 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001838
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001839 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001840 Expr *NewFn = 0;
1841 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1842 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1843 QDRExpr->getLocation(), false, false,
1844 QDRExpr->getSourceRange().getBegin());
1845 else
1846 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1847 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001848 Fn->Destroy(Context);
1849 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001850 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001851
1852 // Promote the function operand.
1853 UsualUnaryConversions(Fn);
1854
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001855 // Make the call expr early, before semantic checks. This guarantees cleanup
1856 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001857 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1858 // Destroy(), or nothing gets cleaned up.
Chris Lattner97316c02008-04-10 02:22:51 +00001859 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001860 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001861
Steve Naroffd6163f32008-09-05 22:11:13 +00001862 const FunctionType *FuncT;
1863 if (!Fn->getType()->isBlockPointerType()) {
1864 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1865 // have type pointer to function".
1866 const PointerType *PT = Fn->getType()->getAsPointerType();
1867 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001868 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1869 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001870 FuncT = PT->getPointeeType()->getAsFunctionType();
1871 } else { // This is a block call.
1872 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1873 getAsFunctionType();
1874 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001875 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001876 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1877 << Fn->getType() << Fn->getSourceRange());
1878
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001879 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001880 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001881
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001882 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1884 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001885 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001886 } else {
1887 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001888
Steve Naroffdb65e052007-08-28 23:30:39 +00001889 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001890 for (unsigned i = 0; i != NumArgs; i++) {
1891 Expr *Arg = Args[i];
1892 DefaultArgumentPromotion(Arg);
1893 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001894 }
Chris Lattner4b009652007-07-25 00:24:17 +00001895 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001896
Douglas Gregor3257fb52008-12-22 05:46:06 +00001897 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1898 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001899 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1900 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001901
Chris Lattner2e64c072007-08-10 20:18:51 +00001902 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001903 if (FDecl)
1904 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001905
Sebastian Redl8b769972009-01-19 00:08:26 +00001906 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001907}
1908
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001909Action::OwningExprResult
1910Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1911 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001912 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001913 QualType literalType = QualType::getFromOpaquePtr(Ty);
1914 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001915 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001916 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001917
Eli Friedman8c2173d2008-05-20 05:22:08 +00001918 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001919 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001920 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1921 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001922 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1923 diag::err_typecheck_decl_incomplete_type,
1924 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001925 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001926
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001927 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001928 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001929 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001930
Chris Lattnere5cb5862008-12-04 23:50:19 +00001931 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001932 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001933 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001934 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001935 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001936 InitExpr.release();
1937 return Owned(new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1938 isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001939}
1940
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001941Action::OwningExprResult
1942Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1943 InitListDesignations &Designators,
1944 SourceLocation RBraceLoc) {
1945 unsigned NumInit = initlist.size();
1946 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001947
Steve Naroff0acc9c92007-09-15 18:49:24 +00001948 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001949 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001950
Chris Lattner71ca8c82008-10-26 23:43:26 +00001951 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1952 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001953 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001954 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001955}
1956
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001957/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001958bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001959 UsualUnaryConversions(castExpr);
1960
1961 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1962 // type needs to be scalar.
1963 if (castType->isVoidType()) {
1964 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001965 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1966 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001967 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001968 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1969 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1970 (castType->isStructureType() || castType->isUnionType())) {
1971 // GCC struct/union extension: allow cast to self.
1972 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1973 << castType << castExpr->getSourceRange();
1974 } else if (castType->isUnionType()) {
1975 // GCC cast to union extension
1976 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1977 RecordDecl::field_iterator Field, FieldEnd;
1978 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1979 Field != FieldEnd; ++Field) {
1980 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1981 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1982 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1983 << castExpr->getSourceRange();
1984 break;
1985 }
1986 }
1987 if (Field == FieldEnd)
1988 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1989 << castExpr->getType() << castExpr->getSourceRange();
1990 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001991 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001992 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001993 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001994 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001995 } else if (!castExpr->getType()->isScalarType() &&
1996 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001997 return Diag(castExpr->getLocStart(),
1998 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001999 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002000 } else if (castExpr->getType()->isVectorType()) {
2001 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2002 return true;
2003 } else if (castType->isVectorType()) {
2004 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2005 return true;
2006 }
2007 return false;
2008}
2009
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002010bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002011 assert(VectorTy->isVectorType() && "Not a vector type!");
2012
2013 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002014 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002015 return Diag(R.getBegin(),
2016 Ty->isVectorType() ?
2017 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002018 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002019 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002020 } else
2021 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002022 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002023 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002024
2025 return false;
2026}
2027
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002028Action::OwningExprResult
2029Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2030 SourceLocation RParenLoc, ExprArg Op) {
2031 assert((Ty != 0) && (Op.get() != 0) &&
2032 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002033
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002034 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002035 QualType castType = QualType::getFromOpaquePtr(Ty);
2036
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002037 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002038 return ExprError();
2039 return Owned(new CStyleCastExpr(castType, castExpr, castType,
2040 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002041}
2042
Chris Lattner98a425c2007-11-26 01:40:58 +00002043/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2044/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002045inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2046 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2047 UsualUnaryConversions(cond);
2048 UsualUnaryConversions(lex);
2049 UsualUnaryConversions(rex);
2050 QualType condT = cond->getType();
2051 QualType lexT = lex->getType();
2052 QualType rexT = rex->getType();
2053
2054 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002055 if (!cond->isTypeDependent()) {
2056 if (!condT->isScalarType()) { // C99 6.5.15p2
2057 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2058 return QualType();
2059 }
Chris Lattner4b009652007-07-25 00:24:17 +00002060 }
Chris Lattner992ae932008-01-06 22:42:25 +00002061
2062 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002063 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2064 return Context.DependentTy;
2065
Chris Lattner992ae932008-01-06 22:42:25 +00002066 // If both operands have arithmetic type, do the usual arithmetic conversions
2067 // to find a common type: C99 6.5.15p3,5.
2068 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002069 UsualArithmeticConversions(lex, rex);
2070 return lex->getType();
2071 }
Chris Lattner992ae932008-01-06 22:42:25 +00002072
2073 // If both operands are the same structure or union type, the result is that
2074 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002075 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002076 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002077 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002078 // "If both the operands have structure or union type, the result has
2079 // that type." This implies that CV qualifiers are dropped.
2080 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002081 }
Chris Lattner992ae932008-01-06 22:42:25 +00002082
2083 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002084 // The following || allows only one side to be void (a GCC-ism).
2085 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002086 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002087 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2088 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002089 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002090 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2091 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002092 ImpCastExprToType(lex, Context.VoidTy);
2093 ImpCastExprToType(rex, Context.VoidTy);
2094 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002095 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002096 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2097 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002098 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2099 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002100 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002101 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002102 return lexT;
2103 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002104 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2105 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002106 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002107 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002108 return rexT;
2109 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002110 // Handle the case where both operands are pointers before we handle null
2111 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002112 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2113 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2114 // get the "pointed to" types
2115 QualType lhptee = LHSPT->getPointeeType();
2116 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002117
Chris Lattner71225142007-07-31 21:27:01 +00002118 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2119 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002120 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002121 // Figure out necessary qualifiers (C99 6.5.15p6)
2122 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002123 QualType destType = Context.getPointerType(destPointee);
2124 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2125 ImpCastExprToType(rex, destType); // promote to void*
2126 return destType;
2127 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002128 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002129 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002130 QualType destType = Context.getPointerType(destPointee);
2131 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2132 ImpCastExprToType(rex, destType); // promote to void*
2133 return destType;
2134 }
Chris Lattner4b009652007-07-25 00:24:17 +00002135
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002136 QualType compositeType = lexT;
2137
2138 // If either type is an Objective-C object type then check
2139 // compatibility according to Objective-C.
2140 if (Context.isObjCObjectPointerType(lexT) ||
2141 Context.isObjCObjectPointerType(rexT)) {
2142 // If both operands are interfaces and either operand can be
2143 // assigned to the other, use that type as the composite
2144 // type. This allows
2145 // xxx ? (A*) a : (B*) b
2146 // where B is a subclass of A.
2147 //
2148 // Additionally, as for assignment, if either type is 'id'
2149 // allow silent coercion. Finally, if the types are
2150 // incompatible then make sure to use 'id' as the composite
2151 // type so the result is acceptable for sending messages to.
2152
2153 // FIXME: This code should not be localized to here. Also this
2154 // should use a compatible check instead of abusing the
2155 // canAssignObjCInterfaces code.
2156 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2157 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2158 if (LHSIface && RHSIface &&
2159 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2160 compositeType = lexT;
2161 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002162 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002163 compositeType = rexT;
2164 } else if (Context.isObjCIdType(lhptee) ||
2165 Context.isObjCIdType(rhptee)) {
2166 // FIXME: This code looks wrong, because isObjCIdType checks
2167 // the struct but getObjCIdType returns the pointer to
2168 // struct. This is horrible and should be fixed.
2169 compositeType = Context.getObjCIdType();
2170 } else {
2171 QualType incompatTy = Context.getObjCIdType();
2172 ImpCastExprToType(lex, incompatTy);
2173 ImpCastExprToType(rex, incompatTy);
2174 return incompatTy;
2175 }
2176 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2177 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002178 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002179 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002180 // In this situation, we assume void* type. No especially good
2181 // reason, but this is what gcc does, and we do have to pick
2182 // to get a consistent AST.
2183 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002184 ImpCastExprToType(lex, incompatTy);
2185 ImpCastExprToType(rex, incompatTy);
2186 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002187 }
2188 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002189 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2190 // differently qualified versions of compatible types, the result type is
2191 // a pointer to an appropriately qualified version of the *composite*
2192 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002193 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002194 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002195 ImpCastExprToType(lex, compositeType);
2196 ImpCastExprToType(rex, compositeType);
2197 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002198 }
Chris Lattner4b009652007-07-25 00:24:17 +00002199 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002200 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2201 // evaluates to "struct objc_object *" (and is handled above when comparing
2202 // id with statically typed objects).
2203 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2204 // GCC allows qualified id and any Objective-C type to devolve to
2205 // id. Currently localizing to here until clear this should be
2206 // part of ObjCQualifiedIdTypesAreCompatible.
2207 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2208 (lexT->isObjCQualifiedIdType() &&
2209 Context.isObjCObjectPointerType(rexT)) ||
2210 (rexT->isObjCQualifiedIdType() &&
2211 Context.isObjCObjectPointerType(lexT))) {
2212 // FIXME: This is not the correct composite type. This only
2213 // happens to work because id can more or less be used anywhere,
2214 // however this may change the type of method sends.
2215 // FIXME: gcc adds some type-checking of the arguments and emits
2216 // (confusing) incompatible comparison warnings in some
2217 // cases. Investigate.
2218 QualType compositeType = Context.getObjCIdType();
2219 ImpCastExprToType(lex, compositeType);
2220 ImpCastExprToType(rex, compositeType);
2221 return compositeType;
2222 }
2223 }
2224
Steve Naroff3eac7692008-09-10 19:17:48 +00002225 // Selection between block pointer types is ok as long as they are the same.
2226 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2227 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2228 return lexT;
2229
Chris Lattner992ae932008-01-06 22:42:25 +00002230 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002231 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002232 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002233 return QualType();
2234}
2235
Steve Naroff87d58b42007-09-16 03:34:24 +00002236/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002237/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002238Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2239 SourceLocation ColonLoc,
2240 ExprArg Cond, ExprArg LHS,
2241 ExprArg RHS) {
2242 Expr *CondExpr = (Expr *) Cond.get();
2243 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002244
2245 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2246 // was the condition.
2247 bool isLHSNull = LHSExpr == 0;
2248 if (isLHSNull)
2249 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002250
2251 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002252 RHSExpr, QuestionLoc);
2253 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002254 return ExprError();
2255
2256 Cond.release();
2257 LHS.release();
2258 RHS.release();
2259 return Owned(new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2260 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002261}
2262
Chris Lattner4b009652007-07-25 00:24:17 +00002263
2264// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2265// being closely modeled after the C99 spec:-). The odd characteristic of this
2266// routine is it effectively iqnores the qualifiers on the top level pointee.
2267// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2268// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002269Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002270Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2271 QualType lhptee, rhptee;
2272
2273 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002274 lhptee = lhsType->getAsPointerType()->getPointeeType();
2275 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002276
2277 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002278 lhptee = Context.getCanonicalType(lhptee);
2279 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002280
Chris Lattner005ed752008-01-04 18:04:52 +00002281 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002282
2283 // C99 6.5.16.1p1: This following citation is common to constraints
2284 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2285 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002286 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002287 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002288 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002289
2290 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2291 // incomplete type and the other is a pointer to a qualified or unqualified
2292 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002293 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002294 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002295 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002296
2297 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002298 assert(rhptee->isFunctionType());
2299 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002300 }
2301
2302 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002303 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002304 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002305
2306 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002307 assert(lhptee->isFunctionType());
2308 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002309 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002310
2311 // Check for ObjC interfaces
2312 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2313 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2314 if (LHSIface && RHSIface &&
2315 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2316 return ConvTy;
2317
2318 // ID acts sort of like void* for ObjC interfaces
2319 if (LHSIface && Context.isObjCIdType(rhptee))
2320 return ConvTy;
2321 if (RHSIface && Context.isObjCIdType(lhptee))
2322 return ConvTy;
2323
Chris Lattner4b009652007-07-25 00:24:17 +00002324 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2325 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002326 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2327 rhptee.getUnqualifiedType()))
2328 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002329 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002330}
2331
Steve Naroff3454b6c2008-09-04 15:10:53 +00002332/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2333/// block pointer types are compatible or whether a block and normal pointer
2334/// are compatible. It is more restrict than comparing two function pointer
2335// types.
2336Sema::AssignConvertType
2337Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2338 QualType rhsType) {
2339 QualType lhptee, rhptee;
2340
2341 // get the "pointed to" type (ignoring qualifiers at the top level)
2342 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2343 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2344
2345 // make sure we operate on the canonical type
2346 lhptee = Context.getCanonicalType(lhptee);
2347 rhptee = Context.getCanonicalType(rhptee);
2348
2349 AssignConvertType ConvTy = Compatible;
2350
2351 // For blocks we enforce that qualifiers are identical.
2352 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2353 ConvTy = CompatiblePointerDiscardsQualifiers;
2354
2355 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2356 return IncompatibleBlockPointer;
2357 return ConvTy;
2358}
2359
Chris Lattner4b009652007-07-25 00:24:17 +00002360/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2361/// has code to accommodate several GCC extensions when type checking
2362/// pointers. Here are some objectionable examples that GCC considers warnings:
2363///
2364/// int a, *pint;
2365/// short *pshort;
2366/// struct foo *pfoo;
2367///
2368/// pint = pshort; // warning: assignment from incompatible pointer type
2369/// a = pint; // warning: assignment makes integer from pointer without a cast
2370/// pint = a; // warning: assignment makes pointer from integer without a cast
2371/// pint = pfoo; // warning: assignment from incompatible pointer type
2372///
2373/// As a result, the code for dealing with pointers is more complex than the
2374/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002375///
Chris Lattner005ed752008-01-04 18:04:52 +00002376Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002377Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002378 // Get canonical types. We're not formatting these types, just comparing
2379 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002380 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2381 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002382
2383 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002384 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002385
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002386 // If the left-hand side is a reference type, then we are in a
2387 // (rare!) case where we've allowed the use of references in C,
2388 // e.g., as a parameter type in a built-in function. In this case,
2389 // just make sure that the type referenced is compatible with the
2390 // right-hand side type. The caller is responsible for adjusting
2391 // lhsType so that the resulting expression does not have reference
2392 // type.
2393 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2394 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002395 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002396 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002397 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002398
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002399 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2400 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002401 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002402 // Relax integer conversions like we do for pointers below.
2403 if (rhsType->isIntegerType())
2404 return IntToPointer;
2405 if (lhsType->isIntegerType())
2406 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002407 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002408 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002409
Nate Begemanc5f0f652008-07-14 18:02:46 +00002410 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002411 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002412 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2413 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002414 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002415
Nate Begemanc5f0f652008-07-14 18:02:46 +00002416 // If we are allowing lax vector conversions, and LHS and RHS are both
2417 // vectors, the total size only needs to be the same. This is a bitcast;
2418 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002419 if (getLangOptions().LaxVectorConversions &&
2420 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002421 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2422 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002423 }
2424 return Incompatible;
2425 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002426
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002427 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002428 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002429
Chris Lattner390564e2008-04-07 06:49:41 +00002430 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002431 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002432 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002433
Chris Lattner390564e2008-04-07 06:49:41 +00002434 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002435 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002436
Steve Naroffa982c712008-09-29 18:10:17 +00002437 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002438 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002439 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002440
2441 // Treat block pointers as objects.
2442 if (getLangOptions().ObjC1 &&
2443 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2444 return Compatible;
2445 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002446 return Incompatible;
2447 }
2448
2449 if (isa<BlockPointerType>(lhsType)) {
2450 if (rhsType->isIntegerType())
2451 return IntToPointer;
2452
Steve Naroffa982c712008-09-29 18:10:17 +00002453 // Treat block pointers as objects.
2454 if (getLangOptions().ObjC1 &&
2455 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2456 return Compatible;
2457
Steve Naroff3454b6c2008-09-04 15:10:53 +00002458 if (rhsType->isBlockPointerType())
2459 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2460
2461 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2462 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002463 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002464 }
Chris Lattner1853da22008-01-04 23:18:45 +00002465 return Incompatible;
2466 }
2467
Chris Lattner390564e2008-04-07 06:49:41 +00002468 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002469 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002470 if (lhsType == Context.BoolTy)
2471 return Compatible;
2472
2473 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002474 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002475
Chris Lattner390564e2008-04-07 06:49:41 +00002476 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002477 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002478
2479 if (isa<BlockPointerType>(lhsType) &&
2480 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002481 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002482 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002483 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002484
Chris Lattner1853da22008-01-04 23:18:45 +00002485 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002486 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002487 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002488 }
2489 return Incompatible;
2490}
2491
Chris Lattner005ed752008-01-04 18:04:52 +00002492Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002493Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002494 if (getLangOptions().CPlusPlus) {
2495 if (!lhsType->isRecordType()) {
2496 // C++ 5.17p3: If the left operand is not of class type, the
2497 // expression is implicitly converted (C++ 4) to the
2498 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002499 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2500 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002501 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002502 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002503 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002504 }
2505
2506 // FIXME: Currently, we fall through and treat C++ classes like C
2507 // structures.
2508 }
2509
Steve Naroffcdee22d2007-11-27 17:58:44 +00002510 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2511 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002512 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2513 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002514 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002515 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002516 return Compatible;
2517 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002518
2519 // We don't allow conversion of non-null-pointer constants to integers.
2520 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2521 return IntToBlockPointer;
2522
Chris Lattner5f505bf2007-10-16 02:55:40 +00002523 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002524 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002525 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002526 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002527 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002528 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002529 if (!lhsType->isReferenceType())
2530 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002531
Chris Lattner005ed752008-01-04 18:04:52 +00002532 Sema::AssignConvertType result =
2533 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002534
2535 // C99 6.5.16.1p2: The value of the right operand is converted to the
2536 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002537 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2538 // so that we can use references in built-in functions even in C.
2539 // The getNonReferenceType() call makes sure that the resulting expression
2540 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002541 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002542 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002543 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002544}
2545
Chris Lattner005ed752008-01-04 18:04:52 +00002546Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002547Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2548 return CheckAssignmentConstraints(lhsType, rhsType);
2549}
2550
Chris Lattner1eafdea2008-11-18 01:30:42 +00002551QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002552 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002553 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002554 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002555 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002556}
2557
Chris Lattner1eafdea2008-11-18 01:30:42 +00002558inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002559 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002560 // For conversion purposes, we ignore any qualifiers.
2561 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002562 QualType lhsType =
2563 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2564 QualType rhsType =
2565 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002566
Nate Begemanc5f0f652008-07-14 18:02:46 +00002567 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002568 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002569 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002570
Nate Begemanc5f0f652008-07-14 18:02:46 +00002571 // Handle the case of a vector & extvector type of the same size and element
2572 // type. It would be nice if we only had one vector type someday.
2573 if (getLangOptions().LaxVectorConversions)
2574 if (const VectorType *LV = lhsType->getAsVectorType())
2575 if (const VectorType *RV = rhsType->getAsVectorType())
2576 if (LV->getElementType() == RV->getElementType() &&
2577 LV->getNumElements() == RV->getNumElements())
2578 return lhsType->isExtVectorType() ? lhsType : rhsType;
2579
2580 // If the lhs is an extended vector and the rhs is a scalar of the same type
2581 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002582 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002583 QualType eltType = V->getElementType();
2584
2585 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2586 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2587 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002588 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002589 return lhsType;
2590 }
2591 }
2592
Nate Begemanc5f0f652008-07-14 18:02:46 +00002593 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002594 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002595 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002596 QualType eltType = V->getElementType();
2597
2598 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2599 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2600 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002601 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002602 return rhsType;
2603 }
2604 }
2605
Chris Lattner4b009652007-07-25 00:24:17 +00002606 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002607 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002608 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002609 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002610 return QualType();
2611}
2612
2613inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002614 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002615{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002616 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002617 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002618
Steve Naroff8f708362007-08-24 19:07:16 +00002619 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002620
Chris Lattner4b009652007-07-25 00:24:17 +00002621 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002622 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002623 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002624}
2625
2626inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002627 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002628{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002629 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2630 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2631 return CheckVectorOperands(Loc, lex, rex);
2632 return InvalidOperands(Loc, lex, rex);
2633 }
Chris Lattner4b009652007-07-25 00:24:17 +00002634
Steve Naroff8f708362007-08-24 19:07:16 +00002635 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002636
Chris Lattner4b009652007-07-25 00:24:17 +00002637 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002638 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002639 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002640}
2641
2642inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002643 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002644{
2645 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002646 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002647
Steve Naroff8f708362007-08-24 19:07:16 +00002648 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002649
Chris Lattner4b009652007-07-25 00:24:17 +00002650 // handle the common case first (both operands are arithmetic).
2651 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002652 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002653
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002654 // Put any potential pointer into PExp
2655 Expr* PExp = lex, *IExp = rex;
2656 if (IExp->getType()->isPointerType())
2657 std::swap(PExp, IExp);
2658
2659 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2660 if (IExp->getType()->isIntegerType()) {
2661 // Check for arithmetic on pointers to incomplete types
2662 if (!PTy->getPointeeType()->isObjectType()) {
2663 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002664 Diag(Loc, diag::ext_gnu_void_ptr)
2665 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002666 } else if (PTy->getPointeeType()->isFunctionType()) {
2667 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002668 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002669 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002670 } else {
2671 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2672 diag::err_typecheck_arithmetic_incomplete_type,
2673 lex->getSourceRange(), SourceRange(),
2674 lex->getType());
2675 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002676 }
2677 }
2678 return PExp->getType();
2679 }
2680 }
2681
Chris Lattner1eafdea2008-11-18 01:30:42 +00002682 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002683}
2684
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002685// C99 6.5.6
2686QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002687 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002688 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002689 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002690
Steve Naroff8f708362007-08-24 19:07:16 +00002691 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002692
Chris Lattnerf6da2912007-12-09 21:53:25 +00002693 // Enforce type constraints: C99 6.5.6p3.
2694
2695 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002696 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002697 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002698
2699 // Either ptr - int or ptr - ptr.
2700 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002701 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002702
Chris Lattnerf6da2912007-12-09 21:53:25 +00002703 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002704 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002705 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002706 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002707 Diag(Loc, diag::ext_gnu_void_ptr)
2708 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002709 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002710 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002711 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002712 return QualType();
2713 }
2714 }
2715
2716 // The result type of a pointer-int computation is the pointer type.
2717 if (rex->getType()->isIntegerType())
2718 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002719
Chris Lattnerf6da2912007-12-09 21:53:25 +00002720 // Handle pointer-pointer subtractions.
2721 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002722 QualType rpointee = RHSPTy->getPointeeType();
2723
Chris Lattnerf6da2912007-12-09 21:53:25 +00002724 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002725 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002726 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002727 if (rpointee->isVoidType()) {
2728 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002729 Diag(Loc, diag::ext_gnu_void_ptr)
2730 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002731 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002732 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002733 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002734 return QualType();
2735 }
2736 }
2737
2738 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002739 if (!Context.typesAreCompatible(
2740 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2741 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002742 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002743 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002744 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002745 return QualType();
2746 }
2747
2748 return Context.getPointerDiffType();
2749 }
2750 }
2751
Chris Lattner1eafdea2008-11-18 01:30:42 +00002752 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002753}
2754
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002755// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002756QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002757 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002758 // C99 6.5.7p2: Each of the operands shall have integer type.
2759 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002760 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002761
Chris Lattner2c8bff72007-12-12 05:47:28 +00002762 // Shifts don't perform usual arithmetic conversions, they just do integer
2763 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002764 if (!isCompAssign)
2765 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002766 UsualUnaryConversions(rex);
2767
2768 // "The type of the result is that of the promoted left operand."
2769 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002770}
2771
Eli Friedman0d9549b2008-08-22 00:56:42 +00002772static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2773 ASTContext& Context) {
2774 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2775 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2776 // ID acts sort of like void* for ObjC interfaces
2777 if (LHSIface && Context.isObjCIdType(RHS))
2778 return true;
2779 if (RHSIface && Context.isObjCIdType(LHS))
2780 return true;
2781 if (!LHSIface || !RHSIface)
2782 return false;
2783 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2784 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2785}
2786
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002787// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002788QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002789 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002790 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002791 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002792
Chris Lattner254f3bc2007-08-26 01:18:55 +00002793 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002794 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2795 UsualArithmeticConversions(lex, rex);
2796 else {
2797 UsualUnaryConversions(lex);
2798 UsualUnaryConversions(rex);
2799 }
Chris Lattner4b009652007-07-25 00:24:17 +00002800 QualType lType = lex->getType();
2801 QualType rType = rex->getType();
2802
Ted Kremenek486509e2007-10-29 17:13:39 +00002803 // For non-floating point types, check for self-comparisons of the form
2804 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2805 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002806 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002807 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2808 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002809 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002810 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002811 }
2812
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002813 // The result of comparisons is 'bool' in C++, 'int' in C.
2814 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2815
Chris Lattner254f3bc2007-08-26 01:18:55 +00002816 if (isRelational) {
2817 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002818 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002819 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002820 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002821 if (lType->isFloatingType()) {
2822 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002823 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002824 }
2825
Chris Lattner254f3bc2007-08-26 01:18:55 +00002826 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002827 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002828 }
Chris Lattner4b009652007-07-25 00:24:17 +00002829
Chris Lattner22be8422007-08-26 01:10:14 +00002830 bool LHSIsNull = lex->isNullPointerConstant(Context);
2831 bool RHSIsNull = rex->isNullPointerConstant(Context);
2832
Chris Lattner254f3bc2007-08-26 01:18:55 +00002833 // All of the following pointer related warnings are GCC extensions, except
2834 // when handling null pointer constants. One day, we can consider making them
2835 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002836 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002837 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002838 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002839 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002840 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002841
Steve Naroff3b435622007-11-13 14:57:38 +00002842 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002843 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2844 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002845 RCanPointeeTy.getUnqualifiedType()) &&
2846 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002847 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002848 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002849 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002850 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002851 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002852 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002853 // Handle block pointer types.
2854 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2855 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2856 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2857
2858 if (!LHSIsNull && !RHSIsNull &&
2859 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002860 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002861 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002862 }
2863 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002864 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002865 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002866 // Allow block pointers to be compared with null pointer constants.
2867 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2868 (lType->isPointerType() && rType->isBlockPointerType())) {
2869 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002870 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002871 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002872 }
2873 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002874 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002875 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002876
Steve Naroff936c4362008-06-03 14:04:54 +00002877 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002878 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002879 const PointerType *LPT = lType->getAsPointerType();
2880 const PointerType *RPT = rType->getAsPointerType();
2881 bool LPtrToVoid = LPT ?
2882 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2883 bool RPtrToVoid = RPT ?
2884 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2885
2886 if (!LPtrToVoid && !RPtrToVoid &&
2887 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002888 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002889 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002890 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002891 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002892 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002893 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002894 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002895 }
Steve Naroff936c4362008-06-03 14:04:54 +00002896 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2897 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002898 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002899 } else {
2900 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002901 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002902 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002903 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002904 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002905 }
Steve Naroff936c4362008-06-03 14:04:54 +00002906 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002907 }
Steve Naroff936c4362008-06-03 14:04:54 +00002908 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2909 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002910 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002911 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002912 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002913 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002914 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002915 }
Steve Naroff936c4362008-06-03 14:04:54 +00002916 if (lType->isIntegerType() &&
2917 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002918 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002919 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002920 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002921 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002922 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002923 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002924 // Handle block pointers.
2925 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2926 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002927 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002928 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002929 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002930 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002931 }
2932 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2933 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002934 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002935 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002936 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002937 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002938 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002939 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002940}
2941
Nate Begemanc5f0f652008-07-14 18:02:46 +00002942/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2943/// operates on extended vector types. Instead of producing an IntTy result,
2944/// like a scalar comparison, a vector comparison produces a vector of integer
2945/// types.
2946QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002947 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002948 bool isRelational) {
2949 // Check to make sure we're operating on vectors of the same type and width,
2950 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002951 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002952 if (vType.isNull())
2953 return vType;
2954
2955 QualType lType = lex->getType();
2956 QualType rType = rex->getType();
2957
2958 // For non-floating point types, check for self-comparisons of the form
2959 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2960 // often indicate logic errors in the program.
2961 if (!lType->isFloatingType()) {
2962 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2963 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2964 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002965 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002966 }
2967
2968 // Check for comparisons of floating point operands using != and ==.
2969 if (!isRelational && lType->isFloatingType()) {
2970 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002971 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002972 }
2973
2974 // Return the type for the comparison, which is the same as vector type for
2975 // integer vectors, or an integer type of identical size and number of
2976 // elements for floating point vectors.
2977 if (lType->isIntegerType())
2978 return lType;
2979
2980 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00002981 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00002982 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00002983 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00002984 else if (TypeSize == Context.getTypeSize(Context.LongTy))
2985 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
2986
2987 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
2988 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00002989 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2990}
2991
Chris Lattner4b009652007-07-25 00:24:17 +00002992inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002993 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002994{
2995 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002996 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002997
Steve Naroff8f708362007-08-24 19:07:16 +00002998 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002999
3000 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003001 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003002 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003003}
3004
3005inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003006 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003007{
3008 UsualUnaryConversions(lex);
3009 UsualUnaryConversions(rex);
3010
Eli Friedmanbea3f842008-05-13 20:16:47 +00003011 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003012 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003013 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003014}
3015
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003016/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3017/// is a read-only property; return true if so. A readonly property expression
3018/// depends on various declarations and thus must be treated specially.
3019///
3020static bool IsReadonlyProperty(Expr *E, Sema &S)
3021{
3022 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3023 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3024 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3025 QualType BaseType = PropExpr->getBase()->getType();
3026 if (const PointerType *PTy = BaseType->getAsPointerType())
3027 if (const ObjCInterfaceType *IFTy =
3028 PTy->getPointeeType()->getAsObjCInterfaceType())
3029 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3030 if (S.isPropertyReadonly(PDecl, IFace))
3031 return true;
3032 }
3033 }
3034 return false;
3035}
3036
Chris Lattner4c2642c2008-11-18 01:22:49 +00003037/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3038/// emit an error and return true. If so, return false.
3039static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003040 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3041 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3042 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003043 if (IsLV == Expr::MLV_Valid)
3044 return false;
3045
3046 unsigned Diag = 0;
3047 bool NeedType = false;
3048 switch (IsLV) { // C99 6.5.16p2
3049 default: assert(0 && "Unknown result from isModifiableLvalue!");
3050 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003051 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003052 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3053 NeedType = true;
3054 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003055 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003056 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3057 NeedType = true;
3058 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003059 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003060 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3061 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003062 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003063 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3064 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003065 case Expr::MLV_IncompleteType:
3066 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003067 return S.DiagnoseIncompleteType(Loc, E->getType(),
3068 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3069 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003070 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003071 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3072 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003073 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003074 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3075 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003076 case Expr::MLV_ReadonlyProperty:
3077 Diag = diag::error_readonly_property_assignment;
3078 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003079 case Expr::MLV_NoSetterProperty:
3080 Diag = diag::error_nosetter_property_assignment;
3081 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003082 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003083
Chris Lattner4c2642c2008-11-18 01:22:49 +00003084 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003085 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003086 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003087 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003088 return true;
3089}
3090
3091
3092
3093// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003094QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3095 SourceLocation Loc,
3096 QualType CompoundType) {
3097 // Verify that LHS is a modifiable lvalue, and emit error if not.
3098 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003099 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003100
3101 QualType LHSType = LHS->getType();
3102 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003103
Chris Lattner005ed752008-01-04 18:04:52 +00003104 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003105 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003106 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003107 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003108 // Special case of NSObject attributes on c-style pointer types.
3109 if (ConvTy == IncompatiblePointer &&
3110 ((Context.isObjCNSObjectType(LHSType) &&
3111 Context.isObjCObjectPointerType(RHSType)) ||
3112 (Context.isObjCNSObjectType(RHSType) &&
3113 Context.isObjCObjectPointerType(LHSType))))
3114 ConvTy = Compatible;
3115
Chris Lattner34c85082008-08-21 18:04:13 +00003116 // If the RHS is a unary plus or minus, check to see if they = and + are
3117 // right next to each other. If so, the user may have typo'd "x =+ 4"
3118 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003119 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003120 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3121 RHSCheck = ICE->getSubExpr();
3122 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3123 if ((UO->getOpcode() == UnaryOperator::Plus ||
3124 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003125 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003126 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003127 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003128 Diag(Loc, diag::warn_not_compound_assign)
3129 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3130 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003131 }
3132 } else {
3133 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003134 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003135 }
Chris Lattner005ed752008-01-04 18:04:52 +00003136
Chris Lattner1eafdea2008-11-18 01:30:42 +00003137 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3138 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003139 return QualType();
3140
Chris Lattner4b009652007-07-25 00:24:17 +00003141 // C99 6.5.16p3: The type of an assignment expression is the type of the
3142 // left operand unless the left operand has qualified type, in which case
3143 // it is the unqualified version of the type of the left operand.
3144 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3145 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003146 // C++ 5.17p1: the type of the assignment expression is that of its left
3147 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003148 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003149}
3150
Chris Lattner1eafdea2008-11-18 01:30:42 +00003151// C99 6.5.17
3152QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3153 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003154
3155 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003156 DefaultFunctionArrayConversion(RHS);
3157 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003158}
3159
3160/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3161/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003162QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3163 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003164 QualType ResType = Op->getType();
3165 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003166
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003167 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3168 // Decrement of bool is not allowed.
3169 if (!isInc) {
3170 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3171 return QualType();
3172 }
3173 // Increment of bool sets it to true, but is deprecated.
3174 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3175 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003176 // OK!
3177 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3178 // C99 6.5.2.4p2, 6.5.6p2
3179 if (PT->getPointeeType()->isObjectType()) {
3180 // Pointer to object is ok!
3181 } else if (PT->getPointeeType()->isVoidType()) {
3182 // Pointer to void is extension.
3183 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003184 } else if (PT->getPointeeType()->isFunctionType()) {
3185 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003186 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003187 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003188 } else {
3189 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3190 diag::err_typecheck_arithmetic_incomplete_type,
3191 Op->getSourceRange(), SourceRange(),
3192 ResType);
3193 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003194 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003195 } else if (ResType->isComplexType()) {
3196 // C99 does not support ++/-- on complex types, we allow as an extension.
3197 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003198 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003199 } else {
3200 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003201 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003202 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003203 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003204 // At this point, we know we have a real, complex or pointer type.
3205 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003206 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003207 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003208 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003209}
3210
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003211/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003212/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003213/// where the declaration is needed for type checking. We only need to
3214/// handle cases when the expression references a function designator
3215/// or is an lvalue. Here are some examples:
3216/// - &(x) => x
3217/// - &*****f => f for f a function designator.
3218/// - &s.xx => s
3219/// - &s.zz[1].yy -> s, if zz is an array
3220/// - *(x + 1) -> x, if x is an array
3221/// - &"123"[2] -> 0
3222/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003223static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003224 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003225 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003226 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003227 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003228 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003229 // Fields cannot be declared with a 'register' storage class.
3230 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003231 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003232 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003233 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003234 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003235 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003236
Douglas Gregord2baafd2008-10-21 16:13:35 +00003237 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003238 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003239 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003240 return 0;
3241 else
3242 return VD;
3243 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003244 case Stmt::UnaryOperatorClass: {
3245 UnaryOperator *UO = cast<UnaryOperator>(E);
3246
3247 switch(UO->getOpcode()) {
3248 case UnaryOperator::Deref: {
3249 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003250 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3251 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3252 if (!VD || VD->getType()->isPointerType())
3253 return 0;
3254 return VD;
3255 }
3256 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003257 }
3258 case UnaryOperator::Real:
3259 case UnaryOperator::Imag:
3260 case UnaryOperator::Extension:
3261 return getPrimaryDecl(UO->getSubExpr());
3262 default:
3263 return 0;
3264 }
3265 }
3266 case Stmt::BinaryOperatorClass: {
3267 BinaryOperator *BO = cast<BinaryOperator>(E);
3268
3269 // Handle cases involving pointer arithmetic. The result of an
3270 // Assign or AddAssign is not an lvalue so they can be ignored.
3271
3272 // (x + n) or (n + x) => x
3273 if (BO->getOpcode() == BinaryOperator::Add) {
3274 if (BO->getLHS()->getType()->isPointerType()) {
3275 return getPrimaryDecl(BO->getLHS());
3276 } else if (BO->getRHS()->getType()->isPointerType()) {
3277 return getPrimaryDecl(BO->getRHS());
3278 }
3279 }
3280
3281 return 0;
3282 }
Chris Lattner4b009652007-07-25 00:24:17 +00003283 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003284 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003285 case Stmt::ImplicitCastExprClass:
3286 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003287 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003288 default:
3289 return 0;
3290 }
3291}
3292
3293/// CheckAddressOfOperand - The operand of & must be either a function
3294/// designator or an lvalue designating an object. If it is an lvalue, the
3295/// object cannot be declared with storage class register or be a bit field.
3296/// Note: The usual conversions are *not* applied to the operand of the &
3297/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003298/// In C++, the operand might be an overloaded function name, in which case
3299/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003300QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003301 if (op->isTypeDependent())
3302 return Context.DependentTy;
3303
Steve Naroff9c6c3592008-01-13 17:10:08 +00003304 if (getLangOptions().C99) {
3305 // Implement C99-only parts of addressof rules.
3306 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3307 if (uOp->getOpcode() == UnaryOperator::Deref)
3308 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3309 // (assuming the deref expression is valid).
3310 return uOp->getSubExpr()->getType();
3311 }
3312 // Technically, there should be a check for array subscript
3313 // expressions here, but the result of one is always an lvalue anyway.
3314 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003315 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003316 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003317
Chris Lattner4b009652007-07-25 00:24:17 +00003318 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003319 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3320 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003321 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3322 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003323 return QualType();
3324 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003325 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003326 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3327 if (Field->isBitField()) {
3328 Diag(OpLoc, diag::err_typecheck_address_of)
3329 << "bit-field" << op->getSourceRange();
3330 return QualType();
3331 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003332 }
3333 // Check for Apple extension for accessing vector components.
3334 } else if (isa<ArraySubscriptExpr>(op) &&
3335 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003336 Diag(OpLoc, diag::err_typecheck_address_of)
3337 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003338 return QualType();
3339 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003340 // We have an lvalue with a decl. Make sure the decl is not declared
3341 // with the register storage-class specifier.
3342 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3343 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003344 Diag(OpLoc, diag::err_typecheck_address_of)
3345 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003346 return QualType();
3347 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003348 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003349 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003350 } else if (isa<FieldDecl>(dcl)) {
3351 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003352 } else if (isa<FunctionDecl>(dcl)) {
3353 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003354 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003355 else
Chris Lattner4b009652007-07-25 00:24:17 +00003356 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003357 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003358
Chris Lattner4b009652007-07-25 00:24:17 +00003359 // If the operand has type "type", the result has type "pointer to type".
3360 return Context.getPointerType(op->getType());
3361}
3362
Chris Lattnerda5c0872008-11-23 09:13:29 +00003363QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3364 UsualUnaryConversions(Op);
3365 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003366
Chris Lattnerda5c0872008-11-23 09:13:29 +00003367 // Note that per both C89 and C99, this is always legal, even if ptype is an
3368 // incomplete type or void. It would be possible to warn about dereferencing
3369 // a void pointer, but it's completely well-defined, and such a warning is
3370 // unlikely to catch any mistakes.
3371 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003372 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003373
Chris Lattner77d52da2008-11-20 06:06:08 +00003374 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003375 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003376 return QualType();
3377}
3378
3379static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3380 tok::TokenKind Kind) {
3381 BinaryOperator::Opcode Opc;
3382 switch (Kind) {
3383 default: assert(0 && "Unknown binop!");
3384 case tok::star: Opc = BinaryOperator::Mul; break;
3385 case tok::slash: Opc = BinaryOperator::Div; break;
3386 case tok::percent: Opc = BinaryOperator::Rem; break;
3387 case tok::plus: Opc = BinaryOperator::Add; break;
3388 case tok::minus: Opc = BinaryOperator::Sub; break;
3389 case tok::lessless: Opc = BinaryOperator::Shl; break;
3390 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3391 case tok::lessequal: Opc = BinaryOperator::LE; break;
3392 case tok::less: Opc = BinaryOperator::LT; break;
3393 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3394 case tok::greater: Opc = BinaryOperator::GT; break;
3395 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3396 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3397 case tok::amp: Opc = BinaryOperator::And; break;
3398 case tok::caret: Opc = BinaryOperator::Xor; break;
3399 case tok::pipe: Opc = BinaryOperator::Or; break;
3400 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3401 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3402 case tok::equal: Opc = BinaryOperator::Assign; break;
3403 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3404 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3405 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3406 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3407 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3408 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3409 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3410 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3411 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3412 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3413 case tok::comma: Opc = BinaryOperator::Comma; break;
3414 }
3415 return Opc;
3416}
3417
3418static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3419 tok::TokenKind Kind) {
3420 UnaryOperator::Opcode Opc;
3421 switch (Kind) {
3422 default: assert(0 && "Unknown unary op!");
3423 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3424 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3425 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3426 case tok::star: Opc = UnaryOperator::Deref; break;
3427 case tok::plus: Opc = UnaryOperator::Plus; break;
3428 case tok::minus: Opc = UnaryOperator::Minus; break;
3429 case tok::tilde: Opc = UnaryOperator::Not; break;
3430 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003431 case tok::kw___real: Opc = UnaryOperator::Real; break;
3432 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3433 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3434 }
3435 return Opc;
3436}
3437
Douglas Gregord7f915e2008-11-06 23:29:22 +00003438/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3439/// operator @p Opc at location @c TokLoc. This routine only supports
3440/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003441Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3442 unsigned Op,
3443 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003444 QualType ResultTy; // Result type of the binary operator.
3445 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3446 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3447
3448 switch (Opc) {
3449 default:
3450 assert(0 && "Unknown binary expr!");
3451 case BinaryOperator::Assign:
3452 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3453 break;
3454 case BinaryOperator::Mul:
3455 case BinaryOperator::Div:
3456 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3457 break;
3458 case BinaryOperator::Rem:
3459 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3460 break;
3461 case BinaryOperator::Add:
3462 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3463 break;
3464 case BinaryOperator::Sub:
3465 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3466 break;
3467 case BinaryOperator::Shl:
3468 case BinaryOperator::Shr:
3469 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3470 break;
3471 case BinaryOperator::LE:
3472 case BinaryOperator::LT:
3473 case BinaryOperator::GE:
3474 case BinaryOperator::GT:
3475 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3476 break;
3477 case BinaryOperator::EQ:
3478 case BinaryOperator::NE:
3479 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3480 break;
3481 case BinaryOperator::And:
3482 case BinaryOperator::Xor:
3483 case BinaryOperator::Or:
3484 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3485 break;
3486 case BinaryOperator::LAnd:
3487 case BinaryOperator::LOr:
3488 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3489 break;
3490 case BinaryOperator::MulAssign:
3491 case BinaryOperator::DivAssign:
3492 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3493 if (!CompTy.isNull())
3494 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3495 break;
3496 case BinaryOperator::RemAssign:
3497 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3498 if (!CompTy.isNull())
3499 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3500 break;
3501 case BinaryOperator::AddAssign:
3502 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3503 if (!CompTy.isNull())
3504 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3505 break;
3506 case BinaryOperator::SubAssign:
3507 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3508 if (!CompTy.isNull())
3509 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3510 break;
3511 case BinaryOperator::ShlAssign:
3512 case BinaryOperator::ShrAssign:
3513 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3514 if (!CompTy.isNull())
3515 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3516 break;
3517 case BinaryOperator::AndAssign:
3518 case BinaryOperator::XorAssign:
3519 case BinaryOperator::OrAssign:
3520 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3521 if (!CompTy.isNull())
3522 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3523 break;
3524 case BinaryOperator::Comma:
3525 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3526 break;
3527 }
3528 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003529 return ExprError();
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003530 if (CompTy.isNull()) {
3531 void *Mem = Context.getAllocator().Allocate<BinaryOperator>();
3532 return Owned(new (Mem) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3533 } else {
3534 void *Mem = Context.getAllocator().Allocate<CompoundAssignOperator>();
3535 return Owned(new (Mem) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3536 CompTy, OpLoc));
3537 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003538}
3539
Chris Lattner4b009652007-07-25 00:24:17 +00003540// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003541Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3542 tok::TokenKind Kind,
3543 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003544 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003545 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003546
Steve Naroff87d58b42007-09-16 03:34:24 +00003547 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3548 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003549
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003550 // If either expression is type-dependent, just build the AST.
3551 // FIXME: We'll need to perform some caching of the result of name
3552 // lookup for operator+.
3553 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003554 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
3555 void *Mem = Context.getAllocator().Allocate<CompoundAssignOperator>();
3556 return Owned(new (Mem) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003557 Context.DependentTy,
3558 Context.DependentTy, TokLoc));
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003559 } else {
3560 void *Mem = Context.getAllocator().Allocate<BinaryOperator>();
3561 return Owned(new (Mem) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3562 TokLoc));
3563 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003564 }
3565
Douglas Gregord7f915e2008-11-06 23:29:22 +00003566 if (getLangOptions().CPlusPlus &&
3567 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3568 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003569 // If this is one of the assignment operators, we only perform
3570 // overload resolution if the left-hand side is a class or
3571 // enumeration type (C++ [expr.ass]p3).
3572 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3573 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3574 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3575 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003576
Douglas Gregord7f915e2008-11-06 23:29:22 +00003577 // Determine which overloaded operator we're dealing with.
3578 static const OverloadedOperatorKind OverOps[] = {
3579 OO_Star, OO_Slash, OO_Percent,
3580 OO_Plus, OO_Minus,
3581 OO_LessLess, OO_GreaterGreater,
3582 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3583 OO_EqualEqual, OO_ExclaimEqual,
3584 OO_Amp,
3585 OO_Caret,
3586 OO_Pipe,
3587 OO_AmpAmp,
3588 OO_PipePipe,
3589 OO_Equal, OO_StarEqual,
3590 OO_SlashEqual, OO_PercentEqual,
3591 OO_PlusEqual, OO_MinusEqual,
3592 OO_LessLessEqual, OO_GreaterGreaterEqual,
3593 OO_AmpEqual, OO_CaretEqual,
3594 OO_PipeEqual,
3595 OO_Comma
3596 };
3597 OverloadedOperatorKind OverOp = OverOps[Opc];
3598
Douglas Gregor5ed15042008-11-18 23:14:02 +00003599 // Add the appropriate overloaded operators (C++ [over.match.oper])
3600 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003601 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003602 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003603 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003604
3605 // Perform overload resolution.
3606 OverloadCandidateSet::iterator Best;
3607 switch (BestViableFunction(CandidateSet, Best)) {
3608 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003609 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003610 FunctionDecl *FnDecl = Best->Function;
3611
Douglas Gregor70d26122008-11-12 17:17:38 +00003612 if (FnDecl) {
3613 // We matched an overloaded operator. Build a call to that
3614 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003615
Douglas Gregor70d26122008-11-12 17:17:38 +00003616 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3618 if (PerformObjectArgumentInitialization(lhs, Method) ||
3619 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3620 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003621 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003622 } else {
3623 // Convert the arguments.
3624 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3625 "passing") ||
3626 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3627 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003628 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003629 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003630
Douglas Gregor70d26122008-11-12 17:17:38 +00003631 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003632 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003633 = FnDecl->getType()->getAsFunctionType()->getResultType();
3634 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003635
Douglas Gregor70d26122008-11-12 17:17:38 +00003636 // Build the actual expression node.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003637 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003638 SourceLocation());
3639 UsualUnaryConversions(FnExpr);
3640
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003641 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003642 } else {
3643 // We matched a built-in operator. Convert the arguments, then
3644 // break out so that we will build the appropriate built-in
3645 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003646 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3647 Best->Conversions[0], "passing") ||
3648 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3649 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003650 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003651
3652 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003653 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003654 }
3655
3656 case OR_No_Viable_Function:
3657 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003658 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003659 break;
3660
3661 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003662 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3663 << BinaryOperator::getOpcodeStr(Opc)
3664 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003665 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003666 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003667 }
3668
Douglas Gregor70d26122008-11-12 17:17:38 +00003669 // Either we found no viable overloaded operator or we matched a
3670 // built-in operator. In either case, fall through to trying to
3671 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003672 }
3673
Douglas Gregord7f915e2008-11-06 23:29:22 +00003674 // Build a built-in binary operation.
3675 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003676}
3677
3678// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003679Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3680 tok::TokenKind Op, ExprArg input) {
3681 // FIXME: Input is modified later, but smart pointer not reassigned.
3682 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003683 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003684
3685 if (getLangOptions().CPlusPlus &&
3686 (Input->getType()->isRecordType()
3687 || Input->getType()->isEnumeralType())) {
3688 // Determine which overloaded operator we're dealing with.
3689 static const OverloadedOperatorKind OverOps[] = {
3690 OO_None, OO_None,
3691 OO_PlusPlus, OO_MinusMinus,
3692 OO_Amp, OO_Star,
3693 OO_Plus, OO_Minus,
3694 OO_Tilde, OO_Exclaim,
3695 OO_None, OO_None,
3696 OO_None,
3697 OO_None
3698 };
3699 OverloadedOperatorKind OverOp = OverOps[Opc];
3700
3701 // Add the appropriate overloaded operators (C++ [over.match.oper])
3702 // to the candidate set.
3703 OverloadCandidateSet CandidateSet;
3704 if (OverOp != OO_None)
3705 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3706
3707 // Perform overload resolution.
3708 OverloadCandidateSet::iterator Best;
3709 switch (BestViableFunction(CandidateSet, Best)) {
3710 case OR_Success: {
3711 // We found a built-in operator or an overloaded operator.
3712 FunctionDecl *FnDecl = Best->Function;
3713
3714 if (FnDecl) {
3715 // We matched an overloaded operator. Build a call to that
3716 // operator.
3717
3718 // Convert the arguments.
3719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3720 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003721 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003722 } else {
3723 // Convert the arguments.
3724 if (PerformCopyInitialization(Input,
3725 FnDecl->getParamDecl(0)->getType(),
3726 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003727 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003728 }
3729
3730 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003731 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003732 = FnDecl->getType()->getAsFunctionType()->getResultType();
3733 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003734
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003735 // Build the actual expression node.
3736 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3737 SourceLocation());
3738 UsualUnaryConversions(FnExpr);
3739
Sebastian Redl8b769972009-01-19 00:08:26 +00003740 input.release();
3741 return Owned(new CXXOperatorCallExpr(FnExpr, &Input, 1,
3742 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003743 } else {
3744 // We matched a built-in operator. Convert the arguments, then
3745 // break out so that we will build the appropriate built-in
3746 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003747 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3748 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003749 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003750
3751 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003752 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003753 }
3754
3755 case OR_No_Viable_Function:
3756 // No viable function; fall through to handling this as a
3757 // built-in operator, which will produce an error message for us.
3758 break;
3759
3760 case OR_Ambiguous:
3761 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3762 << UnaryOperator::getOpcodeStr(Opc)
3763 << Input->getSourceRange();
3764 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003765 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003766 }
3767
3768 // Either we found no viable overloaded operator or we matched a
3769 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003770 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003771 }
3772
Chris Lattner4b009652007-07-25 00:24:17 +00003773 QualType resultType;
3774 switch (Opc) {
3775 default:
3776 assert(0 && "Unimplemented unary expr!");
3777 case UnaryOperator::PreInc:
3778 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003779 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3780 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003781 break;
3782 case UnaryOperator::AddrOf:
3783 resultType = CheckAddressOfOperand(Input, OpLoc);
3784 break;
3785 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003786 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003787 resultType = CheckIndirectionOperand(Input, OpLoc);
3788 break;
3789 case UnaryOperator::Plus:
3790 case UnaryOperator::Minus:
3791 UsualUnaryConversions(Input);
3792 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003793 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3794 break;
3795 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3796 resultType->isEnumeralType())
3797 break;
3798 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3799 Opc == UnaryOperator::Plus &&
3800 resultType->isPointerType())
3801 break;
3802
Sebastian Redl8b769972009-01-19 00:08:26 +00003803 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3804 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003805 case UnaryOperator::Not: // bitwise complement
3806 UsualUnaryConversions(Input);
3807 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003808 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3809 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3810 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003811 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003812 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003813 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003814 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3815 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003816 break;
3817 case UnaryOperator::LNot: // logical negation
3818 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3819 DefaultFunctionArrayConversion(Input);
3820 resultType = Input->getType();
3821 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3823 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003824 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003825 // In C++, it's bool. C++ 5.3.1p8
3826 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003827 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003828 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003829 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003830 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003831 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003832 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003833 resultType = Input->getType();
3834 break;
3835 }
3836 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003837 return ExprError();
3838 input.release();
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003839 void *Mem = Context.getAllocator().Allocate<UnaryOperator>();
3840 return Owned(new (Mem) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003841}
3842
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003843/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3844Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003845 SourceLocation LabLoc,
3846 IdentifierInfo *LabelII) {
3847 // Look up the record for this label identifier.
3848 LabelStmt *&LabelDecl = LabelMap[LabelII];
3849
Daniel Dunbar879788d2008-08-04 16:51:22 +00003850 // If we haven't seen this label yet, create a forward reference. It
3851 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003852 if (LabelDecl == 0)
3853 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3854
3855 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003856 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3857 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003858}
3859
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003860Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003861 SourceLocation RPLoc) { // "({..})"
3862 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3863 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3864 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3865
3866 // FIXME: there are a variety of strange constraints to enforce here, for
3867 // example, it is not possible to goto into a stmt expression apparently.
3868 // More semantic analysis is needed.
3869
3870 // FIXME: the last statement in the compount stmt has its value used. We
3871 // should not warn about it being unused.
3872
3873 // If there are sub stmts in the compound stmt, take the type of the last one
3874 // as the type of the stmtexpr.
3875 QualType Ty = Context.VoidTy;
3876
Chris Lattner200964f2008-07-26 19:51:01 +00003877 if (!Compound->body_empty()) {
3878 Stmt *LastStmt = Compound->body_back();
3879 // If LastStmt is a label, skip down through into the body.
3880 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3881 LastStmt = Label->getSubStmt();
3882
3883 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003884 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003885 }
Chris Lattner4b009652007-07-25 00:24:17 +00003886
3887 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3888}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003889
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003890Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3891 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003892 SourceLocation TypeLoc,
3893 TypeTy *argty,
3894 OffsetOfComponent *CompPtr,
3895 unsigned NumComponents,
3896 SourceLocation RPLoc) {
3897 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3898 assert(!ArgTy.isNull() && "Missing type argument!");
3899
3900 // We must have at least one component that refers to the type, and the first
3901 // one is known to be a field designator. Verify that the ArgTy represents
3902 // a struct/union/class.
3903 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003904 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003905
3906 // Otherwise, create a compound literal expression as the base, and
3907 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003908 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003909
Chris Lattnerb37522e2007-08-31 21:49:13 +00003910 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3911 // GCC extension, diagnose them.
3912 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003913 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3914 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003915
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003916 for (unsigned i = 0; i != NumComponents; ++i) {
3917 const OffsetOfComponent &OC = CompPtr[i];
3918 if (OC.isBrackets) {
3919 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003920 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003921 if (!AT) {
3922 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003923 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003924 }
3925
Chris Lattner2af6a802007-08-30 17:59:59 +00003926 // FIXME: C++: Verify that operator[] isn't overloaded.
3927
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003928 // C99 6.5.2.1p1
3929 Expr *Idx = static_cast<Expr*>(OC.U.E);
3930 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003931 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3932 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003933
3934 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3935 continue;
3936 }
3937
3938 const RecordType *RC = Res->getType()->getAsRecordType();
3939 if (!RC) {
3940 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003941 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003942 }
3943
3944 // Get the decl corresponding to this.
3945 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003946 FieldDecl *MemberDecl
3947 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3948 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003949 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003950 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003951 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3952 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003953
3954 // FIXME: C++: Verify that MemberDecl isn't a static field.
3955 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003956 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3957 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003958 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3959 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003960 }
3961
3962 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3963 BuiltinLoc);
3964}
3965
3966
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003967Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003968 TypeTy *arg1, TypeTy *arg2,
3969 SourceLocation RPLoc) {
3970 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3971 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3972
3973 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3974
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003975 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003976}
3977
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003978Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003979 ExprTy *expr1, ExprTy *expr2,
3980 SourceLocation RPLoc) {
3981 Expr *CondExpr = static_cast<Expr*>(cond);
3982 Expr *LHSExpr = static_cast<Expr*>(expr1);
3983 Expr *RHSExpr = static_cast<Expr*>(expr2);
3984
3985 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3986
3987 // The conditional expression is required to be a constant expression.
3988 llvm::APSInt condEval(32);
3989 SourceLocation ExpLoc;
3990 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003991 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3992 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003993
3994 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3995 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3996 RHSExpr->getType();
3997 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3998}
3999
Steve Naroff52a81c02008-09-03 18:15:37 +00004000//===----------------------------------------------------------------------===//
4001// Clang Extensions.
4002//===----------------------------------------------------------------------===//
4003
4004/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004005void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004006 // Analyze block parameters.
4007 BlockSemaInfo *BSI = new BlockSemaInfo();
4008
4009 // Add BSI to CurBlock.
4010 BSI->PrevBlockInfo = CurBlock;
4011 CurBlock = BSI;
4012
4013 BSI->ReturnType = 0;
4014 BSI->TheScope = BlockScope;
4015
Steve Naroff52059382008-10-10 01:28:17 +00004016 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004017 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004018}
4019
4020void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004021 // Analyze arguments to block.
4022 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4023 "Not a function declarator!");
4024 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4025
Steve Naroff52059382008-10-10 01:28:17 +00004026 CurBlock->hasPrototype = FTI.hasPrototype;
4027 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004028
4029 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4030 // no arguments, not a function that takes a single void argument.
4031 if (FTI.hasPrototype &&
4032 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4033 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4034 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4035 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004036 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004037 } else if (FTI.hasPrototype) {
4038 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004039 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4040 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004041 }
Steve Naroff52059382008-10-10 01:28:17 +00004042 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4043
4044 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4045 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4046 // If this has an identifier, add it to the scope stack.
4047 if ((*AI)->getIdentifier())
4048 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004049}
4050
4051/// ActOnBlockError - If there is an error parsing a block, this callback
4052/// is invoked to pop the information about the block from the action impl.
4053void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4054 // Ensure that CurBlock is deleted.
4055 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4056
4057 // Pop off CurBlock, handle nested blocks.
4058 CurBlock = CurBlock->PrevBlockInfo;
4059
4060 // FIXME: Delete the ParmVarDecl objects as well???
4061
4062}
4063
4064/// ActOnBlockStmtExpr - This is called when the body of a block statement
4065/// literal was successfully completed. ^(int x){...}
4066Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4067 Scope *CurScope) {
4068 // Ensure that CurBlock is deleted.
4069 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4070 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4071
Steve Naroff52059382008-10-10 01:28:17 +00004072 PopDeclContext();
4073
Steve Naroff52a81c02008-09-03 18:15:37 +00004074 // Pop off CurBlock, handle nested blocks.
4075 CurBlock = CurBlock->PrevBlockInfo;
4076
4077 QualType RetTy = Context.VoidTy;
4078 if (BSI->ReturnType)
4079 RetTy = QualType(BSI->ReturnType, 0);
4080
4081 llvm::SmallVector<QualType, 8> ArgTypes;
4082 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4083 ArgTypes.push_back(BSI->Params[i]->getType());
4084
4085 QualType BlockTy;
4086 if (!BSI->hasPrototype)
4087 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4088 else
4089 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004090 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004091
4092 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004093
Steve Naroff95029d92008-10-08 18:44:00 +00004094 BSI->TheDecl->setBody(Body.take());
4095 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004096}
4097
Nate Begemanbd881ef2008-01-30 20:50:20 +00004098/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004099/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004100/// The number of arguments has already been validated to match the number of
4101/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004102static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4103 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004104 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004105 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004106 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4107 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004108
4109 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004110 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004111 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004112 return true;
4113}
4114
4115Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4116 SourceLocation *CommaLocs,
4117 SourceLocation BuiltinLoc,
4118 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004119 // __builtin_overload requires at least 2 arguments
4120 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004121 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4122 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004123
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004124 // The first argument is required to be a constant expression. It tells us
4125 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004126 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004127 Expr *NParamsExpr = Args[0];
4128 llvm::APSInt constEval(32);
4129 SourceLocation ExpLoc;
4130 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004131 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4132 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004133
4134 // Verify that the number of parameters is > 0
4135 unsigned NumParams = constEval.getZExtValue();
4136 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004137 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4138 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004139 // Verify that we have at least 1 + NumParams arguments to the builtin.
4140 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004141 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4142 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004143
4144 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004145 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004146 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004147 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4148 // UsualUnaryConversions will convert the function DeclRefExpr into a
4149 // pointer to function.
4150 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004151 const FunctionTypeProto *FnType = 0;
4152 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4153 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004154
4155 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4156 // parameters, and the number of parameters must match the value passed to
4157 // the builtin.
4158 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004159 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4160 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004161
4162 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004163 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004164 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004165 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004166 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004167 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4168 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004169 // Remember our match, and continue processing the remaining arguments
4170 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004171 OE = new OverloadExpr(Args, NumArgs, i,
4172 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004173 BuiltinLoc, RParenLoc);
4174 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004175 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004176 // Return the newly created OverloadExpr node, if we succeded in matching
4177 // exactly one of the candidate functions.
4178 if (OE)
4179 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004180
4181 // If we didn't find a matching function Expr in the __builtin_overload list
4182 // the return an error.
4183 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004184 for (unsigned i = 0; i != NumParams; ++i) {
4185 if (i != 0) typeNames += ", ";
4186 typeNames += Args[i+1]->getType().getAsString();
4187 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004188
Chris Lattner77d52da2008-11-20 06:06:08 +00004189 return Diag(BuiltinLoc, diag::err_overload_no_match)
4190 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004191}
4192
Anders Carlsson36760332007-10-15 20:28:48 +00004193Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4194 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004195 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004196 Expr *E = static_cast<Expr*>(expr);
4197 QualType T = QualType::getFromOpaquePtr(type);
4198
4199 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004200
4201 // Get the va_list type
4202 QualType VaListType = Context.getBuiltinVaListType();
4203 // Deal with implicit array decay; for example, on x86-64,
4204 // va_list is an array, but it's supposed to decay to
4205 // a pointer for va_arg.
4206 if (VaListType->isArrayType())
4207 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004208 // Make sure the input expression also decays appropriately.
4209 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004210
4211 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004212 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004213 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004214 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004215
4216 // FIXME: Warn if a non-POD type is passed in.
4217
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004218 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004219}
4220
Douglas Gregorad4b3792008-11-29 04:51:27 +00004221Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4222 // The type of __null will be int or long, depending on the size of
4223 // pointers on the target.
4224 QualType Ty;
4225 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4226 Ty = Context.IntTy;
4227 else
4228 Ty = Context.LongTy;
4229
4230 return new GNUNullExpr(Ty, TokenLoc);
4231}
4232
Chris Lattner005ed752008-01-04 18:04:52 +00004233bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4234 SourceLocation Loc,
4235 QualType DstType, QualType SrcType,
4236 Expr *SrcExpr, const char *Flavor) {
4237 // Decode the result (notice that AST's are still created for extensions).
4238 bool isInvalid = false;
4239 unsigned DiagKind;
4240 switch (ConvTy) {
4241 default: assert(0 && "Unknown conversion type");
4242 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004243 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004244 DiagKind = diag::ext_typecheck_convert_pointer_int;
4245 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004246 case IntToPointer:
4247 DiagKind = diag::ext_typecheck_convert_int_pointer;
4248 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004249 case IncompatiblePointer:
4250 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4251 break;
4252 case FunctionVoidPointer:
4253 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4254 break;
4255 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004256 // If the qualifiers lost were because we were applying the
4257 // (deprecated) C++ conversion from a string literal to a char*
4258 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4259 // Ideally, this check would be performed in
4260 // CheckPointerTypesForAssignment. However, that would require a
4261 // bit of refactoring (so that the second argument is an
4262 // expression, rather than a type), which should be done as part
4263 // of a larger effort to fix CheckPointerTypesForAssignment for
4264 // C++ semantics.
4265 if (getLangOptions().CPlusPlus &&
4266 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4267 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004268 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4269 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004270 case IntToBlockPointer:
4271 DiagKind = diag::err_int_to_block_pointer;
4272 break;
4273 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004274 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004275 break;
Steve Naroff19608432008-10-14 22:18:38 +00004276 case IncompatibleObjCQualifiedId:
4277 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4278 // it can give a more specific diagnostic.
4279 DiagKind = diag::warn_incompatible_qualified_id;
4280 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004281 case Incompatible:
4282 DiagKind = diag::err_typecheck_convert_incompatible;
4283 isInvalid = true;
4284 break;
4285 }
4286
Chris Lattner271d4c22008-11-24 05:29:24 +00004287 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4288 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004289 return isInvalid;
4290}
Anders Carlssond5201b92008-11-30 19:50:32 +00004291
4292bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4293{
4294 Expr::EvalResult EvalResult;
4295
4296 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4297 EvalResult.HasSideEffects) {
4298 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4299
4300 if (EvalResult.Diag) {
4301 // We only show the note if it's not the usual "invalid subexpression"
4302 // or if it's actually in a subexpression.
4303 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4304 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4305 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4306 }
4307
4308 return true;
4309 }
4310
4311 if (EvalResult.Diag) {
4312 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4313 E->getSourceRange();
4314
4315 // Print the reason it's not a constant.
4316 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4317 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4318 }
4319
4320 if (Result)
4321 *Result = EvalResult.Val.getInt();
4322 return false;
4323}