blob: 8a8fb731c7770d05f219d832b9db4403e8a4ce30 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattner05faf172008-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 Carlssondce5e2c2009-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 Lattnere7a2e912008-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 Gregoreb8f3062008-11-12 17:17:38 +0000117
Chris Lattnere7a2e912008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-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 Gregorbf3af052008-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 Gregoreb8f3062008-11-12 17:17:38 +0000152
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-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 Carlsson5b1f3f02008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Narofff69936d2007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlcd965b92009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000300 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000305
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Redlcd965b92009-01-18 18:53:16 +0000313
Chris Lattnera7ad98f2008-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 Redlcd965b92009-01-18 18:53:16 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sebastian Redlcd965b92009-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000326}
327
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
366 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor1a49af92009-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 Naroff0a473932009-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 Gregor1a49af92009-01-06 05:10:23 +0000384}
385
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000389static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000390 assert(Record->isAnonymousStructOrUnion() &&
391 "Record must be an anonymous struct or union!");
392
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000393 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000406 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000415Sema::OwningExprResult
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000435 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000521}
522
Douglas Gregor10c42622008-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 Gregor5c37de72008-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 Redlcd965b92009-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 Gregor5c37de72008-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 Naroff0a473932009-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 Gregor5c37de72008-12-06 00:22:45 +0000558 }
559
Chris Lattner8a934232008-03-31 00:36:02 +0000560 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000561 Decl *D = 0;
562 LookupResult Lookup;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000563 if (SS && !SS->isEmpty()) {
564 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
565 if (DC == 0)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000566 return ExprError();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000567 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000568 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000569 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
570
Sebastian Redlcd965b92009-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 Gregor7176fff2009-01-15 00:26:24 +0000577 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000578
Chris Lattner8a934232008-03-31 00:36:02 +0000579 // If this reference is in an Objective-C method, then ivar lookup happens as
580 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000581 IdentifierInfo *II = Name.getAsIdentifierInfo();
582 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-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 Gregor4afa39d2009-01-20 01:17:11 +0000588 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000589 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000590 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-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 Redlcd965b92009-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 Jahanianefc4c4b2008-12-18 17:29:46 +0000598 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000599 return Owned(MRef);
Chris Lattner8a934232008-03-31 00:36:02 +0000600 }
601 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000602 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000603 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000604 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000605 getCurMethodDecl()->getClassInterface()));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000606 return Owned(new ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000607 }
Chris Lattner8a934232008-03-31 00:36:02 +0000608 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 if (D == 0) {
610 // Otherwise, this could be an implicitly declared function reference (legal
611 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000612 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000613 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000614 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 else {
616 // If this name wasn't predeclared and if this is not a function call,
617 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000618 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
620 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000621 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
622 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_use)
624 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000625 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000626 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 }
628 }
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000635
Douglas Gregor88a35142008-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 Gregorbcbffc42009-01-07 00:43:41 +0000676
677 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-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 Redlcd965b92009-01-18 18:53:16 +0000686 return Owned(new MemberExpr(This, true, cast<NamedDecl>(D),
687 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000688 }
689 }
690 }
691 }
692
Douglas Gregor44b43212008-12-11 16:49:14 +0000693 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-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 Redlcd965b92009-01-18 18:53:16 +0000697 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
698 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000699 }
700
Douglas Gregor88a35142008-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 Redlcd965b92009-01-18 18:53:16 +0000704 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
705 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000706 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000707
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000709 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000710 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000711 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000712 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000713 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000714
Steve Naroffdd972f22008-09-05 22:11:13 +0000715 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000717 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
718 false, false, SS));
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719
Steve Naroffdd972f22008-09-05 22:11:13 +0000720 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000721
Steve Naroffdd972f22008-09-05 22:11:13 +0000722 // check if referencing an identifier with __attribute__((deprecated)).
723 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000724 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
725
Douglas Gregorcaaf29a2008-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 Redlcd965b92009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_false)
734 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000735 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000736 ExprError(Diag(Loc, diag::warn_value_always_zero)
737 << Var->getDeclName());
Douglas Gregorcaaf29a2008-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 Naroffdd972f22008-09-05 22:11:13 +0000748
749 // Only create DeclRefExpr's for valid Decl's.
750 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000751 return ExprError();
752
Chris Lattner639e2d32008-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 Naroffdd972f22008-09-05 22:11:13 +0000757 //
Chris Lattner639e2d32008-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 Naroff090276f2008-10-10 01:28:17 +0000762 // The BlocksAttr indicates the variable is bound by-reference.
Steve Naroff0a473932009-01-20 19:53:53 +0000763 void *Mem = Context.getAllocator().Allocate<BlockDeclRefExpr>();
Steve Naroff090276f2008-10-10 01:28:17 +0000764 if (VD->getAttr<BlocksAttr>())
Steve Naroff0a473932009-01-20 19:53:53 +0000765 return Owned(new (Mem) BlockDeclRefExpr(VD,
766 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000767
Steve Naroff090276f2008-10-10 01:28:17 +0000768 // Variable will be bound by-copy, make it const within the closure.
769 VD->getType().addConst();
Steve Naroff0a473932009-01-20 19:53:53 +0000770 return Owned(new (Mem) BlockDeclRefExpr(VD,
771 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-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 Gregor898574e2008-12-05 23:32:09 +0000775
Douglas Gregor898574e2008-12-05 23:32:09 +0000776 bool TypeDependent = false;
Douglas Gregor83f96f62008-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 Gregorbcbffc42009-01-07 00:43:41 +0000795 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000796 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
797 if (Context.getTypeDeclType(Record)->isDependentType()) {
798 TypeDependent = true;
799 break;
800 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000801 }
802 }
803 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000804
Douglas Gregor83f96f62008-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 Gregor898574e2008-12-05 23:32:09 +0000818
Sebastian Redlcd965b92009-01-18 18:53:16 +0000819 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
820 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000821}
822
Sebastian Redlcd965b92009-01-18 18:53:16 +0000823Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
824 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000825 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000826
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000828 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000833
Chris Lattnerfa28b302008-01-12 08:14:25 +0000834 // Pre-defined identifiers are of type char[x], where x is the length of the
835 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000836 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000837 if (FunctionDecl *FD = getCurFunctionDecl())
838 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-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 Redlcd965b92009-01-18 18:53:16 +0000846
847
Chris Lattner8f978d52008-01-12 19:32:28 +0000848 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000849 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000850 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000851 return Owned(new PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000852}
853
Sebastian Redlcd965b92009-01-18 18:53:16 +0000854Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000855 llvm::SmallString<16> CharBuffer;
856 CharBuffer.resize(Tok.getLength());
857 const char *ThisTokBegin = &CharBuffer[0];
858 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000859
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
861 Tok.getLocation(), PP);
862 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000863 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000864
865 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
866
Steve Naroff0a473932009-01-20 19:53:53 +0000867 void *Mem = Context.getAllocator().Allocate<CharacterLiteral>();
868 return Owned(new (Mem) CharacterLiteral(Literal.getValue(), Literal.isWide(),
869 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000870}
871
Sebastian Redlcd965b92009-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
875 if (Tok.getLength() == 1) {
Chris Lattner0c21e842009-01-16 07:10:29 +0000876 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
877 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff0a473932009-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 }
Ted Kremenek28396602009-01-13 23:19:12 +0000882
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000884 // Add padding so that NumericLiteralParser can overread by one character.
885 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000887
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 // Get the spelling of the token, which eliminates trigraphs, etc.
889 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
892 Tok.getLocation(), PP);
893 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000894 return ExprError();
895
Chris Lattner5d661452007-08-26 03:42:43 +0000896 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000897
Chris Lattner5d661452007-08-26 03:42:43 +0000898 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000899 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000900 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000901 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000902 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000903 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000904 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000905 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000906
907 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
908
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000909 // isExact will be set by GetFloatValue().
910 bool isExact = false;
Steve Naroff0a473932009-01-20 19:53:53 +0000911 void *Mem = Context.getAllocator().Allocate<FloatingLiteral>();
912 Res = new (Mem) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
913 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000914
Chris Lattner5d661452007-08-26 03:42:43 +0000915 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000916 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000917 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000918 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000919
Neil Boothb9449512007-08-29 22:00:19 +0000920 // long long is a C99 feature.
921 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000922 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000923 Diag(Tok.getLocation(), diag::ext_longlong);
924
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000926 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000927
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 if (Literal.GetIntegerValue(ResultVal)) {
929 // If this value didn't fit into uintmax_t, warn and force to ull.
930 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000931 Ty = Context.UnsignedLongLongTy;
932 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000933 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000934 } else {
935 // If this value fits into a ULL, try to figure out what else it fits into
936 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000937
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 // Octal, Hexadecimal, and integers with a U suffix are allowed to
939 // be an unsigned int.
940 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
941
942 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000943 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000944 if (!Literal.isLong && !Literal.isLongLong) {
945 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000946 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000947
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 // Does it fit in a unsigned int?
949 if (ResultVal.isIntN(IntSize)) {
950 // Does it fit in a signed int?
951 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000952 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000954 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000955 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000958
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000960 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000961 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000962
Reid Spencer5f016e22007-07-11 17:01:13 +0000963 // Does it fit in a unsigned long?
964 if (ResultVal.isIntN(LongSize)) {
965 // Does it fit in a signed long?
966 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000967 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000969 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000970 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000972 }
973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000975 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000976 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 // Does it fit in a unsigned long long?
979 if (ResultVal.isIntN(LongLongSize)) {
980 // Does it fit in a signed long long?
981 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000982 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000984 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000985 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 }
987 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000988
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 // If we still couldn't decide a type, we probably have something that
990 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000991 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000993 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000994 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000996
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000997 if (ResultVal.getBitWidth() != Width)
998 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 }
Steve Naroff0a473932009-01-20 19:53:53 +00001000 void *Mem = Context.getAllocator().Allocate<IntegerLiteral>();
1001 Res = new (Mem) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001003
Chris Lattner5d661452007-08-26 03:42:43 +00001004 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1005 if (Literal.isImaginary)
1006 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001007
1008 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001009}
1010
Sebastian Redlcd965b92009-01-18 18:53:16 +00001011Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1012 SourceLocation R, ExprArg Val) {
1013 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001014 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff0a473932009-01-20 19:53:53 +00001015 void *Mem = Context.getAllocator().Allocate<ParenExpr>();
1016 return Owned(new (Mem) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001017}
1018
1019/// The UsualUnaryConversions() function is *not* called by this routine.
1020/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001021bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1022 SourceLocation OpLoc,
1023 const SourceRange &ExprRange,
1024 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 // C99 6.5.3.4p1:
1026 if (isa<FunctionType>(exprType) && isSizeof)
1027 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001028 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001030 Diag(OpLoc, diag::ext_sizeof_void_type)
1031 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001032 else
1033 return DiagnoseIncompleteType(OpLoc, exprType,
1034 isSizeof ? diag::err_sizeof_incomplete_type :
1035 diag::err_alignof_incomplete_type,
1036 ExprRange);
Sebastian Redl05189992008-11-11 17:56:53 +00001037
1038 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001039}
1040
Sebastian Redl05189992008-11-11 17:56:53 +00001041/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1042/// the same for @c alignof and @c __alignof
1043/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001044Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001045Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1046 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001047 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001048 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001049
Sebastian Redl05189992008-11-11 17:56:53 +00001050 QualType ArgTy;
1051 SourceRange Range;
1052 if (isType) {
1053 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1054 Range = ArgRange;
1055 } else {
1056 // Get the end location.
1057 Expr *ArgEx = (Expr *)TyOrEx;
1058 Range = ArgEx->getSourceRange();
1059 ArgTy = ArgEx->getType();
1060 }
1061
1062 // Verify that the operand is valid.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001063 // FIXME: This might leak the expression.
Sebastian Redl05189992008-11-11 17:56:53 +00001064 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001065 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001066
1067 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff0a473932009-01-20 19:53:53 +00001068 void *Mem = Context.getAllocator().Allocate<SizeOfAlignOfExpr>();
1069 return Owned(new (Mem) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001070 Context.getSizeType(), OpLoc,
1071 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001072}
1073
Chris Lattner5d794252007-08-24 21:41:10 +00001074QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001075 DefaultFunctionArrayConversion(V);
1076
Chris Lattnercc26ed72007-08-26 05:39:26 +00001077 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001078 if (const ComplexType *CT = V->getType()->getAsComplexType())
1079 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001080
1081 // Otherwise they pass through real integer and floating point types here.
1082 if (V->getType()->isArithmeticType())
1083 return V->getType();
1084
1085 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001086 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001087 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001088}
1089
1090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091
Sebastian Redl0eb23302009-01-19 00:08:26 +00001092Action::OwningExprResult
1093Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1094 tok::TokenKind Kind, ExprArg Input) {
1095 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 UnaryOperator::Opcode Opc;
1098 switch (Kind) {
1099 default: assert(0 && "Unknown unary op!");
1100 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1101 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1102 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001103
Douglas Gregor74253732008-11-19 15:42:04 +00001104 if (getLangOptions().CPlusPlus &&
1105 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1106 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001107 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001108 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1109
1110 // C++ [over.inc]p1:
1111 //
1112 // [...] If the function is a member function with one
1113 // parameter (which shall be of type int) or a non-member
1114 // function with two parameters (the second of which shall be
1115 // of type int), it defines the postfix increment operator ++
1116 // for objects of that type. When the postfix increment is
1117 // called as a result of using the ++ operator, the int
1118 // argument will have value zero.
1119 Expr *Args[2] = {
1120 Arg,
1121 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1122 /*isSigned=*/true),
1123 Context.IntTy, SourceLocation())
1124 };
1125
1126 // Build the candidate set for overloading
1127 OverloadCandidateSet CandidateSet;
1128 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1129
1130 // Perform overload resolution.
1131 OverloadCandidateSet::iterator Best;
1132 switch (BestViableFunction(CandidateSet, Best)) {
1133 case OR_Success: {
1134 // We found a built-in operator or an overloaded operator.
1135 FunctionDecl *FnDecl = Best->Function;
1136
1137 if (FnDecl) {
1138 // We matched an overloaded operator. Build a call to that
1139 // operator.
1140
1141 // Convert the arguments.
1142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1143 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001144 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001145 } else {
1146 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001147 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001148 FnDecl->getParamDecl(0)->getType(),
1149 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001150 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001151 }
1152
1153 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001154 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001155 = FnDecl->getType()->getAsFunctionType()->getResultType();
1156 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001157
Douglas Gregor74253732008-11-19 15:42:04 +00001158 // Build the actual expression node.
Steve Naroff0a473932009-01-20 19:53:53 +00001159 void *Mem = Context.getAllocator().Allocate<DeclRefExpr>();
1160 Expr *FnExpr = new (Mem) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001161 SourceLocation());
1162 UsualUnaryConversions(FnExpr);
1163
Sebastian Redl0eb23302009-01-19 00:08:26 +00001164 Input.release();
Steve Naroff0a473932009-01-20 19:53:53 +00001165 Mem = Context.getAllocator().Allocate<CXXOperatorCallExpr>();
1166 return Owned(new (Mem) CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
1167 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001168 } else {
1169 // We matched a built-in operator. Convert the arguments, then
1170 // break out so that we will build the appropriate built-in
1171 // operator node.
1172 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1173 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001174 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001175
1176 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001177 }
Douglas Gregor74253732008-11-19 15:42:04 +00001178 }
1179
1180 case OR_No_Viable_Function:
1181 // No viable function; fall through to handling this as a
1182 // built-in operator, which will produce an error message for us.
1183 break;
1184
1185 case OR_Ambiguous:
1186 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1187 << UnaryOperator::getOpcodeStr(Opc)
1188 << Arg->getSourceRange();
1189 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001190 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001191 }
1192
1193 // Either we found no viable overloaded operator or we matched a
1194 // built-in operator. In either case, fall through to trying to
1195 // build a built-in operation.
1196 }
1197
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001198 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1199 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001201 return ExprError();
1202 Input.release();
1203 return Owned(new UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001204}
1205
Sebastian Redl0eb23302009-01-19 00:08:26 +00001206Action::OwningExprResult
1207Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1208 ExprArg Idx, SourceLocation RLoc) {
1209 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1210 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001211
Douglas Gregor337c6b92008-11-19 17:17:41 +00001212 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001213 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001214 LHSExp->getType()->isEnumeralType() ||
1215 RHSExp->getType()->isRecordType() ||
1216 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001217 // Add the appropriate overloaded operators (C++ [over.match.oper])
1218 // to the candidate set.
1219 OverloadCandidateSet CandidateSet;
1220 Expr *Args[2] = { LHSExp, RHSExp };
1221 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001222
Douglas Gregor337c6b92008-11-19 17:17:41 +00001223 // Perform overload resolution.
1224 OverloadCandidateSet::iterator Best;
1225 switch (BestViableFunction(CandidateSet, Best)) {
1226 case OR_Success: {
1227 // We found a built-in operator or an overloaded operator.
1228 FunctionDecl *FnDecl = Best->Function;
1229
1230 if (FnDecl) {
1231 // We matched an overloaded operator. Build a call to that
1232 // operator.
1233
1234 // Convert the arguments.
1235 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1236 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1237 PerformCopyInitialization(RHSExp,
1238 FnDecl->getParamDecl(0)->getType(),
1239 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001240 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001241 } else {
1242 // Convert the arguments.
1243 if (PerformCopyInitialization(LHSExp,
1244 FnDecl->getParamDecl(0)->getType(),
1245 "passing") ||
1246 PerformCopyInitialization(RHSExp,
1247 FnDecl->getParamDecl(1)->getType(),
1248 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001249 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001250 }
1251
1252 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001253 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001254 = FnDecl->getType()->getAsFunctionType()->getResultType();
1255 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001256
Douglas Gregor337c6b92008-11-19 17:17:41 +00001257 // Build the actual expression node.
1258 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1259 SourceLocation());
1260 UsualUnaryConversions(FnExpr);
1261
Sebastian Redl0eb23302009-01-19 00:08:26 +00001262 Base.release();
1263 Idx.release();
1264 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001265 } else {
1266 // We matched a built-in operator. Convert the arguments, then
1267 // break out so that we will build the appropriate built-in
1268 // operator node.
1269 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1270 "passing") ||
1271 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1272 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001273 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001274
1275 break;
1276 }
1277 }
1278
1279 case OR_No_Viable_Function:
1280 // No viable function; fall through to handling this as a
1281 // built-in operator, which will produce an error message for us.
1282 break;
1283
1284 case OR_Ambiguous:
1285 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1286 << "[]"
1287 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1288 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001289 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001290 }
1291
1292 // Either we found no viable overloaded operator or we matched a
1293 // built-in operator. In either case, fall through to trying to
1294 // build a built-in operation.
1295 }
1296
Chris Lattner12d9ff62007-07-16 00:14:47 +00001297 // Perform default conversions.
1298 DefaultFunctionArrayConversion(LHSExp);
1299 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001300
Chris Lattner12d9ff62007-07-16 00:14:47 +00001301 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001304 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 // in the subscript position. As a result, we need to derive the array base
1306 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001307 Expr *BaseExpr, *IndexExpr;
1308 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001309 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001310 BaseExpr = LHSExp;
1311 IndexExpr = RHSExp;
1312 // FIXME: need to deal with const...
1313 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001314 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001315 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001316 BaseExpr = RHSExp;
1317 IndexExpr = LHSExp;
1318 // FIXME: need to deal with const...
1319 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001320 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1321 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001322 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001323
Chris Lattner12d9ff62007-07-16 00:14:47 +00001324 // FIXME: need to deal with const...
1325 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001327 return ExprError(Diag(LHSExp->getLocStart(),
1328 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1329 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001331 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001332 return ExprError(Diag(IndexExpr->getLocStart(),
1333 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001334
Chris Lattner12d9ff62007-07-16 00:14:47 +00001335 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1336 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001337 // void (*)(int)) and pointers to incomplete types. Functions are not
1338 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001339 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001340 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001341 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001342 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001343
Sebastian Redl0eb23302009-01-19 00:08:26 +00001344 Base.release();
1345 Idx.release();
1346 return Owned(new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001347}
1348
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001349QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001350CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001351 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001352 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001353
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001354 // The vector accessor can't exceed the number of elements.
1355 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001356
1357 // This flag determines whether or not the component is one of the four
1358 // special names that indicate a subset of exactly half the elements are
1359 // to be selected.
1360 bool HalvingSwizzle = false;
1361
1362 // This flag determines whether or not CompName has an 's' char prefix,
1363 // indicating that it is a string of hex values to be used as vector indices.
1364 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001365
1366 // Check that we've found one of the special components, or that the component
1367 // names must come from the same set.
1368 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001369 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1370 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001371 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001372 do
1373 compStr++;
1374 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001375 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001376 do
1377 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001378 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001379 }
Nate Begeman353417a2009-01-18 01:47:54 +00001380
1381 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001382 // We didn't get to the end of the string. This means the component names
1383 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001384 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1385 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001386 return QualType();
1387 }
Nate Begeman353417a2009-01-18 01:47:54 +00001388
1389 // Ensure no component accessor exceeds the width of the vector type it
1390 // operates on.
1391 if (!HalvingSwizzle) {
1392 compStr = CompName.getName();
1393
1394 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001395 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001396
1397 while (*compStr) {
1398 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1399 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1400 << baseType << SourceRange(CompLoc);
1401 return QualType();
1402 }
1403 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001404 }
Nate Begeman8a997642008-05-09 06:41:27 +00001405
Nate Begeman353417a2009-01-18 01:47:54 +00001406 // If this is a halving swizzle, verify that the base type has an even
1407 // number of elements.
1408 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001409 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001410 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001411 return QualType();
1412 }
1413
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001414 // The component accessor looks fine - now we need to compute the actual type.
1415 // The vector type is implied by the component accessor. For example,
1416 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001417 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001418 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001419 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1420 : CompName.getLength();
1421 if (HexSwizzle)
1422 CompSize--;
1423
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001424 if (CompSize == 1)
1425 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001426
Nate Begeman213541a2008-04-18 23:10:10 +00001427 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001428 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001429 // diagostics look bad. We want extended vector types to appear built-in.
1430 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1431 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1432 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001433 }
1434 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001435}
1436
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001437/// constructSetterName - Return the setter name for the given
1438/// identifier, i.e. "set" + Name where the initial character of Name
1439/// has been capitalized.
1440// FIXME: Merge with same routine in Parser. But where should this
1441// live?
1442static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1443 const IdentifierInfo *Name) {
1444 llvm::SmallString<100> SelectorName;
1445 SelectorName = "set";
1446 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1447 SelectorName[3] = toupper(SelectorName[3]);
1448 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1449}
1450
Sebastian Redl0eb23302009-01-19 00:08:26 +00001451Action::OwningExprResult
1452Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1453 tok::TokenKind OpKind, SourceLocation MemberLoc,
1454 IdentifierInfo &Member) {
1455 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001456 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001457
1458 // Perform default conversions.
1459 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001460
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001461 QualType BaseType = BaseExpr->getType();
1462 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001463
Chris Lattner68a057b2008-07-21 04:36:39 +00001464 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1465 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001467 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001468 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001469 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001470 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1471 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001472 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001473 return ExprError(Diag(MemberLoc,
1474 diag::err_typecheck_member_reference_arrow)
1475 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001477
Chris Lattner68a057b2008-07-21 04:36:39 +00001478 // Handle field access to simple records. This also handles access to fields
1479 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001480 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001481 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001482 if (DiagnoseIncompleteType(OpLoc, BaseType,
1483 diag::err_typecheck_incomplete_tag,
1484 BaseExpr->getSourceRange()))
1485 return ExprError();
1486
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001487 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001488 // FIXME: Qualified name lookup for C++ is a bit more complicated
1489 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001490 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001491 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1492 LookupCriteria(LookupCriteria::Member,
1493 /*RedeclarationOnly=*/false,
1494 getLangOptions().CPlusPlus));
1495
1496 Decl *MemberDecl = 0;
1497 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001498 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1499 << &Member << BaseExpr->getSourceRange());
1500 else if (Result.isAmbiguous()) {
1501 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1502 MemberLoc, BaseExpr->getSourceRange());
1503 return ExprError();
1504 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001505 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001506
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001507 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001508 // We may have found a field within an anonymous union or struct
1509 // (C++ [class.union]).
1510 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001511 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001512 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001513
Douglas Gregor86f19402008-12-20 23:49:58 +00001514 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1515 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001516 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001517 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1518 MemberType = Ref->getPointeeType();
1519 else {
1520 unsigned combinedQualifiers =
1521 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001522 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001523 combinedQualifiers &= ~QualType::Const;
1524 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1525 }
Eli Friedman51019072008-02-06 22:48:16 +00001526
Sebastian Redl0eb23302009-01-19 00:08:26 +00001527 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1528 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001529 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001530 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow,
1531 Var, MemberLoc,
1532 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001533 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001534 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn,
1535 MemberLoc, MemberFn->getType()));
1536 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001537 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001538 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1539 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001540 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001541 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
1542 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001543 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001544 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1545 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001546
Douglas Gregor86f19402008-12-20 23:49:58 +00001547 // We found a declaration kind that we didn't expect. This is a
1548 // generic error message that tells the user that she can't refer
1549 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001550 return ExprError(Diag(MemberLoc,
1551 diag::err_typecheck_member_reference_unknown)
1552 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001553 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001554
Chris Lattnera38e6b12008-07-21 04:59:05 +00001555 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1556 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001557 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001558 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001559 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1560 BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001561 OpKind == tok::arrow);
1562 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001563 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001564 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001565 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1566 << IFTy->getDecl()->getDeclName() << &Member
1567 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001568 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001569
Chris Lattnera38e6b12008-07-21 04:59:05 +00001570 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1571 // pointer to a (potentially qualified) interface type.
1572 const PointerType *PTy;
1573 const ObjCInterfaceType *IFTy;
1574 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1575 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1576 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001577
Daniel Dunbar2307d312008-09-03 01:05:41 +00001578 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001579 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001580 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1581 MemberLoc, BaseExpr));
1582
Daniel Dunbar2307d312008-09-03 01:05:41 +00001583 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001584 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1585 E = IFTy->qual_end(); I != E; ++I)
1586 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001587 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1588 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001589
1590 // If that failed, look for an "implicit" property by seeing if the nullary
1591 // selector is implemented.
1592
1593 // FIXME: The logic for looking up nullary and unary selectors should be
1594 // shared with the code in ActOnInstanceMessage.
1595
1596 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1597 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001598
Daniel Dunbar2307d312008-09-03 01:05:41 +00001599 // If this reference is in an @implementation, check for 'private' methods.
1600 if (!Getter)
1601 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1602 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1603 if (ObjCImplementationDecl *ImpDecl =
1604 ObjCImplementations[ClassDecl->getIdentifier()])
1605 Getter = ImpDecl->getInstanceMethod(Sel);
1606
Steve Naroff7692ed62008-10-22 19:16:27 +00001607 // Look through local category implementations associated with the class.
1608 if (!Getter) {
1609 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1610 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1611 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1612 }
1613 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001614 if (Getter) {
1615 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001616 // will look for the matching setter, in case it is needed.
1617 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1618 &Member);
1619 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1620 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1621 if (!Setter) {
1622 // If this reference is in an @implementation, also check for 'private'
1623 // methods.
1624 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1625 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1626 if (ObjCImplementationDecl *ImpDecl =
1627 ObjCImplementations[ClassDecl->getIdentifier()])
1628 Setter = ImpDecl->getInstanceMethod(SetterSel);
1629 }
1630 // Look through local category implementations associated with the class.
1631 if (!Setter) {
1632 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1633 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1634 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1635 }
1636 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001637
1638 // FIXME: we must check that the setter has property type.
1639 return Owned(new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
1640 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001641 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001642
1643 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1644 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001645 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001646 // Handle properties on qualified "id" protocols.
1647 const ObjCQualifiedIdType *QIdTy;
1648 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1649 // Check protocols on qualified interfaces.
1650 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001651 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001652 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001653 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1654 MemberLoc, BaseExpr));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001655 // Also must look for a getter name which uses property syntax.
1656 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1657 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001658 return Owned(new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(),
1659 OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001660 }
1661 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001662
1663 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1664 << &Member << BaseType);
1665 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001666 // Handle 'field access' to vectors, such as 'V.xx'.
1667 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001668 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1669 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001670 return ExprError();
1671 return Owned(new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001672 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001673
1674 return ExprError(Diag(MemberLoc,
1675 diag::err_typecheck_member_reference_struct_union)
1676 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001677}
1678
Douglas Gregor88a35142008-12-22 05:46:06 +00001679/// ConvertArgumentsForCall - Converts the arguments specified in
1680/// Args/NumArgs to the parameter types of the function FDecl with
1681/// function prototype Proto. Call is the call expression itself, and
1682/// Fn is the function expression. For a C++ member function, this
1683/// routine does not attempt to convert the object argument. Returns
1684/// true if the call is ill-formed.
1685bool
1686Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1687 FunctionDecl *FDecl,
1688 const FunctionTypeProto *Proto,
1689 Expr **Args, unsigned NumArgs,
1690 SourceLocation RParenLoc) {
1691 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1692 // assignment, to the types of the corresponding parameter, ...
1693 unsigned NumArgsInProto = Proto->getNumArgs();
1694 unsigned NumArgsToCheck = NumArgs;
1695
1696 // If too few arguments are available (and we don't have default
1697 // arguments for the remaining parameters), don't make the call.
1698 if (NumArgs < NumArgsInProto) {
1699 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1700 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1701 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1702 // Use default arguments for missing arguments
1703 NumArgsToCheck = NumArgsInProto;
1704 Call->setNumArgs(NumArgsInProto);
1705 }
1706
1707 // If too many are passed and not variadic, error on the extras and drop
1708 // them.
1709 if (NumArgs > NumArgsInProto) {
1710 if (!Proto->isVariadic()) {
1711 Diag(Args[NumArgsInProto]->getLocStart(),
1712 diag::err_typecheck_call_too_many_args)
1713 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1714 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1715 Args[NumArgs-1]->getLocEnd());
1716 // This deletes the extra arguments.
1717 Call->setNumArgs(NumArgsInProto);
1718 }
1719 NumArgsToCheck = NumArgsInProto;
1720 }
1721
1722 // Continue to check argument types (even if we have too few/many args).
1723 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1724 QualType ProtoArgType = Proto->getArgType(i);
1725
1726 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001727 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001728 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001729
1730 // Pass the argument.
1731 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1732 return true;
1733 } else
1734 // We already type-checked the argument, so we know it works.
Douglas Gregor88a35142008-12-22 05:46:06 +00001735 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1736 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001737
Douglas Gregor88a35142008-12-22 05:46:06 +00001738 Call->setArg(i, Arg);
1739 }
1740
1741 // If this is a variadic call, handle args passed through "...".
1742 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001743 VariadicCallType CallType = VariadicFunction;
1744 if (Fn->getType()->isBlockPointerType())
1745 CallType = VariadicBlock; // Block
1746 else if (isa<MemberExpr>(Fn))
1747 CallType = VariadicMethod;
1748
Douglas Gregor88a35142008-12-22 05:46:06 +00001749 // Promote the arguments (C99 6.5.2.2p7).
1750 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1751 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001752 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001753 Call->setArg(i, Arg);
1754 }
1755 }
1756
1757 return false;
1758}
1759
Steve Narofff69936d2007-09-16 03:34:24 +00001760/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001761/// This provides the location of the left/right parens and a list of comma
1762/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001763Action::OwningExprResult
1764Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1765 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001766 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001767 unsigned NumArgs = args.size();
1768 Expr *Fn = static_cast<Expr *>(fn.release());
1769 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001770 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001771 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001772 OverloadedFunctionDecl *Ovl = NULL;
1773
Douglas Gregor5c37de72008-12-06 00:22:45 +00001774 // Determine whether this is a dependent call inside a C++ template,
1775 // in which case we won't do any semantic analysis now.
1776 bool Dependent = false;
1777 if (Fn->isTypeDependent()) {
1778 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1779 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1780 Dependent = true;
1781 else {
1782 // Resolve the CXXDependentNameExpr to an actual identifier;
1783 // it wasn't really a dependent name after all.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001784 OwningExprResult Resolved
1785 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1786 FnName->getName(),
Douglas Gregor5c37de72008-12-06 00:22:45 +00001787 /*HasTrailingLParen=*/true,
1788 /*SS=*/0,
1789 /*ForceResolution=*/true);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001790 if (Resolved.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001791 return ExprError();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001792 else {
1793 delete Fn;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001794 Fn = (Expr *)Resolved.release();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001795 }
1796 }
1797 } else
1798 Dependent = true;
1799 } else
1800 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1801
Douglas Gregor898574e2008-12-05 23:32:09 +00001802 // FIXME: Will need to cache the results of name lookup (including
1803 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001804 if (Dependent)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001805 return Owned(new CallExpr(Fn, Args, NumArgs,
1806 Context.DependentTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001807
Douglas Gregor88a35142008-12-22 05:46:06 +00001808 // Determine whether this is a call to an object (C++ [over.call.object]).
1809 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001810 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1811 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001812
1813 // Determine whether this is a call to a member function.
1814 if (getLangOptions().CPlusPlus) {
1815 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1816 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1817 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001818 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1819 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001820 }
1821
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001822 // If we're directly calling a function or a set of overloaded
1823 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001824 DeclRefExpr *DRExpr = NULL;
1825 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1826 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1827 else
1828 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001829
Douglas Gregor1a49af92009-01-06 05:10:23 +00001830 if (DRExpr) {
1831 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1832 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001833 }
1834
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001835 if (Ovl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001836 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1837 CommaLocs, RParenLoc);
Douglas Gregor0a396682008-11-26 06:01:48 +00001838 if (!FDecl)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001839 return ExprError();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001840
Douglas Gregor0a396682008-11-26 06:01:48 +00001841 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001842 Expr *NewFn = 0;
1843 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1844 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1845 QDRExpr->getLocation(), false, false,
1846 QDRExpr->getSourceRange().getBegin());
1847 else
1848 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1849 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001850 Fn->Destroy(Context);
1851 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001852 }
Chris Lattner04421082008-04-08 04:40:51 +00001853
1854 // Promote the function operand.
1855 UsualUnaryConversions(Fn);
1856
Chris Lattner925e60d2007-12-28 05:29:59 +00001857 // Make the call expr early, before semantic checks. This guarantees cleanup
1858 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001859 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1860 // Destroy(), or nothing gets cleaned up.
Chris Lattner8123a952008-04-10 02:22:51 +00001861 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001862 Context.BoolTy, RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001863
Steve Naroffdd972f22008-09-05 22:11:13 +00001864 const FunctionType *FuncT;
1865 if (!Fn->getType()->isBlockPointerType()) {
1866 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1867 // have type pointer to function".
1868 const PointerType *PT = Fn->getType()->getAsPointerType();
1869 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001870 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1871 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00001872 FuncT = PT->getPointeeType()->getAsFunctionType();
1873 } else { // This is a block call.
1874 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1875 getAsFunctionType();
1876 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001877 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001878 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1879 << Fn->getType() << Fn->getSourceRange());
1880
Chris Lattner925e60d2007-12-28 05:29:59 +00001881 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001882 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001883
Chris Lattner925e60d2007-12-28 05:29:59 +00001884 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001885 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1886 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001887 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00001888 } else {
1889 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001890
Steve Naroffb291ab62007-08-28 23:30:39 +00001891 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001892 for (unsigned i = 0; i != NumArgs; i++) {
1893 Expr *Arg = Args[i];
1894 DefaultArgumentPromotion(Arg);
1895 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001896 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001898
Douglas Gregor88a35142008-12-22 05:46:06 +00001899 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1900 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001901 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1902 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00001903
Chris Lattner59907c42007-08-10 20:18:51 +00001904 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001905 if (FDecl)
1906 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001907
Sebastian Redl0eb23302009-01-19 00:08:26 +00001908 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001909}
1910
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001911Action::OwningExprResult
1912Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1913 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001914 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001915 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001916 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001917 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001918 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00001919
Eli Friedman6223c222008-05-20 05:22:08 +00001920 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001921 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001922 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1923 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001924 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1925 diag::err_typecheck_decl_incomplete_type,
1926 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001927 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00001928
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001929 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001930 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001931 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00001932
Chris Lattner371f2582008-12-04 23:50:19 +00001933 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001934 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001935 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001936 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001937 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001938 InitExpr.release();
1939 return Owned(new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1940 isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00001941}
1942
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001943Action::OwningExprResult
1944Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1945 InitListDesignations &Designators,
1946 SourceLocation RBraceLoc) {
1947 unsigned NumInit = initlist.size();
1948 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001949
Steve Naroff08d92e42007-09-15 18:49:24 +00001950 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001951 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001952
Chris Lattner418f6c72008-10-26 23:43:26 +00001953 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1954 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001955 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001956 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001957}
1958
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001959/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001960bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001961 UsualUnaryConversions(castExpr);
1962
1963 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1964 // type needs to be scalar.
1965 if (castType->isVoidType()) {
1966 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001967 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1968 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001969 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00001970 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1971 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1972 (castType->isStructureType() || castType->isUnionType())) {
1973 // GCC struct/union extension: allow cast to self.
1974 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1975 << castType << castExpr->getSourceRange();
1976 } else if (castType->isUnionType()) {
1977 // GCC cast to union extension
1978 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1979 RecordDecl::field_iterator Field, FieldEnd;
1980 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1981 Field != FieldEnd; ++Field) {
1982 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1983 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1984 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1985 << castExpr->getSourceRange();
1986 break;
1987 }
1988 }
1989 if (Field == FieldEnd)
1990 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1991 << castExpr->getType() << castExpr->getSourceRange();
1992 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001993 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001994 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001995 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001996 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001997 } else if (!castExpr->getType()->isScalarType() &&
1998 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001999 return Diag(castExpr->getLocStart(),
2000 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002001 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002002 } else if (castExpr->getType()->isVectorType()) {
2003 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2004 return true;
2005 } else if (castType->isVectorType()) {
2006 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2007 return true;
2008 }
2009 return false;
2010}
2011
Chris Lattnerfe23e212007-12-20 00:44:32 +00002012bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002013 assert(VectorTy->isVectorType() && "Not a vector type!");
2014
2015 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002016 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002017 return Diag(R.getBegin(),
2018 Ty->isVectorType() ?
2019 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002020 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002021 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002022 } else
2023 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002024 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002025 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002026
2027 return false;
2028}
2029
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002030Action::OwningExprResult
2031Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2032 SourceLocation RParenLoc, ExprArg Op) {
2033 assert((Ty != 0) && (Op.get() != 0) &&
2034 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002035
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002036 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002037 QualType castType = QualType::getFromOpaquePtr(Ty);
2038
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002039 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002040 return ExprError();
2041 return Owned(new CStyleCastExpr(castType, castExpr, castType,
2042 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002043}
2044
Chris Lattnera21ddb32007-11-26 01:40:58 +00002045/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2046/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002047inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002048 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002049 UsualUnaryConversions(cond);
2050 UsualUnaryConversions(lex);
2051 UsualUnaryConversions(rex);
2052 QualType condT = cond->getType();
2053 QualType lexT = lex->getType();
2054 QualType rexT = rex->getType();
2055
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002057 if (!cond->isTypeDependent()) {
2058 if (!condT->isScalarType()) { // C99 6.5.15p2
2059 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2060 return QualType();
2061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002063
2064 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002065 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2066 return Context.DependentTy;
2067
Chris Lattner70d67a92008-01-06 22:42:25 +00002068 // If both operands have arithmetic type, do the usual arithmetic conversions
2069 // to find a common type: C99 6.5.15p3,5.
2070 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002071 UsualArithmeticConversions(lex, rex);
2072 return lex->getType();
2073 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002074
2075 // If both operands are the same structure or union type, the result is that
2076 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002077 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002078 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002079 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002080 // "If both the operands have structure or union type, the result has
2081 // that type." This implies that CV qualifiers are dropped.
2082 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002084
2085 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002086 // The following || allows only one side to be void (a GCC-ism).
2087 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002088 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002089 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2090 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002091 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002092 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2093 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002094 ImpCastExprToType(lex, Context.VoidTy);
2095 ImpCastExprToType(rex, Context.VoidTy);
2096 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002097 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002098 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2099 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002100 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2101 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002102 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002103 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002104 return lexT;
2105 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002106 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2107 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002108 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002109 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002110 return rexT;
2111 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002112 // Handle the case where both operands are pointers before we handle null
2113 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002114 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2115 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2116 // get the "pointed to" types
2117 QualType lhptee = LHSPT->getPointeeType();
2118 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002119
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002120 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2121 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002122 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002123 // Figure out necessary qualifiers (C99 6.5.15p6)
2124 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002125 QualType destType = Context.getPointerType(destPointee);
2126 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2127 ImpCastExprToType(rex, destType); // promote to void*
2128 return destType;
2129 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002130 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002131 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002132 QualType destType = Context.getPointerType(destPointee);
2133 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2134 ImpCastExprToType(rex, destType); // promote to void*
2135 return destType;
2136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002137
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002138 QualType compositeType = lexT;
2139
2140 // If either type is an Objective-C object type then check
2141 // compatibility according to Objective-C.
2142 if (Context.isObjCObjectPointerType(lexT) ||
2143 Context.isObjCObjectPointerType(rexT)) {
2144 // If both operands are interfaces and either operand can be
2145 // assigned to the other, use that type as the composite
2146 // type. This allows
2147 // xxx ? (A*) a : (B*) b
2148 // where B is a subclass of A.
2149 //
2150 // Additionally, as for assignment, if either type is 'id'
2151 // allow silent coercion. Finally, if the types are
2152 // incompatible then make sure to use 'id' as the composite
2153 // type so the result is acceptable for sending messages to.
2154
2155 // FIXME: This code should not be localized to here. Also this
2156 // should use a compatible check instead of abusing the
2157 // canAssignObjCInterfaces code.
2158 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2159 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2160 if (LHSIface && RHSIface &&
2161 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2162 compositeType = lexT;
2163 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002164 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002165 compositeType = rexT;
2166 } else if (Context.isObjCIdType(lhptee) ||
2167 Context.isObjCIdType(rhptee)) {
2168 // FIXME: This code looks wrong, because isObjCIdType checks
2169 // the struct but getObjCIdType returns the pointer to
2170 // struct. This is horrible and should be fixed.
2171 compositeType = Context.getObjCIdType();
2172 } else {
2173 QualType incompatTy = Context.getObjCIdType();
2174 ImpCastExprToType(lex, incompatTy);
2175 ImpCastExprToType(rex, incompatTy);
2176 return incompatTy;
2177 }
2178 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2179 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002180 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002181 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002182 // In this situation, we assume void* type. No especially good
2183 // reason, but this is what gcc does, and we do have to pick
2184 // to get a consistent AST.
2185 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002186 ImpCastExprToType(lex, incompatTy);
2187 ImpCastExprToType(rex, incompatTy);
2188 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002189 }
2190 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002191 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2192 // differently qualified versions of compatible types, the result type is
2193 // a pointer to an appropriately qualified version of the *composite*
2194 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002195 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002196 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002197 ImpCastExprToType(lex, compositeType);
2198 ImpCastExprToType(rex, compositeType);
2199 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 }
2201 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002202 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2203 // evaluates to "struct objc_object *" (and is handled above when comparing
2204 // id with statically typed objects).
2205 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2206 // GCC allows qualified id and any Objective-C type to devolve to
2207 // id. Currently localizing to here until clear this should be
2208 // part of ObjCQualifiedIdTypesAreCompatible.
2209 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2210 (lexT->isObjCQualifiedIdType() &&
2211 Context.isObjCObjectPointerType(rexT)) ||
2212 (rexT->isObjCQualifiedIdType() &&
2213 Context.isObjCObjectPointerType(lexT))) {
2214 // FIXME: This is not the correct composite type. This only
2215 // happens to work because id can more or less be used anywhere,
2216 // however this may change the type of method sends.
2217 // FIXME: gcc adds some type-checking of the arguments and emits
2218 // (confusing) incompatible comparison warnings in some
2219 // cases. Investigate.
2220 QualType compositeType = Context.getObjCIdType();
2221 ImpCastExprToType(lex, compositeType);
2222 ImpCastExprToType(rex, compositeType);
2223 return compositeType;
2224 }
2225 }
2226
Steve Naroff61f40a22008-09-10 19:17:48 +00002227 // Selection between block pointer types is ok as long as they are the same.
2228 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2229 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2230 return lexT;
2231
Chris Lattner70d67a92008-01-06 22:42:25 +00002232 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002233 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002234 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 return QualType();
2236}
2237
Steve Narofff69936d2007-09-16 03:34:24 +00002238/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002239/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002240Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2241 SourceLocation ColonLoc,
2242 ExprArg Cond, ExprArg LHS,
2243 ExprArg RHS) {
2244 Expr *CondExpr = (Expr *) Cond.get();
2245 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002246
2247 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2248 // was the condition.
2249 bool isLHSNull = LHSExpr == 0;
2250 if (isLHSNull)
2251 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002252
2253 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002254 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002256 return ExprError();
2257
2258 Cond.release();
2259 LHS.release();
2260 RHS.release();
2261 return Owned(new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2262 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002263}
2264
Reid Spencer5f016e22007-07-11 17:01:13 +00002265
2266// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2267// being closely modeled after the C99 spec:-). The odd characteristic of this
2268// routine is it effectively iqnores the qualifiers on the top level pointee.
2269// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2270// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002271Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002272Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2273 QualType lhptee, rhptee;
2274
2275 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002276 lhptee = lhsType->getAsPointerType()->getPointeeType();
2277 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002278
2279 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002280 lhptee = Context.getCanonicalType(lhptee);
2281 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002282
Chris Lattner5cf216b2008-01-04 18:04:52 +00002283 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002284
2285 // C99 6.5.16.1p1: This following citation is common to constraints
2286 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2287 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002288 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002289 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002290 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002291
2292 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2293 // incomplete type and the other is a pointer to a qualified or unqualified
2294 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002295 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002296 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002297 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002298
2299 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002300 assert(rhptee->isFunctionType());
2301 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002302 }
2303
2304 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002305 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002306 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002307
2308 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002309 assert(lhptee->isFunctionType());
2310 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002311 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002312
2313 // Check for ObjC interfaces
2314 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2315 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2316 if (LHSIface && RHSIface &&
2317 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2318 return ConvTy;
2319
2320 // ID acts sort of like void* for ObjC interfaces
2321 if (LHSIface && Context.isObjCIdType(rhptee))
2322 return ConvTy;
2323 if (RHSIface && Context.isObjCIdType(lhptee))
2324 return ConvTy;
2325
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2327 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002328 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2329 rhptee.getUnqualifiedType()))
2330 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002331 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002332}
2333
Steve Naroff1c7d0672008-09-04 15:10:53 +00002334/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2335/// block pointer types are compatible or whether a block and normal pointer
2336/// are compatible. It is more restrict than comparing two function pointer
2337// types.
2338Sema::AssignConvertType
2339Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2340 QualType rhsType) {
2341 QualType lhptee, rhptee;
2342
2343 // get the "pointed to" type (ignoring qualifiers at the top level)
2344 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2345 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2346
2347 // make sure we operate on the canonical type
2348 lhptee = Context.getCanonicalType(lhptee);
2349 rhptee = Context.getCanonicalType(rhptee);
2350
2351 AssignConvertType ConvTy = Compatible;
2352
2353 // For blocks we enforce that qualifiers are identical.
2354 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2355 ConvTy = CompatiblePointerDiscardsQualifiers;
2356
2357 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2358 return IncompatibleBlockPointer;
2359 return ConvTy;
2360}
2361
Reid Spencer5f016e22007-07-11 17:01:13 +00002362/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2363/// has code to accommodate several GCC extensions when type checking
2364/// pointers. Here are some objectionable examples that GCC considers warnings:
2365///
2366/// int a, *pint;
2367/// short *pshort;
2368/// struct foo *pfoo;
2369///
2370/// pint = pshort; // warning: assignment from incompatible pointer type
2371/// a = pint; // warning: assignment makes integer from pointer without a cast
2372/// pint = a; // warning: assignment makes pointer from integer without a cast
2373/// pint = pfoo; // warning: assignment from incompatible pointer type
2374///
2375/// As a result, the code for dealing with pointers is more complex than the
2376/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002377///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002378Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002379Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002380 // Get canonical types. We're not formatting these types, just comparing
2381 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002382 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2383 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002384
2385 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002386 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002387
Douglas Gregor9d293df2008-10-28 00:22:11 +00002388 // If the left-hand side is a reference type, then we are in a
2389 // (rare!) case where we've allowed the use of references in C,
2390 // e.g., as a parameter type in a built-in function. In this case,
2391 // just make sure that the type referenced is compatible with the
2392 // right-hand side type. The caller is responsible for adjusting
2393 // lhsType so that the resulting expression does not have reference
2394 // type.
2395 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2396 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002397 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002398 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002399 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002400
Chris Lattnereca7be62008-04-07 05:30:13 +00002401 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2402 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002403 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002404 // Relax integer conversions like we do for pointers below.
2405 if (rhsType->isIntegerType())
2406 return IntToPointer;
2407 if (lhsType->isIntegerType())
2408 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002409 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002410 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002411
Nate Begemanbe2341d2008-07-14 18:02:46 +00002412 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002413 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002414 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2415 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002416 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002417
Nate Begemanbe2341d2008-07-14 18:02:46 +00002418 // If we are allowing lax vector conversions, and LHS and RHS are both
2419 // vectors, the total size only needs to be the same. This is a bitcast;
2420 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002421 if (getLangOptions().LaxVectorConversions &&
2422 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002423 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2424 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002425 }
2426 return Incompatible;
2427 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002428
Chris Lattnere8b3e962008-01-04 23:32:24 +00002429 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002431
Chris Lattner78eca282008-04-07 06:49:41 +00002432 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002433 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002434 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002435
Chris Lattner78eca282008-04-07 06:49:41 +00002436 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002437 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002438
Steve Naroffb4406862008-09-29 18:10:17 +00002439 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002440 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002441 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002442
2443 // Treat block pointers as objects.
2444 if (getLangOptions().ObjC1 &&
2445 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2446 return Compatible;
2447 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002448 return Incompatible;
2449 }
2450
2451 if (isa<BlockPointerType>(lhsType)) {
2452 if (rhsType->isIntegerType())
2453 return IntToPointer;
2454
Steve Naroffb4406862008-09-29 18:10:17 +00002455 // Treat block pointers as objects.
2456 if (getLangOptions().ObjC1 &&
2457 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2458 return Compatible;
2459
Steve Naroff1c7d0672008-09-04 15:10:53 +00002460 if (rhsType->isBlockPointerType())
2461 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2462
2463 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2464 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002465 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002466 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002467 return Incompatible;
2468 }
2469
Chris Lattner78eca282008-04-07 06:49:41 +00002470 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002472 if (lhsType == Context.BoolTy)
2473 return Compatible;
2474
2475 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002476 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002477
Chris Lattner78eca282008-04-07 06:49:41 +00002478 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002480
2481 if (isa<BlockPointerType>(lhsType) &&
2482 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002483 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002484 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002485 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002486
Chris Lattnerfc144e22008-01-04 23:18:45 +00002487 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002488 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002489 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 }
2491 return Incompatible;
2492}
2493
Chris Lattner5cf216b2008-01-04 18:04:52 +00002494Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002495Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002496 if (getLangOptions().CPlusPlus) {
2497 if (!lhsType->isRecordType()) {
2498 // C++ 5.17p3: If the left operand is not of class type, the
2499 // expression is implicitly converted (C++ 4) to the
2500 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002501 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2502 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002503 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002504 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002505 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002506 }
2507
2508 // FIXME: Currently, we fall through and treat C++ classes like C
2509 // structures.
2510 }
2511
Steve Naroff529a4ad2007-11-27 17:58:44 +00002512 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2513 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002514 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2515 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002516 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002517 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002518 return Compatible;
2519 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002520
2521 // We don't allow conversion of non-null-pointer constants to integers.
2522 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2523 return IntToBlockPointer;
2524
Chris Lattner943140e2007-10-16 02:55:40 +00002525 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002526 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002527 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002528 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002529 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002530 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002531 if (!lhsType->isReferenceType())
2532 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002533
Chris Lattner5cf216b2008-01-04 18:04:52 +00002534 Sema::AssignConvertType result =
2535 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002536
2537 // C99 6.5.16.1p2: The value of the right operand is converted to the
2538 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002539 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2540 // so that we can use references in built-in functions even in C.
2541 // The getNonReferenceType() call makes sure that the resulting expression
2542 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002543 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002544 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002545 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002546}
2547
Chris Lattner5cf216b2008-01-04 18:04:52 +00002548Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002549Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2550 return CheckAssignmentConstraints(lhsType, rhsType);
2551}
2552
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002553QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002554 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002555 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002556 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002557 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002558}
2559
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002560inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002561 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002562 // For conversion purposes, we ignore any qualifiers.
2563 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002564 QualType lhsType =
2565 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2566 QualType rhsType =
2567 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002568
Nate Begemanbe2341d2008-07-14 18:02:46 +00002569 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002570 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002572
Nate Begemanbe2341d2008-07-14 18:02:46 +00002573 // Handle the case of a vector & extvector type of the same size and element
2574 // type. It would be nice if we only had one vector type someday.
2575 if (getLangOptions().LaxVectorConversions)
2576 if (const VectorType *LV = lhsType->getAsVectorType())
2577 if (const VectorType *RV = rhsType->getAsVectorType())
2578 if (LV->getElementType() == RV->getElementType() &&
2579 LV->getNumElements() == RV->getNumElements())
2580 return lhsType->isExtVectorType() ? lhsType : rhsType;
2581
2582 // If the lhs is an extended vector and the rhs is a scalar of the same type
2583 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002584 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002585 QualType eltType = V->getElementType();
2586
2587 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2588 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2589 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002590 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002591 return lhsType;
2592 }
2593 }
2594
Nate Begemanbe2341d2008-07-14 18:02:46 +00002595 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002596 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002597 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002598 QualType eltType = V->getElementType();
2599
2600 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2601 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2602 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002603 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002604 return rhsType;
2605 }
2606 }
2607
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002609 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002610 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002611 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 return QualType();
2613}
2614
2615inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002616 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002617{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002618 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002619 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002620
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002621 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002622
Steve Naroffa4332e22007-07-17 00:58:39 +00002623 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002624 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002625 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002626}
2627
2628inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002629 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002630{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002631 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2632 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2633 return CheckVectorOperands(Loc, lex, rex);
2634 return InvalidOperands(Loc, lex, rex);
2635 }
Steve Naroff90045e82007-07-13 23:32:42 +00002636
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002637 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002638
Steve Naroffa4332e22007-07-17 00:58:39 +00002639 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002640 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002641 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002642}
2643
2644inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002645 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002646{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002647 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002648 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002649
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002650 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002651
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002653 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002654 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002655
Eli Friedmand72d16e2008-05-18 18:08:51 +00002656 // Put any potential pointer into PExp
2657 Expr* PExp = lex, *IExp = rex;
2658 if (IExp->getType()->isPointerType())
2659 std::swap(PExp, IExp);
2660
2661 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2662 if (IExp->getType()->isIntegerType()) {
2663 // Check for arithmetic on pointers to incomplete types
2664 if (!PTy->getPointeeType()->isObjectType()) {
2665 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002666 Diag(Loc, diag::ext_gnu_void_ptr)
2667 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002668 } else if (PTy->getPointeeType()->isFunctionType()) {
2669 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002670 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002671 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002672 } else {
2673 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2674 diag::err_typecheck_arithmetic_incomplete_type,
2675 lex->getSourceRange(), SourceRange(),
2676 lex->getType());
2677 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002678 }
2679 }
2680 return PExp->getType();
2681 }
2682 }
2683
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002684 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002685}
2686
Chris Lattnereca7be62008-04-07 05:30:13 +00002687// C99 6.5.6
2688QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002689 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002690 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002691 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002692
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002693 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002694
Chris Lattner6e4ab612007-12-09 21:53:25 +00002695 // Enforce type constraints: C99 6.5.6p3.
2696
2697 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002698 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002699 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002700
2701 // Either ptr - int or ptr - ptr.
2702 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002703 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002704
Chris Lattner6e4ab612007-12-09 21:53:25 +00002705 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002706 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002707 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002708 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002709 Diag(Loc, diag::ext_gnu_void_ptr)
2710 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002711 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002712 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002713 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002714 return QualType();
2715 }
2716 }
2717
2718 // The result type of a pointer-int computation is the pointer type.
2719 if (rex->getType()->isIntegerType())
2720 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002721
Chris Lattner6e4ab612007-12-09 21:53:25 +00002722 // Handle pointer-pointer subtractions.
2723 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002724 QualType rpointee = RHSPTy->getPointeeType();
2725
Chris Lattner6e4ab612007-12-09 21:53:25 +00002726 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002727 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002728 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002729 if (rpointee->isVoidType()) {
2730 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002731 Diag(Loc, diag::ext_gnu_void_ptr)
2732 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002733 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002734 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002735 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002736 return QualType();
2737 }
2738 }
2739
2740 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002741 if (!Context.typesAreCompatible(
2742 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2743 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002744 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002745 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002746 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002747 return QualType();
2748 }
2749
2750 return Context.getPointerDiffType();
2751 }
2752 }
2753
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002754 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002755}
2756
Chris Lattnereca7be62008-04-07 05:30:13 +00002757// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002758QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002759 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002760 // C99 6.5.7p2: Each of the operands shall have integer type.
2761 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002762 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002763
Chris Lattnerca5eede2007-12-12 05:47:28 +00002764 // Shifts don't perform usual arithmetic conversions, they just do integer
2765 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002766 if (!isCompAssign)
2767 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002768 UsualUnaryConversions(rex);
2769
2770 // "The type of the result is that of the promoted left operand."
2771 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002772}
2773
Eli Friedman3d815e72008-08-22 00:56:42 +00002774static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2775 ASTContext& Context) {
2776 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2777 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2778 // ID acts sort of like void* for ObjC interfaces
2779 if (LHSIface && Context.isObjCIdType(RHS))
2780 return true;
2781 if (RHSIface && Context.isObjCIdType(LHS))
2782 return true;
2783 if (!LHSIface || !RHSIface)
2784 return false;
2785 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2786 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2787}
2788
Chris Lattnereca7be62008-04-07 05:30:13 +00002789// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002790QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002791 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002792 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002793 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002794
Chris Lattnera5937dd2007-08-26 01:18:55 +00002795 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002796 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2797 UsualArithmeticConversions(lex, rex);
2798 else {
2799 UsualUnaryConversions(lex);
2800 UsualUnaryConversions(rex);
2801 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002802 QualType lType = lex->getType();
2803 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002804
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002805 // For non-floating point types, check for self-comparisons of the form
2806 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2807 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002808 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002809 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2810 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002811 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002812 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002813 }
2814
Douglas Gregor447b69e2008-11-19 03:25:36 +00002815 // The result of comparisons is 'bool' in C++, 'int' in C.
2816 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2817
Chris Lattnera5937dd2007-08-26 01:18:55 +00002818 if (isRelational) {
2819 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002820 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002821 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002822 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002823 if (lType->isFloatingType()) {
2824 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002825 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002826 }
2827
Chris Lattnera5937dd2007-08-26 01:18:55 +00002828 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002829 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002830 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002831
Chris Lattnerd28f8152007-08-26 01:10:14 +00002832 bool LHSIsNull = lex->isNullPointerConstant(Context);
2833 bool RHSIsNull = rex->isNullPointerConstant(Context);
2834
Chris Lattnera5937dd2007-08-26 01:18:55 +00002835 // All of the following pointer related warnings are GCC extensions, except
2836 // when handling null pointer constants. One day, we can consider making them
2837 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002838 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002839 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002840 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002841 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002842 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002843
Steve Naroff66296cb2007-11-13 14:57:38 +00002844 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002845 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2846 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002847 RCanPointeeTy.getUnqualifiedType()) &&
2848 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002849 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002850 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002852 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002853 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002854 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002855 // Handle block pointer types.
2856 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2857 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2858 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2859
2860 if (!LHSIsNull && !RHSIsNull &&
2861 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002862 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002863 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002864 }
2865 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002866 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002867 }
Steve Naroff59f53942008-09-28 01:11:11 +00002868 // Allow block pointers to be compared with null pointer constants.
2869 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2870 (lType->isPointerType() && rType->isBlockPointerType())) {
2871 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002872 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002873 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002874 }
2875 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002876 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002877 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002878
Steve Naroff20373222008-06-03 14:04:54 +00002879 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002880 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002881 const PointerType *LPT = lType->getAsPointerType();
2882 const PointerType *RPT = rType->getAsPointerType();
2883 bool LPtrToVoid = LPT ?
2884 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2885 bool RPtrToVoid = RPT ?
2886 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2887
2888 if (!LPtrToVoid && !RPtrToVoid &&
2889 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002890 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002891 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002892 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002893 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002894 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002895 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002896 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002897 }
Steve Naroff20373222008-06-03 14:04:54 +00002898 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2899 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002900 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002901 } else {
2902 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002903 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002904 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002905 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002906 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002907 }
Steve Naroff20373222008-06-03 14:04:54 +00002908 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002909 }
Steve Naroff20373222008-06-03 14:04:54 +00002910 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2911 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002912 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002913 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002914 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002915 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002916 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002917 }
Steve Naroff20373222008-06-03 14:04:54 +00002918 if (lType->isIntegerType() &&
2919 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002920 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002921 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002922 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002923 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002924 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 }
Steve Naroff39218df2008-09-04 16:56:14 +00002926 // Handle block pointers.
2927 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2928 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002929 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002930 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002931 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002932 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002933 }
2934 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2935 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002936 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002937 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002938 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002939 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002940 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002941 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002942}
2943
Nate Begemanbe2341d2008-07-14 18:02:46 +00002944/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2945/// operates on extended vector types. Instead of producing an IntTy result,
2946/// like a scalar comparison, a vector comparison produces a vector of integer
2947/// types.
2948QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002949 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002950 bool isRelational) {
2951 // Check to make sure we're operating on vectors of the same type and width,
2952 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002953 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002954 if (vType.isNull())
2955 return vType;
2956
2957 QualType lType = lex->getType();
2958 QualType rType = rex->getType();
2959
2960 // For non-floating point types, check for self-comparisons of the form
2961 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2962 // often indicate logic errors in the program.
2963 if (!lType->isFloatingType()) {
2964 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2965 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2966 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002967 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002968 }
2969
2970 // Check for comparisons of floating point operands using != and ==.
2971 if (!isRelational && lType->isFloatingType()) {
2972 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002973 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002974 }
2975
2976 // Return the type for the comparison, which is the same as vector type for
2977 // integer vectors, or an integer type of identical size and number of
2978 // elements for floating point vectors.
2979 if (lType->isIntegerType())
2980 return lType;
2981
2982 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00002983 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00002984 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00002985 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00002986 else if (TypeSize == Context.getTypeSize(Context.LongTy))
2987 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
2988
2989 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
2990 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00002991 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2992}
2993
Reid Spencer5f016e22007-07-11 17:01:13 +00002994inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002995 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002996{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002997 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002998 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002999
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003000 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003001
Steve Naroffa4332e22007-07-17 00:58:39 +00003002 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003003 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003004 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003005}
3006
3007inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003008 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003009{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003010 UsualUnaryConversions(lex);
3011 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003012
Eli Friedman5773a6c2008-05-13 20:16:47 +00003013 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003014 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003015 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003016}
3017
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003018/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3019/// is a read-only property; return true if so. A readonly property expression
3020/// depends on various declarations and thus must be treated specially.
3021///
3022static bool IsReadonlyProperty(Expr *E, Sema &S)
3023{
3024 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3025 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3026 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3027 QualType BaseType = PropExpr->getBase()->getType();
3028 if (const PointerType *PTy = BaseType->getAsPointerType())
3029 if (const ObjCInterfaceType *IFTy =
3030 PTy->getPointeeType()->getAsObjCInterfaceType())
3031 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3032 if (S.isPropertyReadonly(PDecl, IFace))
3033 return true;
3034 }
3035 }
3036 return false;
3037}
3038
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003039/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3040/// emit an error and return true. If so, return false.
3041static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003042 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3043 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3044 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003045 if (IsLV == Expr::MLV_Valid)
3046 return false;
3047
3048 unsigned Diag = 0;
3049 bool NeedType = false;
3050 switch (IsLV) { // C99 6.5.16p2
3051 default: assert(0 && "Unknown result from isModifiableLvalue!");
3052 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003053 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003054 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3055 NeedType = true;
3056 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003057 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003058 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3059 NeedType = true;
3060 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003061 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003062 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3063 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003064 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003065 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3066 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003067 case Expr::MLV_IncompleteType:
3068 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003069 return S.DiagnoseIncompleteType(Loc, E->getType(),
3070 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3071 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003072 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003073 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3074 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003075 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003076 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3077 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003078 case Expr::MLV_ReadonlyProperty:
3079 Diag = diag::error_readonly_property_assignment;
3080 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003081 case Expr::MLV_NoSetterProperty:
3082 Diag = diag::error_nosetter_property_assignment;
3083 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003084 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003085
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003086 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003087 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003088 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003089 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003090 return true;
3091}
3092
3093
3094
3095// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003096QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3097 SourceLocation Loc,
3098 QualType CompoundType) {
3099 // Verify that LHS is a modifiable lvalue, and emit error if not.
3100 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003101 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003102
3103 QualType LHSType = LHS->getType();
3104 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003105
Chris Lattner5cf216b2008-01-04 18:04:52 +00003106 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003107 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003108 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003109 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003110 // Special case of NSObject attributes on c-style pointer types.
3111 if (ConvTy == IncompatiblePointer &&
3112 ((Context.isObjCNSObjectType(LHSType) &&
3113 Context.isObjCObjectPointerType(RHSType)) ||
3114 (Context.isObjCNSObjectType(RHSType) &&
3115 Context.isObjCObjectPointerType(LHSType))))
3116 ConvTy = Compatible;
3117
Chris Lattner2c156472008-08-21 18:04:13 +00003118 // If the RHS is a unary plus or minus, check to see if they = and + are
3119 // right next to each other. If so, the user may have typo'd "x =+ 4"
3120 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003121 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003122 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3123 RHSCheck = ICE->getSubExpr();
3124 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3125 if ((UO->getOpcode() == UnaryOperator::Plus ||
3126 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003127 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003128 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003129 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003130 Diag(Loc, diag::warn_not_compound_assign)
3131 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3132 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003133 }
3134 } else {
3135 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003136 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003137 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003138
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003139 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3140 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003141 return QualType();
3142
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 // C99 6.5.16p3: The type of an assignment expression is the type of the
3144 // left operand unless the left operand has qualified type, in which case
3145 // it is the unqualified version of the type of the left operand.
3146 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3147 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003148 // C++ 5.17p1: the type of the assignment expression is that of its left
3149 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003150 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003151}
3152
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003153// C99 6.5.17
3154QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3155 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003156
3157 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003158 DefaultFunctionArrayConversion(RHS);
3159 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003160}
3161
Steve Naroff49b45262007-07-13 16:58:59 +00003162/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3163/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003164QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3165 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003166 QualType ResType = Op->getType();
3167 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003168
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003169 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3170 // Decrement of bool is not allowed.
3171 if (!isInc) {
3172 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3173 return QualType();
3174 }
3175 // Increment of bool sets it to true, but is deprecated.
3176 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3177 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003178 // OK!
3179 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3180 // C99 6.5.2.4p2, 6.5.6p2
3181 if (PT->getPointeeType()->isObjectType()) {
3182 // Pointer to object is ok!
3183 } else if (PT->getPointeeType()->isVoidType()) {
3184 // Pointer to void is extension.
3185 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003186 } else if (PT->getPointeeType()->isFunctionType()) {
3187 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003188 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003190 } else {
3191 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3192 diag::err_typecheck_arithmetic_incomplete_type,
3193 Op->getSourceRange(), SourceRange(),
3194 ResType);
3195 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 }
Chris Lattner3528d352008-11-21 07:05:48 +00003197 } else if (ResType->isComplexType()) {
3198 // C99 does not support ++/-- on complex types, we allow as an extension.
3199 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003200 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003201 } else {
3202 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003203 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003204 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003205 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003206 // At this point, we know we have a real, complex or pointer type.
3207 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003208 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003209 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003210 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003211}
3212
Anders Carlsson369dee42008-02-01 07:15:58 +00003213/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003214/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003215/// where the declaration is needed for type checking. We only need to
3216/// handle cases when the expression references a function designator
3217/// or is an lvalue. Here are some examples:
3218/// - &(x) => x
3219/// - &*****f => f for f a function designator.
3220/// - &s.xx => s
3221/// - &s.zz[1].yy -> s, if zz is an array
3222/// - *(x + 1) -> x, if x is an array
3223/// - &"123"[2] -> 0
3224/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003225static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003226 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003227 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003228 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003229 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003230 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003231 // Fields cannot be declared with a 'register' storage class.
3232 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003233 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003234 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003235 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003236 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003237 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003238
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003239 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003240 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003241 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003242 return 0;
3243 else
3244 return VD;
3245 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003246 case Stmt::UnaryOperatorClass: {
3247 UnaryOperator *UO = cast<UnaryOperator>(E);
3248
3249 switch(UO->getOpcode()) {
3250 case UnaryOperator::Deref: {
3251 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003252 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3253 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3254 if (!VD || VD->getType()->isPointerType())
3255 return 0;
3256 return VD;
3257 }
3258 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003259 }
3260 case UnaryOperator::Real:
3261 case UnaryOperator::Imag:
3262 case UnaryOperator::Extension:
3263 return getPrimaryDecl(UO->getSubExpr());
3264 default:
3265 return 0;
3266 }
3267 }
3268 case Stmt::BinaryOperatorClass: {
3269 BinaryOperator *BO = cast<BinaryOperator>(E);
3270
3271 // Handle cases involving pointer arithmetic. The result of an
3272 // Assign or AddAssign is not an lvalue so they can be ignored.
3273
3274 // (x + n) or (n + x) => x
3275 if (BO->getOpcode() == BinaryOperator::Add) {
3276 if (BO->getLHS()->getType()->isPointerType()) {
3277 return getPrimaryDecl(BO->getLHS());
3278 } else if (BO->getRHS()->getType()->isPointerType()) {
3279 return getPrimaryDecl(BO->getRHS());
3280 }
3281 }
3282
3283 return 0;
3284 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003285 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003286 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003287 case Stmt::ImplicitCastExprClass:
3288 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003289 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003290 default:
3291 return 0;
3292 }
3293}
3294
3295/// CheckAddressOfOperand - The operand of & must be either a function
3296/// designator or an lvalue designating an object. If it is an lvalue, the
3297/// object cannot be declared with storage class register or be a bit field.
3298/// Note: The usual conversions are *not* applied to the operand of the &
3299/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003300/// In C++, the operand might be an overloaded function name, in which case
3301/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003302QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003303 if (op->isTypeDependent())
3304 return Context.DependentTy;
3305
Steve Naroff08f19672008-01-13 17:10:08 +00003306 if (getLangOptions().C99) {
3307 // Implement C99-only parts of addressof rules.
3308 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3309 if (uOp->getOpcode() == UnaryOperator::Deref)
3310 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3311 // (assuming the deref expression is valid).
3312 return uOp->getSubExpr()->getType();
3313 }
3314 // Technically, there should be a check for array subscript
3315 // expressions here, but the result of one is always an lvalue anyway.
3316 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003317 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003318 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003319
Reid Spencer5f016e22007-07-11 17:01:13 +00003320 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003321 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3322 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003323 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3324 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 return QualType();
3326 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003327 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003328 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3329 if (Field->isBitField()) {
3330 Diag(OpLoc, diag::err_typecheck_address_of)
3331 << "bit-field" << op->getSourceRange();
3332 return QualType();
3333 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003334 }
3335 // Check for Apple extension for accessing vector components.
3336 } else if (isa<ArraySubscriptExpr>(op) &&
3337 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003338 Diag(OpLoc, diag::err_typecheck_address_of)
3339 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003340 return QualType();
3341 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 // We have an lvalue with a decl. Make sure the decl is not declared
3343 // with the register storage-class specifier.
3344 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3345 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003346 Diag(OpLoc, diag::err_typecheck_address_of)
3347 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003348 return QualType();
3349 }
Douglas Gregor29882052008-12-10 21:26:49 +00003350 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003351 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003352 } else if (isa<FieldDecl>(dcl)) {
3353 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003354 } else if (isa<FunctionDecl>(dcl)) {
3355 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003356 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003357 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003359 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003360
Reid Spencer5f016e22007-07-11 17:01:13 +00003361 // If the operand has type "type", the result has type "pointer to type".
3362 return Context.getPointerType(op->getType());
3363}
3364
Chris Lattner22caddc2008-11-23 09:13:29 +00003365QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3366 UsualUnaryConversions(Op);
3367 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003368
Chris Lattner22caddc2008-11-23 09:13:29 +00003369 // Note that per both C89 and C99, this is always legal, even if ptype is an
3370 // incomplete type or void. It would be possible to warn about dereferencing
3371 // a void pointer, but it's completely well-defined, and such a warning is
3372 // unlikely to catch any mistakes.
3373 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003374 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003375
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003376 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003377 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003378 return QualType();
3379}
3380
3381static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3382 tok::TokenKind Kind) {
3383 BinaryOperator::Opcode Opc;
3384 switch (Kind) {
3385 default: assert(0 && "Unknown binop!");
3386 case tok::star: Opc = BinaryOperator::Mul; break;
3387 case tok::slash: Opc = BinaryOperator::Div; break;
3388 case tok::percent: Opc = BinaryOperator::Rem; break;
3389 case tok::plus: Opc = BinaryOperator::Add; break;
3390 case tok::minus: Opc = BinaryOperator::Sub; break;
3391 case tok::lessless: Opc = BinaryOperator::Shl; break;
3392 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3393 case tok::lessequal: Opc = BinaryOperator::LE; break;
3394 case tok::less: Opc = BinaryOperator::LT; break;
3395 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3396 case tok::greater: Opc = BinaryOperator::GT; break;
3397 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3398 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3399 case tok::amp: Opc = BinaryOperator::And; break;
3400 case tok::caret: Opc = BinaryOperator::Xor; break;
3401 case tok::pipe: Opc = BinaryOperator::Or; break;
3402 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3403 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3404 case tok::equal: Opc = BinaryOperator::Assign; break;
3405 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3406 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3407 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3408 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3409 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3410 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3411 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3412 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3413 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3414 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3415 case tok::comma: Opc = BinaryOperator::Comma; break;
3416 }
3417 return Opc;
3418}
3419
3420static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3421 tok::TokenKind Kind) {
3422 UnaryOperator::Opcode Opc;
3423 switch (Kind) {
3424 default: assert(0 && "Unknown unary op!");
3425 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3426 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3427 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3428 case tok::star: Opc = UnaryOperator::Deref; break;
3429 case tok::plus: Opc = UnaryOperator::Plus; break;
3430 case tok::minus: Opc = UnaryOperator::Minus; break;
3431 case tok::tilde: Opc = UnaryOperator::Not; break;
3432 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 case tok::kw___real: Opc = UnaryOperator::Real; break;
3434 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3435 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3436 }
3437 return Opc;
3438}
3439
Douglas Gregoreaebc752008-11-06 23:29:22 +00003440/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3441/// operator @p Opc at location @c TokLoc. This routine only supports
3442/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003443Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3444 unsigned Op,
3445 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003446 QualType ResultTy; // Result type of the binary operator.
3447 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3448 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3449
3450 switch (Opc) {
3451 default:
3452 assert(0 && "Unknown binary expr!");
3453 case BinaryOperator::Assign:
3454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3455 break;
3456 case BinaryOperator::Mul:
3457 case BinaryOperator::Div:
3458 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3459 break;
3460 case BinaryOperator::Rem:
3461 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3462 break;
3463 case BinaryOperator::Add:
3464 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3465 break;
3466 case BinaryOperator::Sub:
3467 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3468 break;
3469 case BinaryOperator::Shl:
3470 case BinaryOperator::Shr:
3471 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3472 break;
3473 case BinaryOperator::LE:
3474 case BinaryOperator::LT:
3475 case BinaryOperator::GE:
3476 case BinaryOperator::GT:
3477 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3478 break;
3479 case BinaryOperator::EQ:
3480 case BinaryOperator::NE:
3481 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3482 break;
3483 case BinaryOperator::And:
3484 case BinaryOperator::Xor:
3485 case BinaryOperator::Or:
3486 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3487 break;
3488 case BinaryOperator::LAnd:
3489 case BinaryOperator::LOr:
3490 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3491 break;
3492 case BinaryOperator::MulAssign:
3493 case BinaryOperator::DivAssign:
3494 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3495 if (!CompTy.isNull())
3496 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3497 break;
3498 case BinaryOperator::RemAssign:
3499 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3500 if (!CompTy.isNull())
3501 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3502 break;
3503 case BinaryOperator::AddAssign:
3504 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3505 if (!CompTy.isNull())
3506 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3507 break;
3508 case BinaryOperator::SubAssign:
3509 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3510 if (!CompTy.isNull())
3511 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3512 break;
3513 case BinaryOperator::ShlAssign:
3514 case BinaryOperator::ShrAssign:
3515 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3516 if (!CompTy.isNull())
3517 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3518 break;
3519 case BinaryOperator::AndAssign:
3520 case BinaryOperator::XorAssign:
3521 case BinaryOperator::OrAssign:
3522 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3523 if (!CompTy.isNull())
3524 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3525 break;
3526 case BinaryOperator::Comma:
3527 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3528 break;
3529 }
3530 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003531 return ExprError();
Steve Naroff9e0b6002009-01-20 21:06:31 +00003532 if (CompTy.isNull()) {
3533 void *Mem = Context.getAllocator().Allocate<BinaryOperator>();
3534 return Owned(new (Mem) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3535 } else {
3536 void *Mem = Context.getAllocator().Allocate<CompoundAssignOperator>();
3537 return Owned(new (Mem) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3538 CompTy, OpLoc));
3539 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003540}
3541
Reid Spencer5f016e22007-07-11 17:01:13 +00003542// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003543Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3544 tok::TokenKind Kind,
3545 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003546 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003547 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003548
Steve Narofff69936d2007-09-16 03:34:24 +00003549 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3550 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003551
Douglas Gregor898574e2008-12-05 23:32:09 +00003552 // If either expression is type-dependent, just build the AST.
3553 // FIXME: We'll need to perform some caching of the result of name
3554 // lookup for operator+.
3555 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff9e0b6002009-01-20 21:06:31 +00003556 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
3557 void *Mem = Context.getAllocator().Allocate<CompoundAssignOperator>();
3558 return Owned(new (Mem) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003559 Context.DependentTy,
3560 Context.DependentTy, TokLoc));
Steve Naroff9e0b6002009-01-20 21:06:31 +00003561 } else {
3562 void *Mem = Context.getAllocator().Allocate<BinaryOperator>();
3563 return Owned(new (Mem) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3564 TokLoc));
3565 }
Douglas Gregor898574e2008-12-05 23:32:09 +00003566 }
3567
Douglas Gregoreaebc752008-11-06 23:29:22 +00003568 if (getLangOptions().CPlusPlus &&
3569 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3570 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003571 // If this is one of the assignment operators, we only perform
3572 // overload resolution if the left-hand side is a class or
3573 // enumeration type (C++ [expr.ass]p3).
3574 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3575 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3576 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3577 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003578
Douglas Gregoreaebc752008-11-06 23:29:22 +00003579 // Determine which overloaded operator we're dealing with.
3580 static const OverloadedOperatorKind OverOps[] = {
3581 OO_Star, OO_Slash, OO_Percent,
3582 OO_Plus, OO_Minus,
3583 OO_LessLess, OO_GreaterGreater,
3584 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3585 OO_EqualEqual, OO_ExclaimEqual,
3586 OO_Amp,
3587 OO_Caret,
3588 OO_Pipe,
3589 OO_AmpAmp,
3590 OO_PipePipe,
3591 OO_Equal, OO_StarEqual,
3592 OO_SlashEqual, OO_PercentEqual,
3593 OO_PlusEqual, OO_MinusEqual,
3594 OO_LessLessEqual, OO_GreaterGreaterEqual,
3595 OO_AmpEqual, OO_CaretEqual,
3596 OO_PipeEqual,
3597 OO_Comma
3598 };
3599 OverloadedOperatorKind OverOp = OverOps[Opc];
3600
Douglas Gregor96176b32008-11-18 23:14:02 +00003601 // Add the appropriate overloaded operators (C++ [over.match.oper])
3602 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003603 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003604 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003605 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003606
3607 // Perform overload resolution.
3608 OverloadCandidateSet::iterator Best;
3609 switch (BestViableFunction(CandidateSet, Best)) {
3610 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003611 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003612 FunctionDecl *FnDecl = Best->Function;
3613
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003614 if (FnDecl) {
3615 // We matched an overloaded operator. Build a call to that
3616 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003617
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003618 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3620 if (PerformObjectArgumentInitialization(lhs, Method) ||
3621 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3622 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003623 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003624 } else {
3625 // Convert the arguments.
3626 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3627 "passing") ||
3628 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3629 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003630 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003631 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003632
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003633 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003634 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003635 = FnDecl->getType()->getAsFunctionType()->getResultType();
3636 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003637
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003638 // Build the actual expression node.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003639 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregorb4609802008-11-14 16:09:21 +00003640 SourceLocation());
3641 UsualUnaryConversions(FnExpr);
3642
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003643 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003644 } else {
3645 // We matched a built-in operator. Convert the arguments, then
3646 // break out so that we will build the appropriate built-in
3647 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003648 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3649 Best->Conversions[0], "passing") ||
3650 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3651 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003652 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003653
3654 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003655 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003656 }
3657
3658 case OR_No_Viable_Function:
3659 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003660 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003661 break;
3662
3663 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003664 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3665 << BinaryOperator::getOpcodeStr(Opc)
3666 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003667 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003668 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003669 }
3670
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003671 // Either we found no viable overloaded operator or we matched a
3672 // built-in operator. In either case, fall through to trying to
3673 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003674 }
3675
Douglas Gregoreaebc752008-11-06 23:29:22 +00003676 // Build a built-in binary operation.
3677 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003678}
3679
3680// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003681Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3682 tok::TokenKind Op, ExprArg input) {
3683 // FIXME: Input is modified later, but smart pointer not reassigned.
3684 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003685 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003686
3687 if (getLangOptions().CPlusPlus &&
3688 (Input->getType()->isRecordType()
3689 || Input->getType()->isEnumeralType())) {
3690 // Determine which overloaded operator we're dealing with.
3691 static const OverloadedOperatorKind OverOps[] = {
3692 OO_None, OO_None,
3693 OO_PlusPlus, OO_MinusMinus,
3694 OO_Amp, OO_Star,
3695 OO_Plus, OO_Minus,
3696 OO_Tilde, OO_Exclaim,
3697 OO_None, OO_None,
3698 OO_None,
3699 OO_None
3700 };
3701 OverloadedOperatorKind OverOp = OverOps[Opc];
3702
3703 // Add the appropriate overloaded operators (C++ [over.match.oper])
3704 // to the candidate set.
3705 OverloadCandidateSet CandidateSet;
3706 if (OverOp != OO_None)
3707 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3708
3709 // Perform overload resolution.
3710 OverloadCandidateSet::iterator Best;
3711 switch (BestViableFunction(CandidateSet, Best)) {
3712 case OR_Success: {
3713 // We found a built-in operator or an overloaded operator.
3714 FunctionDecl *FnDecl = Best->Function;
3715
3716 if (FnDecl) {
3717 // We matched an overloaded operator. Build a call to that
3718 // operator.
3719
3720 // Convert the arguments.
3721 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3722 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003723 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003724 } else {
3725 // Convert the arguments.
3726 if (PerformCopyInitialization(Input,
3727 FnDecl->getParamDecl(0)->getType(),
3728 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003729 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003730 }
3731
3732 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003733 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003734 = FnDecl->getType()->getAsFunctionType()->getResultType();
3735 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003736
Douglas Gregor74253732008-11-19 15:42:04 +00003737 // Build the actual expression node.
3738 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3739 SourceLocation());
3740 UsualUnaryConversions(FnExpr);
3741
Sebastian Redl0eb23302009-01-19 00:08:26 +00003742 input.release();
3743 return Owned(new CXXOperatorCallExpr(FnExpr, &Input, 1,
3744 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003745 } else {
3746 // We matched a built-in operator. Convert the arguments, then
3747 // break out so that we will build the appropriate built-in
3748 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003749 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3750 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003751 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003752
3753 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003754 }
Douglas Gregor74253732008-11-19 15:42:04 +00003755 }
3756
3757 case OR_No_Viable_Function:
3758 // No viable function; fall through to handling this as a
3759 // built-in operator, which will produce an error message for us.
3760 break;
3761
3762 case OR_Ambiguous:
3763 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3764 << UnaryOperator::getOpcodeStr(Opc)
3765 << Input->getSourceRange();
3766 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003767 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003768 }
3769
3770 // Either we found no viable overloaded operator or we matched a
3771 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003772 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003773 }
3774
Reid Spencer5f016e22007-07-11 17:01:13 +00003775 QualType resultType;
3776 switch (Opc) {
3777 default:
3778 assert(0 && "Unimplemented unary expr!");
3779 case UnaryOperator::PreInc:
3780 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003781 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3782 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003783 break;
3784 case UnaryOperator::AddrOf:
3785 resultType = CheckAddressOfOperand(Input, OpLoc);
3786 break;
3787 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003788 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003789 resultType = CheckIndirectionOperand(Input, OpLoc);
3790 break;
3791 case UnaryOperator::Plus:
3792 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003793 UsualUnaryConversions(Input);
3794 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003795 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3796 break;
3797 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3798 resultType->isEnumeralType())
3799 break;
3800 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3801 Opc == UnaryOperator::Plus &&
3802 resultType->isPointerType())
3803 break;
3804
Sebastian Redl0eb23302009-01-19 00:08:26 +00003805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3806 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003807 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003808 UsualUnaryConversions(Input);
3809 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003810 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3811 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3812 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003813 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003814 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003815 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003816 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3817 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003818 break;
3819 case UnaryOperator::LNot: // logical negation
3820 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003821 DefaultFunctionArrayConversion(Input);
3822 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003823 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00003824 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3825 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003826 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003827 // In C++, it's bool. C++ 5.3.1p8
3828 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003829 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003830 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003831 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003832 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003833 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003834 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003835 resultType = Input->getType();
3836 break;
3837 }
3838 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003839 return ExprError();
3840 input.release();
Steve Naroff9e0b6002009-01-20 21:06:31 +00003841 void *Mem = Context.getAllocator().Allocate<UnaryOperator>();
3842 return Owned(new (Mem) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003843}
3844
Steve Naroff1b273c42007-09-16 14:56:35 +00003845/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3846Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003847 SourceLocation LabLoc,
3848 IdentifierInfo *LabelII) {
3849 // Look up the record for this label identifier.
3850 LabelStmt *&LabelDecl = LabelMap[LabelII];
3851
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003852 // If we haven't seen this label yet, create a forward reference. It
3853 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003854 if (LabelDecl == 0)
3855 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3856
3857 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003858 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3859 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003860}
3861
Steve Naroff1b273c42007-09-16 14:56:35 +00003862Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003863 SourceLocation RPLoc) { // "({..})"
3864 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3865 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3866 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3867
3868 // FIXME: there are a variety of strange constraints to enforce here, for
3869 // example, it is not possible to goto into a stmt expression apparently.
3870 // More semantic analysis is needed.
3871
3872 // FIXME: the last statement in the compount stmt has its value used. We
3873 // should not warn about it being unused.
3874
3875 // If there are sub stmts in the compound stmt, take the type of the last one
3876 // as the type of the stmtexpr.
3877 QualType Ty = Context.VoidTy;
3878
Chris Lattner611b2ec2008-07-26 19:51:01 +00003879 if (!Compound->body_empty()) {
3880 Stmt *LastStmt = Compound->body_back();
3881 // If LastStmt is a label, skip down through into the body.
3882 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3883 LastStmt = Label->getSubStmt();
3884
3885 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003886 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003887 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003888
3889 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3890}
Steve Naroffd34e9152007-08-01 22:05:33 +00003891
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003892Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3893 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003894 SourceLocation TypeLoc,
3895 TypeTy *argty,
3896 OffsetOfComponent *CompPtr,
3897 unsigned NumComponents,
3898 SourceLocation RPLoc) {
3899 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3900 assert(!ArgTy.isNull() && "Missing type argument!");
3901
3902 // We must have at least one component that refers to the type, and the first
3903 // one is known to be a field designator. Verify that the ArgTy represents
3904 // a struct/union/class.
3905 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003906 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003907
3908 // Otherwise, create a compound literal expression as the base, and
3909 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003910 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003911
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003912 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3913 // GCC extension, diagnose them.
3914 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003915 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3916 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003917
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003918 for (unsigned i = 0; i != NumComponents; ++i) {
3919 const OffsetOfComponent &OC = CompPtr[i];
3920 if (OC.isBrackets) {
3921 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003922 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003923 if (!AT) {
3924 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003925 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003926 }
3927
Chris Lattner704fe352007-08-30 17:59:59 +00003928 // FIXME: C++: Verify that operator[] isn't overloaded.
3929
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003930 // C99 6.5.2.1p1
3931 Expr *Idx = static_cast<Expr*>(OC.U.E);
3932 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003933 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3934 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003935
3936 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3937 continue;
3938 }
3939
3940 const RecordType *RC = Res->getType()->getAsRecordType();
3941 if (!RC) {
3942 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003943 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003944 }
3945
3946 // Get the decl corresponding to this.
3947 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003948 FieldDecl *MemberDecl
3949 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3950 Decl::IDNS_Ordinary,
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003951 S, RD, false, false).getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003952 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003953 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3954 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003955
3956 // FIXME: C++: Verify that MemberDecl isn't a static field.
3957 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003958 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3959 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003960 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3961 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003962 }
3963
3964 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3965 BuiltinLoc);
3966}
3967
3968
Steve Naroff1b273c42007-09-16 14:56:35 +00003969Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003970 TypeTy *arg1, TypeTy *arg2,
3971 SourceLocation RPLoc) {
3972 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3973 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3974
3975 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3976
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003977 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003978}
3979
Steve Naroff1b273c42007-09-16 14:56:35 +00003980Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003981 ExprTy *expr1, ExprTy *expr2,
3982 SourceLocation RPLoc) {
3983 Expr *CondExpr = static_cast<Expr*>(cond);
3984 Expr *LHSExpr = static_cast<Expr*>(expr1);
3985 Expr *RHSExpr = static_cast<Expr*>(expr2);
3986
3987 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3988
3989 // The conditional expression is required to be a constant expression.
3990 llvm::APSInt condEval(32);
3991 SourceLocation ExpLoc;
3992 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003993 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3994 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003995
3996 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3997 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3998 RHSExpr->getType();
3999 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
4000}
4001
Steve Naroff4eb206b2008-09-03 18:15:37 +00004002//===----------------------------------------------------------------------===//
4003// Clang Extensions.
4004//===----------------------------------------------------------------------===//
4005
4006/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004007void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004008 // Analyze block parameters.
4009 BlockSemaInfo *BSI = new BlockSemaInfo();
4010
4011 // Add BSI to CurBlock.
4012 BSI->PrevBlockInfo = CurBlock;
4013 CurBlock = BSI;
4014
4015 BSI->ReturnType = 0;
4016 BSI->TheScope = BlockScope;
4017
Steve Naroff090276f2008-10-10 01:28:17 +00004018 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004019 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004020}
4021
4022void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004023 // Analyze arguments to block.
4024 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4025 "Not a function declarator!");
4026 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4027
Steve Naroff090276f2008-10-10 01:28:17 +00004028 CurBlock->hasPrototype = FTI.hasPrototype;
4029 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004030
4031 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4032 // no arguments, not a function that takes a single void argument.
4033 if (FTI.hasPrototype &&
4034 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4035 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4036 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4037 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004038 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004039 } else if (FTI.hasPrototype) {
4040 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004041 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4042 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004043 }
Steve Naroff090276f2008-10-10 01:28:17 +00004044 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4045
4046 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4047 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4048 // If this has an identifier, add it to the scope stack.
4049 if ((*AI)->getIdentifier())
4050 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004051}
4052
4053/// ActOnBlockError - If there is an error parsing a block, this callback
4054/// is invoked to pop the information about the block from the action impl.
4055void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4056 // Ensure that CurBlock is deleted.
4057 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4058
4059 // Pop off CurBlock, handle nested blocks.
4060 CurBlock = CurBlock->PrevBlockInfo;
4061
4062 // FIXME: Delete the ParmVarDecl objects as well???
4063
4064}
4065
4066/// ActOnBlockStmtExpr - This is called when the body of a block statement
4067/// literal was successfully completed. ^(int x){...}
4068Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4069 Scope *CurScope) {
4070 // Ensure that CurBlock is deleted.
4071 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4072 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4073
Steve Naroff090276f2008-10-10 01:28:17 +00004074 PopDeclContext();
4075
Steve Naroff4eb206b2008-09-03 18:15:37 +00004076 // Pop off CurBlock, handle nested blocks.
4077 CurBlock = CurBlock->PrevBlockInfo;
4078
4079 QualType RetTy = Context.VoidTy;
4080 if (BSI->ReturnType)
4081 RetTy = QualType(BSI->ReturnType, 0);
4082
4083 llvm::SmallVector<QualType, 8> ArgTypes;
4084 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4085 ArgTypes.push_back(BSI->Params[i]->getType());
4086
4087 QualType BlockTy;
4088 if (!BSI->hasPrototype)
4089 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4090 else
4091 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004092 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004093
4094 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004095
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004096 BSI->TheDecl->setBody(Body.take());
4097 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004098}
4099
Nate Begeman67295d02008-01-30 20:50:20 +00004100/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004101/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004102/// The number of arguments has already been validated to match the number of
4103/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004104static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4105 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004106 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004107 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004108 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4109 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004110
4111 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004112 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004113 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004114 return true;
4115}
4116
4117Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4118 SourceLocation *CommaLocs,
4119 SourceLocation BuiltinLoc,
4120 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004121 // __builtin_overload requires at least 2 arguments
4122 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004123 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4124 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004125
Nate Begemane2ce1d92008-01-17 17:46:27 +00004126 // The first argument is required to be a constant expression. It tells us
4127 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004128 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004129 Expr *NParamsExpr = Args[0];
4130 llvm::APSInt constEval(32);
4131 SourceLocation ExpLoc;
4132 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004133 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4134 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004135
4136 // Verify that the number of parameters is > 0
4137 unsigned NumParams = constEval.getZExtValue();
4138 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004139 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4140 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004141 // Verify that we have at least 1 + NumParams arguments to the builtin.
4142 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004143 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4144 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004145
4146 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004147 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004148 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004149 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4150 // UsualUnaryConversions will convert the function DeclRefExpr into a
4151 // pointer to function.
4152 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004153 const FunctionTypeProto *FnType = 0;
4154 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4155 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004156
4157 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4158 // parameters, and the number of parameters must match the value passed to
4159 // the builtin.
4160 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004161 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4162 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004163
4164 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004165 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004166 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004167 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004168 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004169 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4170 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004171 // Remember our match, and continue processing the remaining arguments
4172 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004173 OE = new OverloadExpr(Args, NumArgs, i,
4174 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004175 BuiltinLoc, RParenLoc);
4176 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004177 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004178 // Return the newly created OverloadExpr node, if we succeded in matching
4179 // exactly one of the candidate functions.
4180 if (OE)
4181 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004182
4183 // If we didn't find a matching function Expr in the __builtin_overload list
4184 // the return an error.
4185 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004186 for (unsigned i = 0; i != NumParams; ++i) {
4187 if (i != 0) typeNames += ", ";
4188 typeNames += Args[i+1]->getType().getAsString();
4189 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004190
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004191 return Diag(BuiltinLoc, diag::err_overload_no_match)
4192 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004193}
4194
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004195Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4196 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004197 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004198 Expr *E = static_cast<Expr*>(expr);
4199 QualType T = QualType::getFromOpaquePtr(type);
4200
4201 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004202
4203 // Get the va_list type
4204 QualType VaListType = Context.getBuiltinVaListType();
4205 // Deal with implicit array decay; for example, on x86-64,
4206 // va_list is an array, but it's supposed to decay to
4207 // a pointer for va_arg.
4208 if (VaListType->isArrayType())
4209 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004210 // Make sure the input expression also decays appropriately.
4211 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004212
4213 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004214 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004215 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004216 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004217
4218 // FIXME: Warn if a non-POD type is passed in.
4219
Douglas Gregor9d293df2008-10-28 00:22:11 +00004220 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004221}
4222
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004223Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4224 // The type of __null will be int or long, depending on the size of
4225 // pointers on the target.
4226 QualType Ty;
4227 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4228 Ty = Context.IntTy;
4229 else
4230 Ty = Context.LongTy;
4231
4232 return new GNUNullExpr(Ty, TokenLoc);
4233}
4234
Chris Lattner5cf216b2008-01-04 18:04:52 +00004235bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4236 SourceLocation Loc,
4237 QualType DstType, QualType SrcType,
4238 Expr *SrcExpr, const char *Flavor) {
4239 // Decode the result (notice that AST's are still created for extensions).
4240 bool isInvalid = false;
4241 unsigned DiagKind;
4242 switch (ConvTy) {
4243 default: assert(0 && "Unknown conversion type");
4244 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004245 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004246 DiagKind = diag::ext_typecheck_convert_pointer_int;
4247 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004248 case IntToPointer:
4249 DiagKind = diag::ext_typecheck_convert_int_pointer;
4250 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004251 case IncompatiblePointer:
4252 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4253 break;
4254 case FunctionVoidPointer:
4255 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4256 break;
4257 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004258 // If the qualifiers lost were because we were applying the
4259 // (deprecated) C++ conversion from a string literal to a char*
4260 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4261 // Ideally, this check would be performed in
4262 // CheckPointerTypesForAssignment. However, that would require a
4263 // bit of refactoring (so that the second argument is an
4264 // expression, rather than a type), which should be done as part
4265 // of a larger effort to fix CheckPointerTypesForAssignment for
4266 // C++ semantics.
4267 if (getLangOptions().CPlusPlus &&
4268 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4269 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004270 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4271 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004272 case IntToBlockPointer:
4273 DiagKind = diag::err_int_to_block_pointer;
4274 break;
4275 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004276 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004277 break;
Steve Naroff39579072008-10-14 22:18:38 +00004278 case IncompatibleObjCQualifiedId:
4279 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4280 // it can give a more specific diagnostic.
4281 DiagKind = diag::warn_incompatible_qualified_id;
4282 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004283 case Incompatible:
4284 DiagKind = diag::err_typecheck_convert_incompatible;
4285 isInvalid = true;
4286 break;
4287 }
4288
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004289 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4290 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004291 return isInvalid;
4292}
Anders Carlssone21555e2008-11-30 19:50:32 +00004293
4294bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4295{
4296 Expr::EvalResult EvalResult;
4297
4298 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4299 EvalResult.HasSideEffects) {
4300 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4301
4302 if (EvalResult.Diag) {
4303 // We only show the note if it's not the usual "invalid subexpression"
4304 // or if it's actually in a subexpression.
4305 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4306 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4307 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4308 }
4309
4310 return true;
4311 }
4312
4313 if (EvalResult.Diag) {
4314 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4315 E->getSourceRange();
4316
4317 // Print the reason it's not a constant.
4318 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4319 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4320 }
4321
4322 if (Result)
4323 *Result = EvalResult.Val.getInt();
4324 return false;
4325}