blob: d4babb4baa4f945ad43c1f63e616077322dc1ce2 [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!
Steve Naroff6ece14c2009-01-21 00:14:39 +0000322 return Owned(new (Context) StringLiteral(Literal.GetString(),
323 Literal.GetStringLength(),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000324 Literal.AnyWide, StrTy,
325 StringToks[0].getLocation(),
326 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000327}
328
Chris Lattner639e2d32008-10-20 05:16:36 +0000329/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
330/// CurBlock to VD should cause it to be snapshotted (as we do for auto
331/// variables defined outside the block) or false if this is not needed (e.g.
332/// for values inside the block or for globals).
333///
334/// FIXME: This will create BlockDeclRefExprs for global variables,
335/// function references, etc which is suboptimal :) and breaks
336/// things like "integer constant expression" tests.
337static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
338 ValueDecl *VD) {
339 // If the value is defined inside the block, we couldn't snapshot it even if
340 // we wanted to.
341 if (CurBlock->TheDecl == VD->getDeclContext())
342 return false;
343
344 // If this is an enum constant or function, it is constant, don't snapshot.
345 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
346 return false;
347
348 // If this is a reference to an extern, static, or global variable, no need to
349 // snapshot it.
350 // FIXME: What about 'const' variables in C++?
351 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
352 return Var->hasLocalStorage();
353
354 return true;
355}
356
357
358
Steve Naroff08d92e42007-09-15 18:49:24 +0000359/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000360/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000361/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000362/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000363/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000364Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
365 IdentifierInfo &II,
366 bool HasTrailingLParen,
367 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000368 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
369}
370
Douglas Gregor1a49af92009-01-06 05:10:23 +0000371/// BuildDeclRefExpr - Build either a DeclRefExpr or a
372/// QualifiedDeclRefExpr based on whether or not SS is a
373/// nested-name-specifier.
374DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
375 bool TypeDependent, bool ValueDependent,
376 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000377 if (SS && !SS->isEmpty())
378 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroff0a473932009-01-20 19:53:53 +0000379 ValueDependent, SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000380 else
381 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000382}
383
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000384/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
385/// variable corresponding to the anonymous union or struct whose type
386/// is Record.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000387static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000388 assert(Record->isAnonymousStructOrUnion() &&
389 "Record must be an anonymous struct or union!");
390
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000391 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000392 // be an O(1) operation rather than a slow walk through DeclContext's
393 // vector (which itself will be eliminated). DeclGroups might make
394 // this even better.
395 DeclContext *Ctx = Record->getDeclContext();
396 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
397 DEnd = Ctx->decls_end();
398 D != DEnd; ++D) {
399 if (*D == Record) {
400 // The object for the anonymous struct/union directly
401 // follows its type in the list of declarations.
402 ++D;
403 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000404 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000405 return *D;
406 }
407 }
408
409 assert(false && "Missing object for anonymous record");
410 return 0;
411}
412
Sebastian Redlcd965b92009-01-18 18:53:16 +0000413Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000414Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
415 FieldDecl *Field,
416 Expr *BaseObjectExpr,
417 SourceLocation OpLoc) {
418 assert(Field->getDeclContext()->isRecord() &&
419 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
420 && "Field must be stored inside an anonymous struct or union");
421
422 // Construct the sequence of field member references
423 // we'll have to perform to get to the field in the anonymous
424 // union/struct. The list of members is built from the field
425 // outward, so traverse it backwards to go from an object in
426 // the current context to the field we found.
427 llvm::SmallVector<FieldDecl *, 4> AnonFields;
428 AnonFields.push_back(Field);
429 VarDecl *BaseObject = 0;
430 DeclContext *Ctx = Field->getDeclContext();
431 do {
432 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000433 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000434 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
435 AnonFields.push_back(AnonField);
436 else {
437 BaseObject = cast<VarDecl>(AnonObject);
438 break;
439 }
440 Ctx = Ctx->getParent();
441 } while (Ctx->isRecord() &&
442 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
443
444 // Build the expression that refers to the base object, from
445 // which we will build a sequence of member references to each
446 // of the anonymous union objects and, eventually, the field we
447 // found via name lookup.
448 bool BaseObjectIsPointer = false;
449 unsigned ExtraQuals = 0;
450 if (BaseObject) {
451 // BaseObject is an anonymous struct/union variable (and is,
452 // therefore, not part of another non-anonymous record).
453 delete BaseObjectExpr;
454
Steve Naroff6ece14c2009-01-21 00:14:39 +0000455 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000456 SourceLocation());
457 ExtraQuals
458 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
459 } else if (BaseObjectExpr) {
460 // The caller provided the base object expression. Determine
461 // whether its a pointer and whether it adds any qualifiers to the
462 // anonymous struct/union fields we're looking into.
463 QualType ObjectType = BaseObjectExpr->getType();
464 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
465 BaseObjectIsPointer = true;
466 ObjectType = ObjectPtr->getPointeeType();
467 }
468 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
469 } else {
470 // We've found a member of an anonymous struct/union that is
471 // inside a non-anonymous struct/union, so in a well-formed
472 // program our base object expression is "this".
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
474 if (!MD->isStatic()) {
475 QualType AnonFieldType
476 = Context.getTagDeclType(
477 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
478 QualType ThisType = Context.getTagDeclType(MD->getParent());
479 if ((Context.getCanonicalType(AnonFieldType)
480 == Context.getCanonicalType(ThisType)) ||
481 IsDerivedFrom(ThisType, AnonFieldType)) {
482 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000483 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000484 MD->getThisType(Context));
485 BaseObjectIsPointer = true;
486 }
487 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000488 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
489 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000490 }
491 ExtraQuals = MD->getTypeQualifiers();
492 }
493
494 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000495 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
496 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000497 }
498
499 // Build the implicit member references to the field of the
500 // anonymous struct/union.
501 Expr *Result = BaseObjectExpr;
502 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
503 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
504 FI != FIEnd; ++FI) {
505 QualType MemberType = (*FI)->getType();
506 if (!(*FI)->isMutable()) {
507 unsigned combinedQualifiers
508 = MemberType.getCVRQualifiers() | ExtraQuals;
509 MemberType = MemberType.getQualifiedType(combinedQualifiers);
510 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000511 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
512 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000513 BaseObjectIsPointer = false;
514 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
515 OpLoc = SourceLocation();
516 }
517
Sebastian Redlcd965b92009-01-18 18:53:16 +0000518 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000519}
520
Douglas Gregor10c42622008-11-18 15:03:34 +0000521/// ActOnDeclarationNameExpr - The parser has read some kind of name
522/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
523/// performs lookup on that name and returns an expression that refers
524/// to that name. This routine isn't directly called from the parser,
525/// because the parser doesn't know about DeclarationName. Rather,
526/// this routine is called by ActOnIdentifierExpr,
527/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
528/// which form the DeclarationName from the corresponding syntactic
529/// forms.
530///
531/// HasTrailingLParen indicates whether this identifier is used in a
532/// function call context. LookupCtx is only used for a C++
533/// qualified-id (foo::bar) to indicate the class or namespace that
534/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000535///
536/// If ForceResolution is true, then we will attempt to resolve the
537/// name even if it looks like a dependent name. This option is off by
538/// default.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000539Sema::OwningExprResult
540Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
541 DeclarationName Name, bool HasTrailingLParen,
542 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregor5c37de72008-12-06 00:22:45 +0000543 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
544 HasTrailingLParen && !SS && !ForceResolution) {
545 // We've seen something of the form
546 // identifier(
547 // and we are in a template, so it is likely that 's' is a
548 // dependent name. However, we won't know until we've parsed all
549 // of the call arguments. So, build a CXXDependentNameExpr node
550 // to represent this name. Then, if it turns out that none of the
551 // arguments are type-dependent, we'll force the resolution of the
552 // dependent name at that point.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000553 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
554 Context.DependentTy, Loc));
Douglas Gregor5c37de72008-12-06 00:22:45 +0000555 }
556
Chris Lattner8a934232008-03-31 00:36:02 +0000557 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000558 Decl *D = 0;
559 LookupResult Lookup;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000560 if (SS && !SS->isEmpty()) {
561 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
562 if (DC == 0)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000563 return ExprError();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000564 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000565 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000566 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
567
Sebastian Redlcd965b92009-01-18 18:53:16 +0000568 if (Lookup.isAmbiguous()) {
569 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet() ? SS->getRange()
571 : SourceRange());
572 return ExprError();
573 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000574 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000575
Chris Lattner8a934232008-03-31 00:36:02 +0000576 // If this reference is in an Objective-C method, then ivar lookup happens as
577 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000578 IdentifierInfo *II = Name.getAsIdentifierInfo();
579 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000585 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd965b92009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000592 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
593 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000594 true, true);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattner8a934232008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000600 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000603 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000604 }
Chris Lattner8a934232008-03-31 00:36:02 +0000605 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000622 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 }
625 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000626
627 // We may have found a field within an anonymous union or struct
628 // (C++ [class.union]).
629 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
631 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000632
Douglas Gregor88a35142008-12-22 05:46:06 +0000633 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
634 if (!MD->isStatic()) {
635 // C++ [class.mfct.nonstatic]p2:
636 // [...] if name lookup (3.4.1) resolves the name in the
637 // id-expression to a nonstatic nontype member of class X or of
638 // a base class of X, the id-expression is transformed into a
639 // class member access expression (5.2.5) using (*this) (9.3.2)
640 // as the postfix-expression to the left of the '.' operator.
641 DeclContext *Ctx = 0;
642 QualType MemberType;
643 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
644 Ctx = FD->getDeclContext();
645 MemberType = FD->getType();
646
647 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
648 MemberType = RefType->getPointeeType();
649 else if (!FD->isMutable()) {
650 unsigned combinedQualifiers
651 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
652 MemberType = MemberType.getQualifiedType(combinedQualifiers);
653 }
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 if (!Method->isStatic()) {
656 Ctx = Method->getParent();
657 MemberType = Method->getType();
658 }
659 } else if (OverloadedFunctionDecl *Ovl
660 = dyn_cast<OverloadedFunctionDecl>(D)) {
661 for (OverloadedFunctionDecl::function_iterator
662 Func = Ovl->function_begin(),
663 FuncEnd = Ovl->function_end();
664 Func != FuncEnd; ++Func) {
665 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
666 if (!DMethod->isStatic()) {
667 Ctx = Ovl->getDeclContext();
668 MemberType = Context.OverloadTy;
669 break;
670 }
671 }
672 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000673
674 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000675 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
676 QualType ThisType = Context.getTagDeclType(MD->getParent());
677 if ((Context.getCanonicalType(CtxType)
678 == Context.getCanonicalType(ThisType)) ||
679 IsDerivedFrom(ThisType, CtxType)) {
680 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000681 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor88a35142008-12-22 05:46:06 +0000682 MD->getThisType(Context));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000683 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000684 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000685 }
686 }
687 }
688 }
689
Douglas Gregor44b43212008-12-11 16:49:14 +0000690 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
692 if (MD->isStatic())
693 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000694 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
695 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000696 }
697
Douglas Gregor88a35142008-12-22 05:46:06 +0000698 // Any other ways we could have found the field in a well-formed
699 // program would have been turned into implicit member expressions
700 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000701 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
702 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000703 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000708 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000709 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
Steve Naroffdd972f22008-09-05 22:11:13 +0000712 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000713 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000714 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
715 false, false, SS));
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716
Steve Naroffdd972f22008-09-05 22:11:13 +0000717 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000718
Steve Naroffdd972f22008-09-05 22:11:13 +0000719 // check if referencing an identifier with __attribute__((deprecated)).
720 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000721 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
722
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000723 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
724 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
725 Scope *CheckS = S;
726 while (CheckS) {
727 if (CheckS->isWithinElse() &&
728 CheckS->getControlParent()->isDeclScope(Var)) {
729 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000730 ExprError(Diag(Loc, diag::warn_value_always_false)
731 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000732 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_zero)
734 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000735 break;
736 }
737
738 // Move up one more control parent to check again.
739 CheckS = CheckS->getControlParent();
740 if (CheckS)
741 CheckS = CheckS->getParent();
742 }
743 }
744 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000745
746 // Only create DeclRefExpr's for valid Decl's.
747 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000748 return ExprError();
749
Chris Lattner639e2d32008-10-20 05:16:36 +0000750 // If the identifier reference is inside a block, and it refers to a value
751 // that is outside the block, create a BlockDeclRefExpr instead of a
752 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
753 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000754 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000755 // We do not do this for things like enum constants, global variables, etc,
756 // as they do not get snapshotted.
757 //
758 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000759 // The BlocksAttr indicates the variable is bound by-reference.
760 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000761 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000762 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000763
Steve Naroff090276f2008-10-10 01:28:17 +0000764 // Variable will be bound by-copy, make it const within the closure.
765 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000766 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000767 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000768 }
769 // If this reference is not in a block or if the referenced variable is
770 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000771
Douglas Gregor898574e2008-12-05 23:32:09 +0000772 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000773 bool ValueDependent = false;
774 if (getLangOptions().CPlusPlus) {
775 // C++ [temp.dep.expr]p3:
776 // An id-expression is type-dependent if it contains:
777 // - an identifier that was declared with a dependent type,
778 if (VD->getType()->isDependentType())
779 TypeDependent = true;
780 // - FIXME: a template-id that is dependent,
781 // - a conversion-function-id that specifies a dependent type,
782 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
783 Name.getCXXNameType()->isDependentType())
784 TypeDependent = true;
785 // - a nested-name-specifier that contains a class-name that
786 // names a dependent type.
787 else if (SS && !SS->isEmpty()) {
788 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
789 DC; DC = DC->getParent()) {
790 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000791 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000792 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
793 if (Context.getTypeDeclType(Record)->isDependentType()) {
794 TypeDependent = true;
795 break;
796 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000797 }
798 }
799 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000800
Douglas Gregor83f96f62008-12-10 20:57:37 +0000801 // C++ [temp.dep.constexpr]p2:
802 //
803 // An identifier is value-dependent if it is:
804 // - a name declared with a dependent type,
805 if (TypeDependent)
806 ValueDependent = true;
807 // - the name of a non-type template parameter,
808 else if (isa<NonTypeTemplateParmDecl>(VD))
809 ValueDependent = true;
810 // - a constant with integral or enumeration type and is
811 // initialized with an expression that is value-dependent
812 // (FIXME!).
813 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000814
Sebastian Redlcd965b92009-01-18 18:53:16 +0000815 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
816 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000817}
818
Sebastian Redlcd965b92009-01-18 18:53:16 +0000819Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
820 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000821 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000822
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000824 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000825 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
826 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
827 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000829
Chris Lattnerfa28b302008-01-12 08:14:25 +0000830 // Pre-defined identifiers are of type char[x], where x is the length of the
831 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000832 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000833 if (FunctionDecl *FD = getCurFunctionDecl())
834 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000835 else if (ObjCMethodDecl *MD = getCurMethodDecl())
836 Length = MD->getSynthesizedMethodSize();
837 else {
838 Diag(Loc, diag::ext_predef_outside_function);
839 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
840 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
841 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000842
843
Chris Lattner8f978d52008-01-12 19:32:28 +0000844 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000845 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000846 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000847 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000848}
849
Sebastian Redlcd965b92009-01-18 18:53:16 +0000850Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 llvm::SmallString<16> CharBuffer;
852 CharBuffer.resize(Tok.getLength());
853 const char *ThisTokBegin = &CharBuffer[0];
854 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000855
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
857 Tok.getLocation(), PP);
858 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000859 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000860
861 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
862
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000863 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
864 Literal.isWide(),
865 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000866}
867
Sebastian Redlcd965b92009-01-18 18:53:16 +0000868Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
869 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
871 if (Tok.getLength() == 1) {
Chris Lattner0c21e842009-01-16 07:10:29 +0000872 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
873 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000874 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +0000875 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 }
Ted Kremenek28396602009-01-13 23:19:12 +0000877
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000879 // Add padding so that NumericLiteralParser can overread by one character.
880 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000882
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 // Get the spelling of the token, which eliminates trigraphs, etc.
884 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
887 Tok.getLocation(), PP);
888 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000889 return ExprError();
890
Chris Lattner5d661452007-08-26 03:42:43 +0000891 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000892
Chris Lattner5d661452007-08-26 03:42:43 +0000893 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000894 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000895 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000896 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000897 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000898 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000899 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000900 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000901
902 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
903
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000904 // isExact will be set by GetFloatValue().
905 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000906 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
907 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000908
Chris Lattner5d661452007-08-26 03:42:43 +0000909 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000910 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000911 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000912 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000913
Neil Boothb9449512007-08-29 22:00:19 +0000914 // long long is a C99 feature.
915 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000916 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000917 Diag(Tok.getLocation(), diag::ext_longlong);
918
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000920 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000921
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 if (Literal.GetIntegerValue(ResultVal)) {
923 // If this value didn't fit into uintmax_t, warn and force to ull.
924 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000925 Ty = Context.UnsignedLongLongTy;
926 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000927 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 } else {
929 // If this value fits into a ULL, try to figure out what else it fits into
930 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000931
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 // Octal, Hexadecimal, and integers with a U suffix are allowed to
933 // be an unsigned int.
934 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
935
936 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000937 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000938 if (!Literal.isLong && !Literal.isLongLong) {
939 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000940 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 // Does it fit in a unsigned int?
943 if (ResultVal.isIntN(IntSize)) {
944 // Does it fit in a signed int?
945 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000946 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000948 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000949 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000952
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000954 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000955 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 // Does it fit in a unsigned long?
958 if (ResultVal.isIntN(LongSize)) {
959 // Does it fit in a signed long?
960 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000961 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000963 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000964 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000966 }
967
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000969 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000970 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 // Does it fit in a unsigned long long?
973 if (ResultVal.isIntN(LongLongSize)) {
974 // Does it fit in a signed long long?
975 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000976 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000978 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000979 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
981 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000982
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 // If we still couldn't decide a type, we probably have something that
984 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000985 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000987 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000988 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000990
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000991 if (ResultVal.getBitWidth() != Width)
992 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000994 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000996
Chris Lattner5d661452007-08-26 03:42:43 +0000997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
998 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +0000999 Res = new (Context) ImaginaryLiteral(Res,
1000 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001001
1002 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001003}
1004
Sebastian Redlcd965b92009-01-18 18:53:16 +00001005Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1006 SourceLocation R, ExprArg Val) {
1007 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001008 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001009 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001010}
1011
1012/// The UsualUnaryConversions() function is *not* called by this routine.
1013/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001014bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1015 SourceLocation OpLoc,
1016 const SourceRange &ExprRange,
1017 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001019 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001021 if (isSizeof)
1022 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1023 return false;
1024 }
1025
1026 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001027 Diag(OpLoc, diag::ext_sizeof_void_type)
1028 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001029 return false;
1030 }
Sebastian Redl05189992008-11-11 17:56:53 +00001031
Chris Lattner01072922009-01-24 19:46:37 +00001032 return DiagnoseIncompleteType(OpLoc, exprType,
1033 isSizeof ? diag::err_sizeof_incomplete_type :
1034 diag::err_alignof_incomplete_type,
1035 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001036}
1037
Chris Lattner31e21e02009-01-24 20:17:12 +00001038bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1039 const SourceRange &ExprRange) {
1040 E = E->IgnoreParens();
1041
1042 // alignof decl is always ok.
1043 if (isa<DeclRefExpr>(E))
1044 return false;
1045
1046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1047 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1048 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001049 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001050 return true;
1051 }
1052 // Other fields are ok.
1053 return false;
1054 }
1055 }
1056 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1057}
1058
Sebastian Redl05189992008-11-11 17:56:53 +00001059/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1060/// the same for @c alignof and @c __alignof
1061/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001062Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001063Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1064 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001066 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001067
Sebastian Redl05189992008-11-11 17:56:53 +00001068 QualType ArgTy;
1069 SourceRange Range;
1070 if (isType) {
1071 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1072 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001073
1074 // Verify that the operand is valid.
1075 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1076 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001077 } else {
1078 // Get the end location.
1079 Expr *ArgEx = (Expr *)TyOrEx;
1080 Range = ArgEx->getSourceRange();
1081 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001082
1083 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001084 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001085 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001086 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001087 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1088 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1089 isInvalid = true;
1090 } else {
1091 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1092 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001093
1094 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001095 DeleteExpr(ArgEx);
1096 return ExprError();
1097 }
Sebastian Redl05189992008-11-11 17:56:53 +00001098 }
1099
Sebastian Redl05189992008-11-11 17:56:53 +00001100 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001101 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001102 Context.getSizeType(), OpLoc,
1103 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001104}
1105
Chris Lattner5d794252007-08-24 21:41:10 +00001106QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001107 DefaultFunctionArrayConversion(V);
1108
Chris Lattnercc26ed72007-08-26 05:39:26 +00001109 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001110 if (const ComplexType *CT = V->getType()->getAsComplexType())
1111 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001112
1113 // Otherwise they pass through real integer and floating point types here.
1114 if (V->getType()->isArithmeticType())
1115 return V->getType();
1116
1117 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001118 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001119 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001120}
1121
1122
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
Sebastian Redl0eb23302009-01-19 00:08:26 +00001124Action::OwningExprResult
1125Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1126 tok::TokenKind Kind, ExprArg Input) {
1127 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 UnaryOperator::Opcode Opc;
1130 switch (Kind) {
1131 default: assert(0 && "Unknown unary op!");
1132 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1133 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1134 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001135
Douglas Gregor74253732008-11-19 15:42:04 +00001136 if (getLangOptions().CPlusPlus &&
1137 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1138 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001139 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001140 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1141
1142 // C++ [over.inc]p1:
1143 //
1144 // [...] If the function is a member function with one
1145 // parameter (which shall be of type int) or a non-member
1146 // function with two parameters (the second of which shall be
1147 // of type int), it defines the postfix increment operator ++
1148 // for objects of that type. When the postfix increment is
1149 // called as a result of using the ++ operator, the int
1150 // argument will have value zero.
1151 Expr *Args[2] = {
1152 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001153 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1154 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001155 };
1156
1157 // Build the candidate set for overloading
1158 OverloadCandidateSet CandidateSet;
1159 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1160
1161 // Perform overload resolution.
1162 OverloadCandidateSet::iterator Best;
1163 switch (BestViableFunction(CandidateSet, Best)) {
1164 case OR_Success: {
1165 // We found a built-in operator or an overloaded operator.
1166 FunctionDecl *FnDecl = Best->Function;
1167
1168 if (FnDecl) {
1169 // We matched an overloaded operator. Build a call to that
1170 // operator.
1171
1172 // Convert the arguments.
1173 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1174 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001175 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001176 } else {
1177 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001178 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001179 FnDecl->getParamDecl(0)->getType(),
1180 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001181 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001182 }
1183
1184 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001185 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001186 = FnDecl->getType()->getAsFunctionType()->getResultType();
1187 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001188
Douglas Gregor74253732008-11-19 15:42:04 +00001189 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001190 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001191 SourceLocation());
1192 UsualUnaryConversions(FnExpr);
1193
Sebastian Redl0eb23302009-01-19 00:08:26 +00001194 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001195 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroff0a473932009-01-20 19:53:53 +00001196 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001197 } else {
1198 // We matched a built-in operator. Convert the arguments, then
1199 // break out so that we will build the appropriate built-in
1200 // operator node.
1201 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1202 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001203 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001204
1205 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001206 }
Douglas Gregor74253732008-11-19 15:42:04 +00001207 }
1208
1209 case OR_No_Viable_Function:
1210 // No viable function; fall through to handling this as a
1211 // built-in operator, which will produce an error message for us.
1212 break;
1213
1214 case OR_Ambiguous:
1215 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1216 << UnaryOperator::getOpcodeStr(Opc)
1217 << Arg->getSourceRange();
1218 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001219 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001220 }
1221
1222 // Either we found no viable overloaded operator or we matched a
1223 // built-in operator. In either case, fall through to trying to
1224 // build a built-in operation.
1225 }
1226
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001227 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1228 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001230 return ExprError();
1231 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001232 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001233}
1234
Sebastian Redl0eb23302009-01-19 00:08:26 +00001235Action::OwningExprResult
1236Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1237 ExprArg Idx, SourceLocation RLoc) {
1238 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1239 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001240
Douglas Gregor337c6b92008-11-19 17:17:41 +00001241 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001242 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001243 LHSExp->getType()->isEnumeralType() ||
1244 RHSExp->getType()->isRecordType() ||
1245 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001246 // Add the appropriate overloaded operators (C++ [over.match.oper])
1247 // to the candidate set.
1248 OverloadCandidateSet CandidateSet;
1249 Expr *Args[2] = { LHSExp, RHSExp };
1250 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001251
Douglas Gregor337c6b92008-11-19 17:17:41 +00001252 // Perform overload resolution.
1253 OverloadCandidateSet::iterator Best;
1254 switch (BestViableFunction(CandidateSet, Best)) {
1255 case OR_Success: {
1256 // We found a built-in operator or an overloaded operator.
1257 FunctionDecl *FnDecl = Best->Function;
1258
1259 if (FnDecl) {
1260 // We matched an overloaded operator. Build a call to that
1261 // operator.
1262
1263 // Convert the arguments.
1264 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1265 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1266 PerformCopyInitialization(RHSExp,
1267 FnDecl->getParamDecl(0)->getType(),
1268 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001269 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001270 } else {
1271 // Convert the arguments.
1272 if (PerformCopyInitialization(LHSExp,
1273 FnDecl->getParamDecl(0)->getType(),
1274 "passing") ||
1275 PerformCopyInitialization(RHSExp,
1276 FnDecl->getParamDecl(1)->getType(),
1277 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001278 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001279 }
1280
1281 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001282 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001283 = FnDecl->getType()->getAsFunctionType()->getResultType();
1284 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001285
Douglas Gregor337c6b92008-11-19 17:17:41 +00001286 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001287 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor337c6b92008-11-19 17:17:41 +00001288 SourceLocation());
1289 UsualUnaryConversions(FnExpr);
1290
Sebastian Redl0eb23302009-01-19 00:08:26 +00001291 Base.release();
1292 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001293 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1294 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001295 } else {
1296 // We matched a built-in operator. Convert the arguments, then
1297 // break out so that we will build the appropriate built-in
1298 // operator node.
1299 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1300 "passing") ||
1301 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1302 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001303 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001304
1305 break;
1306 }
1307 }
1308
1309 case OR_No_Viable_Function:
1310 // No viable function; fall through to handling this as a
1311 // built-in operator, which will produce an error message for us.
1312 break;
1313
1314 case OR_Ambiguous:
1315 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1316 << "[]"
1317 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1318 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001319 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001320 }
1321
1322 // Either we found no viable overloaded operator or we matched a
1323 // built-in operator. In either case, fall through to trying to
1324 // build a built-in operation.
1325 }
1326
Chris Lattner12d9ff62007-07-16 00:14:47 +00001327 // Perform default conversions.
1328 DefaultFunctionArrayConversion(LHSExp);
1329 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001330
Chris Lattner12d9ff62007-07-16 00:14:47 +00001331 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001334 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 // in the subscript position. As a result, we need to derive the array base
1336 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001337 Expr *BaseExpr, *IndexExpr;
1338 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001339 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001340 BaseExpr = LHSExp;
1341 IndexExpr = RHSExp;
1342 // FIXME: need to deal with const...
1343 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001344 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001345 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001346 BaseExpr = RHSExp;
1347 IndexExpr = LHSExp;
1348 // FIXME: need to deal with const...
1349 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001350 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1351 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001352 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001353
Chris Lattner12d9ff62007-07-16 00:14:47 +00001354 // FIXME: need to deal with const...
1355 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001357 return ExprError(Diag(LHSExp->getLocStart(),
1358 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1359 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001361 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001362 return ExprError(Diag(IndexExpr->getLocStart(),
1363 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001364
Chris Lattner12d9ff62007-07-16 00:14:47 +00001365 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1366 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001367 // void (*)(int)) and pointers to incomplete types. Functions are not
1368 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001369 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001370 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001371 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001372 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001373
Sebastian Redl0eb23302009-01-19 00:08:26 +00001374 Base.release();
1375 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001376 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1377 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001378}
1379
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001380QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001381CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001382 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001383 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001384
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001385 // The vector accessor can't exceed the number of elements.
1386 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001387
1388 // This flag determines whether or not the component is one of the four
1389 // special names that indicate a subset of exactly half the elements are
1390 // to be selected.
1391 bool HalvingSwizzle = false;
1392
1393 // This flag determines whether or not CompName has an 's' char prefix,
1394 // indicating that it is a string of hex values to be used as vector indices.
1395 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001396
1397 // Check that we've found one of the special components, or that the component
1398 // names must come from the same set.
1399 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001400 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1401 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001402 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001403 do
1404 compStr++;
1405 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001406 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001407 do
1408 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001409 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001410 }
Nate Begeman353417a2009-01-18 01:47:54 +00001411
1412 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001413 // We didn't get to the end of the string. This means the component names
1414 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001415 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1416 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001417 return QualType();
1418 }
Nate Begeman353417a2009-01-18 01:47:54 +00001419
1420 // Ensure no component accessor exceeds the width of the vector type it
1421 // operates on.
1422 if (!HalvingSwizzle) {
1423 compStr = CompName.getName();
1424
1425 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001426 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001427
1428 while (*compStr) {
1429 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1430 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1431 << baseType << SourceRange(CompLoc);
1432 return QualType();
1433 }
1434 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001435 }
Nate Begeman8a997642008-05-09 06:41:27 +00001436
Nate Begeman353417a2009-01-18 01:47:54 +00001437 // If this is a halving swizzle, verify that the base type has an even
1438 // number of elements.
1439 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001440 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001441 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001442 return QualType();
1443 }
1444
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001445 // The component accessor looks fine - now we need to compute the actual type.
1446 // The vector type is implied by the component accessor. For example,
1447 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001448 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001449 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001450 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1451 : CompName.getLength();
1452 if (HexSwizzle)
1453 CompSize--;
1454
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001455 if (CompSize == 1)
1456 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001457
Nate Begeman213541a2008-04-18 23:10:10 +00001458 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001459 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001460 // diagostics look bad. We want extended vector types to appear built-in.
1461 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1462 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1463 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001464 }
1465 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001466}
1467
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001468/// constructSetterName - Return the setter name for the given
1469/// identifier, i.e. "set" + Name where the initial character of Name
1470/// has been capitalized.
1471// FIXME: Merge with same routine in Parser. But where should this
1472// live?
1473static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1474 const IdentifierInfo *Name) {
1475 llvm::SmallString<100> SelectorName;
1476 SelectorName = "set";
1477 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1478 SelectorName[3] = toupper(SelectorName[3]);
1479 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1480}
1481
Sebastian Redl0eb23302009-01-19 00:08:26 +00001482Action::OwningExprResult
1483Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1484 tok::TokenKind OpKind, SourceLocation MemberLoc,
1485 IdentifierInfo &Member) {
1486 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001487 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001488
1489 // Perform default conversions.
1490 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001491
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001492 QualType BaseType = BaseExpr->getType();
1493 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001494
Chris Lattner68a057b2008-07-21 04:36:39 +00001495 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1496 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001498 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001499 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001500 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001501 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1502 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001503 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001504 return ExprError(Diag(MemberLoc,
1505 diag::err_typecheck_member_reference_arrow)
1506 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001508
Chris Lattner68a057b2008-07-21 04:36:39 +00001509 // Handle field access to simple records. This also handles access to fields
1510 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001511 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001512 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001513 if (DiagnoseIncompleteType(OpLoc, BaseType,
1514 diag::err_typecheck_incomplete_tag,
1515 BaseExpr->getSourceRange()))
1516 return ExprError();
1517
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001518 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001519 // FIXME: Qualified name lookup for C++ is a bit more complicated
1520 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001521 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001522 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1523 LookupCriteria(LookupCriteria::Member,
1524 /*RedeclarationOnly=*/false,
1525 getLangOptions().CPlusPlus));
1526
1527 Decl *MemberDecl = 0;
1528 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001529 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1530 << &Member << BaseExpr->getSourceRange());
1531 else if (Result.isAmbiguous()) {
1532 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1533 MemberLoc, BaseExpr->getSourceRange());
1534 return ExprError();
1535 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001536 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001537
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001538 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001539 // We may have found a field within an anonymous union or struct
1540 // (C++ [class.union]).
1541 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001542 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001543 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001544
Douglas Gregor86f19402008-12-20 23:49:58 +00001545 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1546 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001547 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001548 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1549 MemberType = Ref->getPointeeType();
1550 else {
1551 unsigned combinedQualifiers =
1552 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001553 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001554 combinedQualifiers &= ~QualType::Const;
1555 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1556 }
Eli Friedman51019072008-02-06 22:48:16 +00001557
Steve Naroff6ece14c2009-01-21 00:14:39 +00001558 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1559 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001560 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001561 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001562 Var, MemberLoc,
1563 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001564 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001565 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1566 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001567 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001568 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001569 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001570 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001571 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001572 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001573 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001574 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001575 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1576 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001577
Douglas Gregor86f19402008-12-20 23:49:58 +00001578 // We found a declaration kind that we didn't expect. This is a
1579 // generic error message that tells the user that she can't refer
1580 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001581 return ExprError(Diag(MemberLoc,
1582 diag::err_typecheck_member_reference_unknown)
1583 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001584 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001585
Chris Lattnera38e6b12008-07-21 04:59:05 +00001586 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1587 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001588 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001589 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001590 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1591 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001592 OpKind == tok::arrow);
1593 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001594 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001595 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001596 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1597 << IFTy->getDecl()->getDeclName() << &Member
1598 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001599 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001600
Chris Lattnera38e6b12008-07-21 04:59:05 +00001601 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1602 // pointer to a (potentially qualified) interface type.
1603 const PointerType *PTy;
1604 const ObjCInterfaceType *IFTy;
1605 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1606 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1607 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001608
Daniel Dunbar2307d312008-09-03 01:05:41 +00001609 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001610 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001611 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001612 MemberLoc, BaseExpr));
1613
Daniel Dunbar2307d312008-09-03 01:05:41 +00001614 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001615 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1616 E = IFTy->qual_end(); I != E; ++I)
1617 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001618 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001619 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001620
1621 // If that failed, look for an "implicit" property by seeing if the nullary
1622 // selector is implemented.
1623
1624 // FIXME: The logic for looking up nullary and unary selectors should be
1625 // shared with the code in ActOnInstanceMessage.
1626
1627 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1628 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001629
Daniel Dunbar2307d312008-09-03 01:05:41 +00001630 // If this reference is in an @implementation, check for 'private' methods.
1631 if (!Getter)
1632 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1633 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1634 if (ObjCImplementationDecl *ImpDecl =
1635 ObjCImplementations[ClassDecl->getIdentifier()])
1636 Getter = ImpDecl->getInstanceMethod(Sel);
1637
Steve Naroff7692ed62008-10-22 19:16:27 +00001638 // Look through local category implementations associated with the class.
1639 if (!Getter) {
1640 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1641 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1642 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1643 }
1644 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001645 if (Getter) {
1646 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001647 // will look for the matching setter, in case it is needed.
1648 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1649 &Member);
1650 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1651 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1652 if (!Setter) {
1653 // If this reference is in an @implementation, also check for 'private'
1654 // methods.
1655 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1656 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1657 if (ObjCImplementationDecl *ImpDecl =
1658 ObjCImplementations[ClassDecl->getIdentifier()])
1659 Setter = ImpDecl->getInstanceMethod(SetterSel);
1660 }
1661 // Look through local category implementations associated with the class.
1662 if (!Setter) {
1663 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1664 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1665 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1666 }
1667 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001668
1669 // FIXME: we must check that the setter has property type.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001670 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1671 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001672 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001673
1674 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1675 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001676 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001677 // Handle properties on qualified "id" protocols.
1678 const ObjCQualifiedIdType *QIdTy;
1679 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1680 // Check protocols on qualified interfaces.
1681 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001682 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001683 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001684 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001685 MemberLoc, BaseExpr));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001686 // Also must look for a getter name which uses property syntax.
1687 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1688 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001689 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1690 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001691 }
1692 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001693
1694 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1695 << &Member << BaseType);
1696 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001697 // Handle 'field access' to vectors, such as 'V.xx'.
1698 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001699 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1700 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001701 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001702 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1703 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001704 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001705
1706 return ExprError(Diag(MemberLoc,
1707 diag::err_typecheck_member_reference_struct_union)
1708 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001709}
1710
Douglas Gregor88a35142008-12-22 05:46:06 +00001711/// ConvertArgumentsForCall - Converts the arguments specified in
1712/// Args/NumArgs to the parameter types of the function FDecl with
1713/// function prototype Proto. Call is the call expression itself, and
1714/// Fn is the function expression. For a C++ member function, this
1715/// routine does not attempt to convert the object argument. Returns
1716/// true if the call is ill-formed.
1717bool
1718Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1719 FunctionDecl *FDecl,
1720 const FunctionTypeProto *Proto,
1721 Expr **Args, unsigned NumArgs,
1722 SourceLocation RParenLoc) {
1723 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1724 // assignment, to the types of the corresponding parameter, ...
1725 unsigned NumArgsInProto = Proto->getNumArgs();
1726 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001727 bool Invalid = false;
1728
Douglas Gregor88a35142008-12-22 05:46:06 +00001729 // If too few arguments are available (and we don't have default
1730 // arguments for the remaining parameters), don't make the call.
1731 if (NumArgs < NumArgsInProto) {
1732 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1733 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1734 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1735 // Use default arguments for missing arguments
1736 NumArgsToCheck = NumArgsInProto;
1737 Call->setNumArgs(NumArgsInProto);
1738 }
1739
1740 // If too many are passed and not variadic, error on the extras and drop
1741 // them.
1742 if (NumArgs > NumArgsInProto) {
1743 if (!Proto->isVariadic()) {
1744 Diag(Args[NumArgsInProto]->getLocStart(),
1745 diag::err_typecheck_call_too_many_args)
1746 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1747 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1748 Args[NumArgs-1]->getLocEnd());
1749 // This deletes the extra arguments.
1750 Call->setNumArgs(NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001751 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00001752 }
1753 NumArgsToCheck = NumArgsInProto;
1754 }
1755
1756 // Continue to check argument types (even if we have too few/many args).
1757 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1758 QualType ProtoArgType = Proto->getArgType(i);
1759
1760 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001761 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001762 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001763
1764 // Pass the argument.
1765 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1766 return true;
1767 } else
1768 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001769 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00001770 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001771
Douglas Gregor88a35142008-12-22 05:46:06 +00001772 Call->setArg(i, Arg);
1773 }
1774
1775 // If this is a variadic call, handle args passed through "...".
1776 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001777 VariadicCallType CallType = VariadicFunction;
1778 if (Fn->getType()->isBlockPointerType())
1779 CallType = VariadicBlock; // Block
1780 else if (isa<MemberExpr>(Fn))
1781 CallType = VariadicMethod;
1782
Douglas Gregor88a35142008-12-22 05:46:06 +00001783 // Promote the arguments (C99 6.5.2.2p7).
1784 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1785 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001786 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001787 Call->setArg(i, Arg);
1788 }
1789 }
1790
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001791 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00001792}
1793
Steve Narofff69936d2007-09-16 03:34:24 +00001794/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001795/// This provides the location of the left/right parens and a list of comma
1796/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001797Action::OwningExprResult
1798Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1799 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001800 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001801 unsigned NumArgs = args.size();
1802 Expr *Fn = static_cast<Expr *>(fn.release());
1803 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001804 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001805 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001806 OverloadedFunctionDecl *Ovl = NULL;
1807
Douglas Gregor5c37de72008-12-06 00:22:45 +00001808 // Determine whether this is a dependent call inside a C++ template,
1809 // in which case we won't do any semantic analysis now.
1810 bool Dependent = false;
1811 if (Fn->isTypeDependent()) {
1812 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1813 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1814 Dependent = true;
1815 else {
1816 // Resolve the CXXDependentNameExpr to an actual identifier;
1817 // it wasn't really a dependent name after all.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001818 OwningExprResult Resolved
1819 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1820 FnName->getName(),
Douglas Gregor5c37de72008-12-06 00:22:45 +00001821 /*HasTrailingLParen=*/true,
1822 /*SS=*/0,
1823 /*ForceResolution=*/true);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001824 if (Resolved.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001825 return ExprError();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001826 else {
1827 delete Fn;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001828 Fn = (Expr *)Resolved.release();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001829 }
1830 }
1831 } else
1832 Dependent = true;
1833 } else
1834 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1835
Douglas Gregor898574e2008-12-05 23:32:09 +00001836 // FIXME: Will need to cache the results of name lookup (including
1837 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001838 if (Dependent)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001839 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1840 Context.DependentTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001841
Douglas Gregor88a35142008-12-22 05:46:06 +00001842 // Determine whether this is a call to an object (C++ [over.call.object]).
1843 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001844 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1845 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001846
1847 // Determine whether this is a call to a member function.
1848 if (getLangOptions().CPlusPlus) {
1849 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1850 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1851 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001852 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1853 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001854 }
1855
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001856 // If we're directly calling a function or a set of overloaded
1857 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001858 DeclRefExpr *DRExpr = NULL;
1859 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1860 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1861 else
1862 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001863
Douglas Gregor1a49af92009-01-06 05:10:23 +00001864 if (DRExpr) {
1865 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1866 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001867 }
1868
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001869 if (Ovl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001870 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1871 CommaLocs, RParenLoc);
Douglas Gregor0a396682008-11-26 06:01:48 +00001872 if (!FDecl)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001873 return ExprError();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001874
Douglas Gregor0a396682008-11-26 06:01:48 +00001875 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001876 Expr *NewFn = 0;
1877 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001878 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor1a49af92009-01-06 05:10:23 +00001879 QDRExpr->getLocation(), false, false,
1880 QDRExpr->getSourceRange().getBegin());
1881 else
Steve Naroff6ece14c2009-01-21 00:14:39 +00001882 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1883 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001884 Fn->Destroy(Context);
1885 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001886 }
Chris Lattner04421082008-04-08 04:40:51 +00001887
1888 // Promote the function operand.
1889 UsualUnaryConversions(Fn);
1890
Chris Lattner925e60d2007-12-28 05:29:59 +00001891 // Make the call expr early, before semantic checks. This guarantees cleanup
1892 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001893 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1894 // Destroy(), or nothing gets cleaned up.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001895 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001896 Context.BoolTy, RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001897
Steve Naroffdd972f22008-09-05 22:11:13 +00001898 const FunctionType *FuncT;
1899 if (!Fn->getType()->isBlockPointerType()) {
1900 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1901 // have type pointer to function".
1902 const PointerType *PT = Fn->getType()->getAsPointerType();
1903 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001904 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1905 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00001906 FuncT = PT->getPointeeType()->getAsFunctionType();
1907 } else { // This is a block call.
1908 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1909 getAsFunctionType();
1910 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001911 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001912 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1913 << Fn->getType() << Fn->getSourceRange());
1914
Chris Lattner925e60d2007-12-28 05:29:59 +00001915 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001916 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001917
Chris Lattner925e60d2007-12-28 05:29:59 +00001918 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001919 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1920 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001921 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00001922 } else {
1923 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001924
Steve Naroffb291ab62007-08-28 23:30:39 +00001925 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001926 for (unsigned i = 0; i != NumArgs; i++) {
1927 Expr *Arg = Args[i];
1928 DefaultArgumentPromotion(Arg);
1929 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001930 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001932
Douglas Gregor88a35142008-12-22 05:46:06 +00001933 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1934 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001935 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1936 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00001937
Chris Lattner59907c42007-08-10 20:18:51 +00001938 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001939 if (FDecl)
1940 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001941
Sebastian Redl0eb23302009-01-19 00:08:26 +00001942 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001943}
1944
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001945Action::OwningExprResult
1946Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1947 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001948 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001949 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001950 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001951 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001952 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00001953
Eli Friedman6223c222008-05-20 05:22:08 +00001954 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001955 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001956 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1957 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001958 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1959 diag::err_typecheck_decl_incomplete_type,
1960 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001961 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00001962
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001963 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001964 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001965 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00001966
Chris Lattner371f2582008-12-04 23:50:19 +00001967 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001968 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001969 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001970 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001971 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001972 InitExpr.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001973 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1974 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00001975}
1976
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001977Action::OwningExprResult
1978Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1979 InitListDesignations &Designators,
1980 SourceLocation RBraceLoc) {
1981 unsigned NumInit = initlist.size();
1982 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001983
Steve Naroff08d92e42007-09-15 18:49:24 +00001984 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001985 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001986
Steve Naroff6ece14c2009-01-21 00:14:39 +00001987 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
1988 RBraceLoc, Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001989 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001990 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001991}
1992
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001993/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001994bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001995 UsualUnaryConversions(castExpr);
1996
1997 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1998 // type needs to be scalar.
1999 if (castType->isVoidType()) {
2000 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002001 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2002 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002003 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002004 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2005 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2006 (castType->isStructureType() || castType->isUnionType())) {
2007 // GCC struct/union extension: allow cast to self.
2008 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2009 << castType << castExpr->getSourceRange();
2010 } else if (castType->isUnionType()) {
2011 // GCC cast to union extension
2012 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2013 RecordDecl::field_iterator Field, FieldEnd;
2014 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2015 Field != FieldEnd; ++Field) {
2016 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2017 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2018 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2019 << castExpr->getSourceRange();
2020 break;
2021 }
2022 }
2023 if (Field == FieldEnd)
2024 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2025 << castExpr->getType() << castExpr->getSourceRange();
2026 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002027 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002028 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002029 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002030 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002031 } else if (!castExpr->getType()->isScalarType() &&
2032 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002033 return Diag(castExpr->getLocStart(),
2034 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002035 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002036 } else if (castExpr->getType()->isVectorType()) {
2037 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2038 return true;
2039 } else if (castType->isVectorType()) {
2040 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2041 return true;
2042 }
2043 return false;
2044}
2045
Chris Lattnerfe23e212007-12-20 00:44:32 +00002046bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002047 assert(VectorTy->isVectorType() && "Not a vector type!");
2048
2049 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002050 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002051 return Diag(R.getBegin(),
2052 Ty->isVectorType() ?
2053 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002054 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002055 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002056 } else
2057 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002058 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002059 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002060
2061 return false;
2062}
2063
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002064Action::OwningExprResult
2065Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2066 SourceLocation RParenLoc, ExprArg Op) {
2067 assert((Ty != 0) && (Op.get() != 0) &&
2068 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002069
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002070 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002071 QualType castType = QualType::getFromOpaquePtr(Ty);
2072
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002073 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002074 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002075 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002076 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002077}
2078
Chris Lattnera21ddb32007-11-26 01:40:58 +00002079/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2080/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002081inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002082 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002083 UsualUnaryConversions(cond);
2084 UsualUnaryConversions(lex);
2085 UsualUnaryConversions(rex);
2086 QualType condT = cond->getType();
2087 QualType lexT = lex->getType();
2088 QualType rexT = rex->getType();
2089
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002091 if (!cond->isTypeDependent()) {
2092 if (!condT->isScalarType()) { // C99 6.5.15p2
2093 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2094 return QualType();
2095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002097
2098 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002099 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2100 return Context.DependentTy;
2101
Chris Lattner70d67a92008-01-06 22:42:25 +00002102 // If both operands have arithmetic type, do the usual arithmetic conversions
2103 // to find a common type: C99 6.5.15p3,5.
2104 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002105 UsualArithmeticConversions(lex, rex);
2106 return lex->getType();
2107 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002108
2109 // If both operands are the same structure or union type, the result is that
2110 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002111 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002112 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002113 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002114 // "If both the operands have structure or union type, the result has
2115 // that type." This implies that CV qualifiers are dropped.
2116 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002118
2119 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002120 // The following || allows only one side to be void (a GCC-ism).
2121 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002122 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002123 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2124 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002125 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002126 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2127 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002128 ImpCastExprToType(lex, Context.VoidTy);
2129 ImpCastExprToType(rex, Context.VoidTy);
2130 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002131 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002132 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2133 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002134 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2135 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002136 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002137 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002138 return lexT;
2139 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002140 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2141 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002142 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002143 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002144 return rexT;
2145 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002146 // Handle the case where both operands are pointers before we handle null
2147 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002148 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2149 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2150 // get the "pointed to" types
2151 QualType lhptee = LHSPT->getPointeeType();
2152 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002153
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002154 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2155 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002156 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002157 // Figure out necessary qualifiers (C99 6.5.15p6)
2158 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002159 QualType destType = Context.getPointerType(destPointee);
2160 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2161 ImpCastExprToType(rex, destType); // promote to void*
2162 return destType;
2163 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002164 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002165 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002166 QualType destType = Context.getPointerType(destPointee);
2167 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2168 ImpCastExprToType(rex, destType); // promote to void*
2169 return destType;
2170 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002171
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002172 QualType compositeType = lexT;
2173
2174 // If either type is an Objective-C object type then check
2175 // compatibility according to Objective-C.
2176 if (Context.isObjCObjectPointerType(lexT) ||
2177 Context.isObjCObjectPointerType(rexT)) {
2178 // If both operands are interfaces and either operand can be
2179 // assigned to the other, use that type as the composite
2180 // type. This allows
2181 // xxx ? (A*) a : (B*) b
2182 // where B is a subclass of A.
2183 //
2184 // Additionally, as for assignment, if either type is 'id'
2185 // allow silent coercion. Finally, if the types are
2186 // incompatible then make sure to use 'id' as the composite
2187 // type so the result is acceptable for sending messages to.
2188
2189 // FIXME: This code should not be localized to here. Also this
2190 // should use a compatible check instead of abusing the
2191 // canAssignObjCInterfaces code.
2192 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2193 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2194 if (LHSIface && RHSIface &&
2195 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2196 compositeType = lexT;
2197 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002198 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002199 compositeType = rexT;
2200 } else if (Context.isObjCIdType(lhptee) ||
2201 Context.isObjCIdType(rhptee)) {
2202 // FIXME: This code looks wrong, because isObjCIdType checks
2203 // the struct but getObjCIdType returns the pointer to
2204 // struct. This is horrible and should be fixed.
2205 compositeType = Context.getObjCIdType();
2206 } else {
2207 QualType incompatTy = Context.getObjCIdType();
2208 ImpCastExprToType(lex, incompatTy);
2209 ImpCastExprToType(rex, incompatTy);
2210 return incompatTy;
2211 }
2212 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2213 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002214 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002215 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002216 // In this situation, we assume void* type. No especially good
2217 // reason, but this is what gcc does, and we do have to pick
2218 // to get a consistent AST.
2219 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002220 ImpCastExprToType(lex, incompatTy);
2221 ImpCastExprToType(rex, incompatTy);
2222 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002223 }
2224 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002225 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2226 // differently qualified versions of compatible types, the result type is
2227 // a pointer to an appropriately qualified version of the *composite*
2228 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002229 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002230 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002231 ImpCastExprToType(lex, compositeType);
2232 ImpCastExprToType(rex, compositeType);
2233 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 }
2235 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002236 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2237 // evaluates to "struct objc_object *" (and is handled above when comparing
2238 // id with statically typed objects).
2239 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2240 // GCC allows qualified id and any Objective-C type to devolve to
2241 // id. Currently localizing to here until clear this should be
2242 // part of ObjCQualifiedIdTypesAreCompatible.
2243 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2244 (lexT->isObjCQualifiedIdType() &&
2245 Context.isObjCObjectPointerType(rexT)) ||
2246 (rexT->isObjCQualifiedIdType() &&
2247 Context.isObjCObjectPointerType(lexT))) {
2248 // FIXME: This is not the correct composite type. This only
2249 // happens to work because id can more or less be used anywhere,
2250 // however this may change the type of method sends.
2251 // FIXME: gcc adds some type-checking of the arguments and emits
2252 // (confusing) incompatible comparison warnings in some
2253 // cases. Investigate.
2254 QualType compositeType = Context.getObjCIdType();
2255 ImpCastExprToType(lex, compositeType);
2256 ImpCastExprToType(rex, compositeType);
2257 return compositeType;
2258 }
2259 }
2260
Steve Naroff61f40a22008-09-10 19:17:48 +00002261 // Selection between block pointer types is ok as long as they are the same.
2262 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2263 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2264 return lexT;
2265
Chris Lattner70d67a92008-01-06 22:42:25 +00002266 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002267 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002268 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 return QualType();
2270}
2271
Steve Narofff69936d2007-09-16 03:34:24 +00002272/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002273/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002274Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2275 SourceLocation ColonLoc,
2276 ExprArg Cond, ExprArg LHS,
2277 ExprArg RHS) {
2278 Expr *CondExpr = (Expr *) Cond.get();
2279 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002280
2281 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2282 // was the condition.
2283 bool isLHSNull = LHSExpr == 0;
2284 if (isLHSNull)
2285 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002286
2287 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002288 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002289 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002290 return ExprError();
2291
2292 Cond.release();
2293 LHS.release();
2294 RHS.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002295 return Owned(new (Context) ConditionalOperator(CondExpr,
2296 isLHSNull ? 0 : LHSExpr,
2297 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002298}
2299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300
2301// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2302// being closely modeled after the C99 spec:-). The odd characteristic of this
2303// routine is it effectively iqnores the qualifiers on the top level pointee.
2304// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2305// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002306Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002307Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2308 QualType lhptee, rhptee;
2309
2310 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002311 lhptee = lhsType->getAsPointerType()->getPointeeType();
2312 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002313
2314 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002315 lhptee = Context.getCanonicalType(lhptee);
2316 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002317
Chris Lattner5cf216b2008-01-04 18:04:52 +00002318 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002319
2320 // C99 6.5.16.1p1: This following citation is common to constraints
2321 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2322 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002323 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002324 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002325 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002326
2327 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2328 // incomplete type and the other is a pointer to a qualified or unqualified
2329 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002330 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002331 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002332 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002333
2334 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002335 assert(rhptee->isFunctionType());
2336 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002337 }
2338
2339 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002340 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002341 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002342
2343 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002344 assert(lhptee->isFunctionType());
2345 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002346 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002347
2348 // Check for ObjC interfaces
2349 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2350 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2351 if (LHSIface && RHSIface &&
2352 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2353 return ConvTy;
2354
2355 // ID acts sort of like void* for ObjC interfaces
2356 if (LHSIface && Context.isObjCIdType(rhptee))
2357 return ConvTy;
2358 if (RHSIface && Context.isObjCIdType(lhptee))
2359 return ConvTy;
2360
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2362 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002363 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2364 rhptee.getUnqualifiedType()))
2365 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002366 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002367}
2368
Steve Naroff1c7d0672008-09-04 15:10:53 +00002369/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2370/// block pointer types are compatible or whether a block and normal pointer
2371/// are compatible. It is more restrict than comparing two function pointer
2372// types.
2373Sema::AssignConvertType
2374Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2375 QualType rhsType) {
2376 QualType lhptee, rhptee;
2377
2378 // get the "pointed to" type (ignoring qualifiers at the top level)
2379 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2380 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2381
2382 // make sure we operate on the canonical type
2383 lhptee = Context.getCanonicalType(lhptee);
2384 rhptee = Context.getCanonicalType(rhptee);
2385
2386 AssignConvertType ConvTy = Compatible;
2387
2388 // For blocks we enforce that qualifiers are identical.
2389 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2390 ConvTy = CompatiblePointerDiscardsQualifiers;
2391
2392 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2393 return IncompatibleBlockPointer;
2394 return ConvTy;
2395}
2396
Reid Spencer5f016e22007-07-11 17:01:13 +00002397/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2398/// has code to accommodate several GCC extensions when type checking
2399/// pointers. Here are some objectionable examples that GCC considers warnings:
2400///
2401/// int a, *pint;
2402/// short *pshort;
2403/// struct foo *pfoo;
2404///
2405/// pint = pshort; // warning: assignment from incompatible pointer type
2406/// a = pint; // warning: assignment makes integer from pointer without a cast
2407/// pint = a; // warning: assignment makes pointer from integer without a cast
2408/// pint = pfoo; // warning: assignment from incompatible pointer type
2409///
2410/// As a result, the code for dealing with pointers is more complex than the
2411/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002412///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002413Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002414Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002415 // Get canonical types. We're not formatting these types, just comparing
2416 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002417 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2418 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002419
2420 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002421 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002422
Douglas Gregor9d293df2008-10-28 00:22:11 +00002423 // If the left-hand side is a reference type, then we are in a
2424 // (rare!) case where we've allowed the use of references in C,
2425 // e.g., as a parameter type in a built-in function. In this case,
2426 // just make sure that the type referenced is compatible with the
2427 // right-hand side type. The caller is responsible for adjusting
2428 // lhsType so that the resulting expression does not have reference
2429 // type.
2430 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2431 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002432 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002433 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002434 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002435
Chris Lattnereca7be62008-04-07 05:30:13 +00002436 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2437 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002438 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002439 // Relax integer conversions like we do for pointers below.
2440 if (rhsType->isIntegerType())
2441 return IntToPointer;
2442 if (lhsType->isIntegerType())
2443 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002444 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002445 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002446
Nate Begemanbe2341d2008-07-14 18:02:46 +00002447 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002448 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002449 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2450 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002451 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002452
Nate Begemanbe2341d2008-07-14 18:02:46 +00002453 // If we are allowing lax vector conversions, and LHS and RHS are both
2454 // vectors, the total size only needs to be the same. This is a bitcast;
2455 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002456 if (getLangOptions().LaxVectorConversions &&
2457 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002458 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2459 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002460 }
2461 return Incompatible;
2462 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002463
Chris Lattnere8b3e962008-01-04 23:32:24 +00002464 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002465 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002466
Chris Lattner78eca282008-04-07 06:49:41 +00002467 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002469 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002470
Chris Lattner78eca282008-04-07 06:49:41 +00002471 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002473
Steve Naroffb4406862008-09-29 18:10:17 +00002474 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002475 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002476 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002477
2478 // Treat block pointers as objects.
2479 if (getLangOptions().ObjC1 &&
2480 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2481 return Compatible;
2482 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002483 return Incompatible;
2484 }
2485
2486 if (isa<BlockPointerType>(lhsType)) {
2487 if (rhsType->isIntegerType())
2488 return IntToPointer;
2489
Steve Naroffb4406862008-09-29 18:10:17 +00002490 // Treat block pointers as objects.
2491 if (getLangOptions().ObjC1 &&
2492 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2493 return Compatible;
2494
Steve Naroff1c7d0672008-09-04 15:10:53 +00002495 if (rhsType->isBlockPointerType())
2496 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2497
2498 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2499 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002500 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002501 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002502 return Incompatible;
2503 }
2504
Chris Lattner78eca282008-04-07 06:49:41 +00002505 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002507 if (lhsType == Context.BoolTy)
2508 return Compatible;
2509
2510 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002511 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002512
Chris Lattner78eca282008-04-07 06:49:41 +00002513 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002515
2516 if (isa<BlockPointerType>(lhsType) &&
2517 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002518 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002519 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002520 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002521
Chris Lattnerfc144e22008-01-04 23:18:45 +00002522 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002523 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 }
2526 return Incompatible;
2527}
2528
Chris Lattner5cf216b2008-01-04 18:04:52 +00002529Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002530Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002531 if (getLangOptions().CPlusPlus) {
2532 if (!lhsType->isRecordType()) {
2533 // C++ 5.17p3: If the left operand is not of class type, the
2534 // expression is implicitly converted (C++ 4) to the
2535 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002536 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2537 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002538 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002539 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002540 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002541 }
2542
2543 // FIXME: Currently, we fall through and treat C++ classes like C
2544 // structures.
2545 }
2546
Steve Naroff529a4ad2007-11-27 17:58:44 +00002547 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2548 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002549 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2550 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002551 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002552 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002553 return Compatible;
2554 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002555
2556 // We don't allow conversion of non-null-pointer constants to integers.
2557 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2558 return IntToBlockPointer;
2559
Chris Lattner943140e2007-10-16 02:55:40 +00002560 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002561 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002562 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002563 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002564 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002565 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002566 if (!lhsType->isReferenceType())
2567 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002568
Chris Lattner5cf216b2008-01-04 18:04:52 +00002569 Sema::AssignConvertType result =
2570 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002571
2572 // C99 6.5.16.1p2: The value of the right operand is converted to the
2573 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002574 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2575 // so that we can use references in built-in functions even in C.
2576 // The getNonReferenceType() call makes sure that the resulting expression
2577 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002578 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002579 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002580 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002581}
2582
Chris Lattner5cf216b2008-01-04 18:04:52 +00002583Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002584Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2585 return CheckAssignmentConstraints(lhsType, rhsType);
2586}
2587
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002588QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002589 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002590 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002591 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002592 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002593}
2594
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002595inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002596 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002597 // For conversion purposes, we ignore any qualifiers.
2598 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002599 QualType lhsType =
2600 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2601 QualType rhsType =
2602 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002603
Nate Begemanbe2341d2008-07-14 18:02:46 +00002604 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002605 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002607
Nate Begemanbe2341d2008-07-14 18:02:46 +00002608 // Handle the case of a vector & extvector type of the same size and element
2609 // type. It would be nice if we only had one vector type someday.
2610 if (getLangOptions().LaxVectorConversions)
2611 if (const VectorType *LV = lhsType->getAsVectorType())
2612 if (const VectorType *RV = rhsType->getAsVectorType())
2613 if (LV->getElementType() == RV->getElementType() &&
2614 LV->getNumElements() == RV->getNumElements())
2615 return lhsType->isExtVectorType() ? lhsType : rhsType;
2616
2617 // If the lhs is an extended vector and the rhs is a scalar of the same type
2618 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002619 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002620 QualType eltType = V->getElementType();
2621
2622 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2623 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2624 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002625 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002626 return lhsType;
2627 }
2628 }
2629
Nate Begemanbe2341d2008-07-14 18:02:46 +00002630 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002631 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002632 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002633 QualType eltType = V->getElementType();
2634
2635 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2636 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2637 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002638 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002639 return rhsType;
2640 }
2641 }
2642
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002644 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002645 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002646 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 return QualType();
2648}
2649
2650inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002651 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002652{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002653 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002654 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002655
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002656 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002657
Steve Naroffa4332e22007-07-17 00:58:39 +00002658 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002659 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002660 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002661}
2662
2663inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002664 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002665{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002666 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2667 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2668 return CheckVectorOperands(Loc, lex, rex);
2669 return InvalidOperands(Loc, lex, rex);
2670 }
Steve Naroff90045e82007-07-13 23:32:42 +00002671
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002672 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002673
Steve Naroffa4332e22007-07-17 00:58:39 +00002674 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002675 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002676 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002677}
2678
2679inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002680 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002681{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002682 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002683 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002684
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002685 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002686
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002688 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002689 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002690
Eli Friedmand72d16e2008-05-18 18:08:51 +00002691 // Put any potential pointer into PExp
2692 Expr* PExp = lex, *IExp = rex;
2693 if (IExp->getType()->isPointerType())
2694 std::swap(PExp, IExp);
2695
2696 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2697 if (IExp->getType()->isIntegerType()) {
2698 // Check for arithmetic on pointers to incomplete types
2699 if (!PTy->getPointeeType()->isObjectType()) {
2700 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002701 if (getLangOptions().CPlusPlus) {
2702 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2703 << lex->getSourceRange() << rex->getSourceRange();
2704 return QualType();
2705 }
2706
2707 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002708 Diag(Loc, diag::ext_gnu_void_ptr)
2709 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002710 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002711 if (getLangOptions().CPlusPlus) {
2712 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2713 << lex->getType() << lex->getSourceRange();
2714 return QualType();
2715 }
2716
2717 // GNU extension: arithmetic on pointer to function
2718 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002719 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002720 } else {
2721 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2722 diag::err_typecheck_arithmetic_incomplete_type,
2723 lex->getSourceRange(), SourceRange(),
2724 lex->getType());
2725 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002726 }
2727 }
2728 return PExp->getType();
2729 }
2730 }
2731
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002732 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002733}
2734
Chris Lattnereca7be62008-04-07 05:30:13 +00002735// C99 6.5.6
2736QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002737 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002738 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002739 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002740
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002741 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002742
Chris Lattner6e4ab612007-12-09 21:53:25 +00002743 // Enforce type constraints: C99 6.5.6p3.
2744
2745 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002746 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002747 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002748
2749 // Either ptr - int or ptr - ptr.
2750 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002751 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002752
Chris Lattner6e4ab612007-12-09 21:53:25 +00002753 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002754 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002755 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002756 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002757 Diag(Loc, diag::ext_gnu_void_ptr)
2758 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00002759 } else if (lpointee->isFunctionType()) {
2760 if (getLangOptions().CPlusPlus) {
2761 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2762 << lex->getType() << lex->getSourceRange();
2763 return QualType();
2764 }
2765
2766 // GNU extension: arithmetic on pointer to function
2767 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2768 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002769 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002770 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002771 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002772 return QualType();
2773 }
2774 }
2775
2776 // The result type of a pointer-int computation is the pointer type.
2777 if (rex->getType()->isIntegerType())
2778 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002779
Chris Lattner6e4ab612007-12-09 21:53:25 +00002780 // Handle pointer-pointer subtractions.
2781 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002782 QualType rpointee = RHSPTy->getPointeeType();
2783
Chris Lattner6e4ab612007-12-09 21:53:25 +00002784 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002785 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002786 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002787 if (rpointee->isVoidType()) {
2788 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002789 Diag(Loc, diag::ext_gnu_void_ptr)
2790 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00002791 } else if (rpointee->isFunctionType()) {
2792 if (getLangOptions().CPlusPlus) {
2793 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2794 << rex->getType() << rex->getSourceRange();
2795 return QualType();
2796 }
2797
2798 // GNU extension: arithmetic on pointer to function
2799 if (!lpointee->isFunctionType())
2800 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2801 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002802 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002803 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002804 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002805 return QualType();
2806 }
2807 }
2808
2809 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002810 if (!Context.typesAreCompatible(
2811 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2812 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002813 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002814 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002815 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002816 return QualType();
2817 }
2818
2819 return Context.getPointerDiffType();
2820 }
2821 }
2822
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002823 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002824}
2825
Chris Lattnereca7be62008-04-07 05:30:13 +00002826// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002827QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002828 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002829 // C99 6.5.7p2: Each of the operands shall have integer type.
2830 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002831 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002832
Chris Lattnerca5eede2007-12-12 05:47:28 +00002833 // Shifts don't perform usual arithmetic conversions, they just do integer
2834 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002835 if (!isCompAssign)
2836 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002837 UsualUnaryConversions(rex);
2838
2839 // "The type of the result is that of the promoted left operand."
2840 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002841}
2842
Eli Friedman3d815e72008-08-22 00:56:42 +00002843static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2844 ASTContext& Context) {
2845 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2846 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2847 // ID acts sort of like void* for ObjC interfaces
2848 if (LHSIface && Context.isObjCIdType(RHS))
2849 return true;
2850 if (RHSIface && Context.isObjCIdType(LHS))
2851 return true;
2852 if (!LHSIface || !RHSIface)
2853 return false;
2854 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2855 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2856}
2857
Chris Lattnereca7be62008-04-07 05:30:13 +00002858// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002859QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002860 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002861 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002862 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002863
Chris Lattnera5937dd2007-08-26 01:18:55 +00002864 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002865 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2866 UsualArithmeticConversions(lex, rex);
2867 else {
2868 UsualUnaryConversions(lex);
2869 UsualUnaryConversions(rex);
2870 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002871 QualType lType = lex->getType();
2872 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002873
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002874 // For non-floating point types, check for self-comparisons of the form
2875 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2876 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002877 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002878 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2879 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002880 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002881 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002882 }
2883
Douglas Gregor447b69e2008-11-19 03:25:36 +00002884 // The result of comparisons is 'bool' in C++, 'int' in C.
2885 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2886
Chris Lattnera5937dd2007-08-26 01:18:55 +00002887 if (isRelational) {
2888 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002889 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002890 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002891 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002892 if (lType->isFloatingType()) {
2893 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002894 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002895 }
2896
Chris Lattnera5937dd2007-08-26 01:18:55 +00002897 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002898 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002899 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002900
Chris Lattnerd28f8152007-08-26 01:10:14 +00002901 bool LHSIsNull = lex->isNullPointerConstant(Context);
2902 bool RHSIsNull = rex->isNullPointerConstant(Context);
2903
Chris Lattnera5937dd2007-08-26 01:18:55 +00002904 // All of the following pointer related warnings are GCC extensions, except
2905 // when handling null pointer constants. One day, we can consider making them
2906 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002907 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002908 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002909 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002910 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002911 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002912
Steve Naroff66296cb2007-11-13 14:57:38 +00002913 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002914 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2915 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002916 RCanPointeeTy.getUnqualifiedType()) &&
2917 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002918 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002919 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002921 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002922 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002923 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002924 // Handle block pointer types.
2925 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2926 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2927 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2928
2929 if (!LHSIsNull && !RHSIsNull &&
2930 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002931 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002932 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002933 }
2934 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002935 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002936 }
Steve Naroff59f53942008-09-28 01:11:11 +00002937 // Allow block pointers to be compared with null pointer constants.
2938 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2939 (lType->isPointerType() && rType->isBlockPointerType())) {
2940 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002941 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002942 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002943 }
2944 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002945 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002946 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002947
Steve Naroff20373222008-06-03 14:04:54 +00002948 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002949 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002950 const PointerType *LPT = lType->getAsPointerType();
2951 const PointerType *RPT = rType->getAsPointerType();
2952 bool LPtrToVoid = LPT ?
2953 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2954 bool RPtrToVoid = RPT ?
2955 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2956
2957 if (!LPtrToVoid && !RPtrToVoid &&
2958 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002959 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002960 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002961 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002962 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002963 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002964 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002965 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002966 }
Steve Naroff20373222008-06-03 14:04:54 +00002967 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2968 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002969 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002970 } else {
2971 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002972 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002973 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002974 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002975 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002976 }
Steve Naroff20373222008-06-03 14:04:54 +00002977 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002978 }
Steve Naroff20373222008-06-03 14:04:54 +00002979 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2980 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002981 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002982 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002983 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002984 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002985 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002986 }
Steve Naroff20373222008-06-03 14:04:54 +00002987 if (lType->isIntegerType() &&
2988 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002989 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002990 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002991 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002992 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002993 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002994 }
Steve Naroff39218df2008-09-04 16:56:14 +00002995 // Handle block pointers.
2996 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2997 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002998 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002999 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003000 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003001 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003002 }
3003 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3004 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003005 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003006 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003007 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003008 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003009 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003010 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003011}
3012
Nate Begemanbe2341d2008-07-14 18:02:46 +00003013/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3014/// operates on extended vector types. Instead of producing an IntTy result,
3015/// like a scalar comparison, a vector comparison produces a vector of integer
3016/// types.
3017QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003018 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003019 bool isRelational) {
3020 // Check to make sure we're operating on vectors of the same type and width,
3021 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003022 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003023 if (vType.isNull())
3024 return vType;
3025
3026 QualType lType = lex->getType();
3027 QualType rType = rex->getType();
3028
3029 // For non-floating point types, check for self-comparisons of the form
3030 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3031 // often indicate logic errors in the program.
3032 if (!lType->isFloatingType()) {
3033 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3034 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3035 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003036 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003037 }
3038
3039 // Check for comparisons of floating point operands using != and ==.
3040 if (!isRelational && lType->isFloatingType()) {
3041 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003042 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003043 }
3044
3045 // Return the type for the comparison, which is the same as vector type for
3046 // integer vectors, or an integer type of identical size and number of
3047 // elements for floating point vectors.
3048 if (lType->isIntegerType())
3049 return lType;
3050
3051 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003052 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003053 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003054 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003055 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3056 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3057
3058 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3059 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003060 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3061}
3062
Reid Spencer5f016e22007-07-11 17:01:13 +00003063inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003064 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003065{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003066 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003067 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003068
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003069 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003070
Steve Naroffa4332e22007-07-17 00:58:39 +00003071 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003072 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003073 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003074}
3075
3076inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003077 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003078{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003079 UsualUnaryConversions(lex);
3080 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003081
Eli Friedman5773a6c2008-05-13 20:16:47 +00003082 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003083 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003084 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003085}
3086
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003087/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3088/// is a read-only property; return true if so. A readonly property expression
3089/// depends on various declarations and thus must be treated specially.
3090///
3091static bool IsReadonlyProperty(Expr *E, Sema &S)
3092{
3093 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3094 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3095 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3096 QualType BaseType = PropExpr->getBase()->getType();
3097 if (const PointerType *PTy = BaseType->getAsPointerType())
3098 if (const ObjCInterfaceType *IFTy =
3099 PTy->getPointeeType()->getAsObjCInterfaceType())
3100 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3101 if (S.isPropertyReadonly(PDecl, IFace))
3102 return true;
3103 }
3104 }
3105 return false;
3106}
3107
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003108/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3109/// emit an error and return true. If so, return false.
3110static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003111 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3112 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3113 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003114 if (IsLV == Expr::MLV_Valid)
3115 return false;
3116
3117 unsigned Diag = 0;
3118 bool NeedType = false;
3119 switch (IsLV) { // C99 6.5.16p2
3120 default: assert(0 && "Unknown result from isModifiableLvalue!");
3121 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003122 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003123 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3124 NeedType = true;
3125 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003126 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003127 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3128 NeedType = true;
3129 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003130 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003131 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3132 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003133 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003134 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3135 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003136 case Expr::MLV_IncompleteType:
3137 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003138 return S.DiagnoseIncompleteType(Loc, E->getType(),
3139 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3140 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003141 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003142 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3143 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003144 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003145 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3146 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003147 case Expr::MLV_ReadonlyProperty:
3148 Diag = diag::error_readonly_property_assignment;
3149 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003150 case Expr::MLV_NoSetterProperty:
3151 Diag = diag::error_nosetter_property_assignment;
3152 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003154
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003155 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003156 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003157 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003158 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003159 return true;
3160}
3161
3162
3163
3164// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003165QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3166 SourceLocation Loc,
3167 QualType CompoundType) {
3168 // Verify that LHS is a modifiable lvalue, and emit error if not.
3169 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003170 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003171
3172 QualType LHSType = LHS->getType();
3173 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003174
Chris Lattner5cf216b2008-01-04 18:04:52 +00003175 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003176 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003177 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003178 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003179 // Special case of NSObject attributes on c-style pointer types.
3180 if (ConvTy == IncompatiblePointer &&
3181 ((Context.isObjCNSObjectType(LHSType) &&
3182 Context.isObjCObjectPointerType(RHSType)) ||
3183 (Context.isObjCNSObjectType(RHSType) &&
3184 Context.isObjCObjectPointerType(LHSType))))
3185 ConvTy = Compatible;
3186
Chris Lattner2c156472008-08-21 18:04:13 +00003187 // If the RHS is a unary plus or minus, check to see if they = and + are
3188 // right next to each other. If so, the user may have typo'd "x =+ 4"
3189 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003190 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003191 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3192 RHSCheck = ICE->getSubExpr();
3193 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3194 if ((UO->getOpcode() == UnaryOperator::Plus ||
3195 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003196 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003197 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003198 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003199 Diag(Loc, diag::warn_not_compound_assign)
3200 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3201 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003202 }
3203 } else {
3204 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003205 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003206 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003207
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003208 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3209 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003210 return QualType();
3211
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 // C99 6.5.16p3: The type of an assignment expression is the type of the
3213 // left operand unless the left operand has qualified type, in which case
3214 // it is the unqualified version of the type of the left operand.
3215 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3216 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003217 // C++ 5.17p1: the type of the assignment expression is that of its left
3218 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003219 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003220}
3221
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003222// C99 6.5.17
3223QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3224 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003225
3226 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003227 DefaultFunctionArrayConversion(RHS);
3228 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003229}
3230
Steve Naroff49b45262007-07-13 16:58:59 +00003231/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3232/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003233QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3234 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003235 QualType ResType = Op->getType();
3236 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003237
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003238 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3239 // Decrement of bool is not allowed.
3240 if (!isInc) {
3241 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3242 return QualType();
3243 }
3244 // Increment of bool sets it to true, but is deprecated.
3245 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3246 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003247 // OK!
3248 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3249 // C99 6.5.2.4p2, 6.5.6p2
3250 if (PT->getPointeeType()->isObjectType()) {
3251 // Pointer to object is ok!
3252 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003253 if (getLangOptions().CPlusPlus) {
3254 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3255 << Op->getSourceRange();
3256 return QualType();
3257 }
3258
3259 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003260 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003261 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003262 if (getLangOptions().CPlusPlus) {
3263 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3264 << Op->getType() << Op->getSourceRange();
3265 return QualType();
3266 }
3267
3268 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003269 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003270 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003271 } else {
3272 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3273 diag::err_typecheck_arithmetic_incomplete_type,
3274 Op->getSourceRange(), SourceRange(),
3275 ResType);
3276 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003277 }
Chris Lattner3528d352008-11-21 07:05:48 +00003278 } else if (ResType->isComplexType()) {
3279 // C99 does not support ++/-- on complex types, we allow as an extension.
3280 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003281 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003282 } else {
3283 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003284 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003285 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003286 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003287 // At this point, we know we have a real, complex or pointer type.
3288 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003289 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003290 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003291 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003292}
3293
Anders Carlsson369dee42008-02-01 07:15:58 +00003294/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003295/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003296/// where the declaration is needed for type checking. We only need to
3297/// handle cases when the expression references a function designator
3298/// or is an lvalue. Here are some examples:
3299/// - &(x) => x
3300/// - &*****f => f for f a function designator.
3301/// - &s.xx => s
3302/// - &s.zz[1].yy -> s, if zz is an array
3303/// - *(x + 1) -> x, if x is an array
3304/// - &"123"[2] -> 0
3305/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003306static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003307 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003308 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003309 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003310 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003311 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003312 // Fields cannot be declared with a 'register' storage class.
3313 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003314 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003315 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003316 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003317 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003318 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003319
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003320 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003321 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003322 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003323 return 0;
3324 else
3325 return VD;
3326 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003327 case Stmt::UnaryOperatorClass: {
3328 UnaryOperator *UO = cast<UnaryOperator>(E);
3329
3330 switch(UO->getOpcode()) {
3331 case UnaryOperator::Deref: {
3332 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003333 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3334 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3335 if (!VD || VD->getType()->isPointerType())
3336 return 0;
3337 return VD;
3338 }
3339 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003340 }
3341 case UnaryOperator::Real:
3342 case UnaryOperator::Imag:
3343 case UnaryOperator::Extension:
3344 return getPrimaryDecl(UO->getSubExpr());
3345 default:
3346 return 0;
3347 }
3348 }
3349 case Stmt::BinaryOperatorClass: {
3350 BinaryOperator *BO = cast<BinaryOperator>(E);
3351
3352 // Handle cases involving pointer arithmetic. The result of an
3353 // Assign or AddAssign is not an lvalue so they can be ignored.
3354
3355 // (x + n) or (n + x) => x
3356 if (BO->getOpcode() == BinaryOperator::Add) {
3357 if (BO->getLHS()->getType()->isPointerType()) {
3358 return getPrimaryDecl(BO->getLHS());
3359 } else if (BO->getRHS()->getType()->isPointerType()) {
3360 return getPrimaryDecl(BO->getRHS());
3361 }
3362 }
3363
3364 return 0;
3365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003366 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003367 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003368 case Stmt::ImplicitCastExprClass:
3369 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003370 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003371 default:
3372 return 0;
3373 }
3374}
3375
3376/// CheckAddressOfOperand - The operand of & must be either a function
3377/// designator or an lvalue designating an object. If it is an lvalue, the
3378/// object cannot be declared with storage class register or be a bit field.
3379/// Note: The usual conversions are *not* applied to the operand of the &
3380/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003381/// In C++, the operand might be an overloaded function name, in which case
3382/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003383QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003384 if (op->isTypeDependent())
3385 return Context.DependentTy;
3386
Steve Naroff08f19672008-01-13 17:10:08 +00003387 if (getLangOptions().C99) {
3388 // Implement C99-only parts of addressof rules.
3389 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3390 if (uOp->getOpcode() == UnaryOperator::Deref)
3391 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3392 // (assuming the deref expression is valid).
3393 return uOp->getSubExpr()->getType();
3394 }
3395 // Technically, there should be a check for array subscript
3396 // expressions here, but the result of one is always an lvalue anyway.
3397 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003398 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003399 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003400
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003402 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3403 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003404 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3405 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003406 return QualType();
3407 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003408 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003409 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3410 if (Field->isBitField()) {
3411 Diag(OpLoc, diag::err_typecheck_address_of)
3412 << "bit-field" << op->getSourceRange();
3413 return QualType();
3414 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003415 }
3416 // Check for Apple extension for accessing vector components.
3417 } else if (isa<ArraySubscriptExpr>(op) &&
3418 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003419 Diag(OpLoc, diag::err_typecheck_address_of)
3420 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003421 return QualType();
3422 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 // We have an lvalue with a decl. Make sure the decl is not declared
3424 // with the register storage-class specifier.
3425 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3426 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003427 Diag(OpLoc, diag::err_typecheck_address_of)
3428 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003429 return QualType();
3430 }
Douglas Gregor29882052008-12-10 21:26:49 +00003431 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003432 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003433 } else if (isa<FieldDecl>(dcl)) {
3434 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003435 } else if (isa<FunctionDecl>(dcl)) {
3436 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003437 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003438 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003439 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003440 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003441
Reid Spencer5f016e22007-07-11 17:01:13 +00003442 // If the operand has type "type", the result has type "pointer to type".
3443 return Context.getPointerType(op->getType());
3444}
3445
Chris Lattner22caddc2008-11-23 09:13:29 +00003446QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3447 UsualUnaryConversions(Op);
3448 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003449
Chris Lattner22caddc2008-11-23 09:13:29 +00003450 // Note that per both C89 and C99, this is always legal, even if ptype is an
3451 // incomplete type or void. It would be possible to warn about dereferencing
3452 // a void pointer, but it's completely well-defined, and such a warning is
3453 // unlikely to catch any mistakes.
3454 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003455 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003456
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003457 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003458 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003459 return QualType();
3460}
3461
3462static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3463 tok::TokenKind Kind) {
3464 BinaryOperator::Opcode Opc;
3465 switch (Kind) {
3466 default: assert(0 && "Unknown binop!");
3467 case tok::star: Opc = BinaryOperator::Mul; break;
3468 case tok::slash: Opc = BinaryOperator::Div; break;
3469 case tok::percent: Opc = BinaryOperator::Rem; break;
3470 case tok::plus: Opc = BinaryOperator::Add; break;
3471 case tok::minus: Opc = BinaryOperator::Sub; break;
3472 case tok::lessless: Opc = BinaryOperator::Shl; break;
3473 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3474 case tok::lessequal: Opc = BinaryOperator::LE; break;
3475 case tok::less: Opc = BinaryOperator::LT; break;
3476 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3477 case tok::greater: Opc = BinaryOperator::GT; break;
3478 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3479 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3480 case tok::amp: Opc = BinaryOperator::And; break;
3481 case tok::caret: Opc = BinaryOperator::Xor; break;
3482 case tok::pipe: Opc = BinaryOperator::Or; break;
3483 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3484 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3485 case tok::equal: Opc = BinaryOperator::Assign; break;
3486 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3487 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3488 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3489 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3490 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3491 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3492 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3493 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3494 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3495 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3496 case tok::comma: Opc = BinaryOperator::Comma; break;
3497 }
3498 return Opc;
3499}
3500
3501static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3502 tok::TokenKind Kind) {
3503 UnaryOperator::Opcode Opc;
3504 switch (Kind) {
3505 default: assert(0 && "Unknown unary op!");
3506 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3507 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3508 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3509 case tok::star: Opc = UnaryOperator::Deref; break;
3510 case tok::plus: Opc = UnaryOperator::Plus; break;
3511 case tok::minus: Opc = UnaryOperator::Minus; break;
3512 case tok::tilde: Opc = UnaryOperator::Not; break;
3513 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003514 case tok::kw___real: Opc = UnaryOperator::Real; break;
3515 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3516 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3517 }
3518 return Opc;
3519}
3520
Douglas Gregoreaebc752008-11-06 23:29:22 +00003521/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3522/// operator @p Opc at location @c TokLoc. This routine only supports
3523/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003524Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3525 unsigned Op,
3526 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003527 QualType ResultTy; // Result type of the binary operator.
3528 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3529 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3530
3531 switch (Opc) {
3532 default:
3533 assert(0 && "Unknown binary expr!");
3534 case BinaryOperator::Assign:
3535 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3536 break;
3537 case BinaryOperator::Mul:
3538 case BinaryOperator::Div:
3539 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3540 break;
3541 case BinaryOperator::Rem:
3542 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3543 break;
3544 case BinaryOperator::Add:
3545 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3546 break;
3547 case BinaryOperator::Sub:
3548 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3549 break;
3550 case BinaryOperator::Shl:
3551 case BinaryOperator::Shr:
3552 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3553 break;
3554 case BinaryOperator::LE:
3555 case BinaryOperator::LT:
3556 case BinaryOperator::GE:
3557 case BinaryOperator::GT:
3558 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3559 break;
3560 case BinaryOperator::EQ:
3561 case BinaryOperator::NE:
3562 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3563 break;
3564 case BinaryOperator::And:
3565 case BinaryOperator::Xor:
3566 case BinaryOperator::Or:
3567 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3568 break;
3569 case BinaryOperator::LAnd:
3570 case BinaryOperator::LOr:
3571 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3572 break;
3573 case BinaryOperator::MulAssign:
3574 case BinaryOperator::DivAssign:
3575 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3576 if (!CompTy.isNull())
3577 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3578 break;
3579 case BinaryOperator::RemAssign:
3580 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3581 if (!CompTy.isNull())
3582 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3583 break;
3584 case BinaryOperator::AddAssign:
3585 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3586 if (!CompTy.isNull())
3587 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3588 break;
3589 case BinaryOperator::SubAssign:
3590 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3591 if (!CompTy.isNull())
3592 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3593 break;
3594 case BinaryOperator::ShlAssign:
3595 case BinaryOperator::ShrAssign:
3596 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3597 if (!CompTy.isNull())
3598 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3599 break;
3600 case BinaryOperator::AndAssign:
3601 case BinaryOperator::XorAssign:
3602 case BinaryOperator::OrAssign:
3603 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3604 if (!CompTy.isNull())
3605 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3606 break;
3607 case BinaryOperator::Comma:
3608 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3609 break;
3610 }
3611 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003612 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003613 if (CompTy.isNull())
3614 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3615 else
3616 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff9e0b6002009-01-20 21:06:31 +00003617 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003618}
3619
Reid Spencer5f016e22007-07-11 17:01:13 +00003620// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003621Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3622 tok::TokenKind Kind,
3623 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003624 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003625 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003626
Steve Narofff69936d2007-09-16 03:34:24 +00003627 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3628 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003629
Douglas Gregor898574e2008-12-05 23:32:09 +00003630 // If either expression is type-dependent, just build the AST.
3631 // FIXME: We'll need to perform some caching of the result of name
3632 // lookup for operator+.
3633 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003634 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3635 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003636 Context.DependentTy,
3637 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003638 else
3639 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3640 TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003641 }
3642
Douglas Gregoreaebc752008-11-06 23:29:22 +00003643 if (getLangOptions().CPlusPlus &&
3644 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3645 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003646 // If this is one of the assignment operators, we only perform
3647 // overload resolution if the left-hand side is a class or
3648 // enumeration type (C++ [expr.ass]p3).
3649 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3650 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3651 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3652 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003653
Douglas Gregoreaebc752008-11-06 23:29:22 +00003654 // Determine which overloaded operator we're dealing with.
3655 static const OverloadedOperatorKind OverOps[] = {
3656 OO_Star, OO_Slash, OO_Percent,
3657 OO_Plus, OO_Minus,
3658 OO_LessLess, OO_GreaterGreater,
3659 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3660 OO_EqualEqual, OO_ExclaimEqual,
3661 OO_Amp,
3662 OO_Caret,
3663 OO_Pipe,
3664 OO_AmpAmp,
3665 OO_PipePipe,
3666 OO_Equal, OO_StarEqual,
3667 OO_SlashEqual, OO_PercentEqual,
3668 OO_PlusEqual, OO_MinusEqual,
3669 OO_LessLessEqual, OO_GreaterGreaterEqual,
3670 OO_AmpEqual, OO_CaretEqual,
3671 OO_PipeEqual,
3672 OO_Comma
3673 };
3674 OverloadedOperatorKind OverOp = OverOps[Opc];
3675
Douglas Gregor96176b32008-11-18 23:14:02 +00003676 // Add the appropriate overloaded operators (C++ [over.match.oper])
3677 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003678 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003679 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003680 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003681
3682 // Perform overload resolution.
3683 OverloadCandidateSet::iterator Best;
3684 switch (BestViableFunction(CandidateSet, Best)) {
3685 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003686 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003687 FunctionDecl *FnDecl = Best->Function;
3688
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003689 if (FnDecl) {
3690 // We matched an overloaded operator. Build a call to that
3691 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003692
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003693 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3695 if (PerformObjectArgumentInitialization(lhs, Method) ||
3696 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3697 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003698 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003699 } else {
3700 // Convert the arguments.
3701 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3702 "passing") ||
3703 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3704 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003705 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003706 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003707
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003708 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003709 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003710 = FnDecl->getType()->getAsFunctionType()->getResultType();
3711 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003712
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003713 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003714 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3715 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00003716 UsualUnaryConversions(FnExpr);
3717
Steve Naroff6ece14c2009-01-21 00:14:39 +00003718 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3719 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003720 } else {
3721 // We matched a built-in operator. Convert the arguments, then
3722 // break out so that we will build the appropriate built-in
3723 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003724 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3725 Best->Conversions[0], "passing") ||
3726 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3727 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003728 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003729
3730 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003731 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003732 }
3733
3734 case OR_No_Viable_Function:
3735 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003736 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003737 break;
3738
3739 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003740 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3741 << BinaryOperator::getOpcodeStr(Opc)
3742 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003743 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003744 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003745 }
3746
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003747 // Either we found no viable overloaded operator or we matched a
3748 // built-in operator. In either case, fall through to trying to
3749 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003750 }
3751
Douglas Gregoreaebc752008-11-06 23:29:22 +00003752 // Build a built-in binary operation.
3753 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003754}
3755
3756// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003757Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3758 tok::TokenKind Op, ExprArg input) {
3759 // FIXME: Input is modified later, but smart pointer not reassigned.
3760 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003761 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003762
3763 if (getLangOptions().CPlusPlus &&
3764 (Input->getType()->isRecordType()
3765 || Input->getType()->isEnumeralType())) {
3766 // Determine which overloaded operator we're dealing with.
3767 static const OverloadedOperatorKind OverOps[] = {
3768 OO_None, OO_None,
3769 OO_PlusPlus, OO_MinusMinus,
3770 OO_Amp, OO_Star,
3771 OO_Plus, OO_Minus,
3772 OO_Tilde, OO_Exclaim,
3773 OO_None, OO_None,
3774 OO_None,
3775 OO_None
3776 };
3777 OverloadedOperatorKind OverOp = OverOps[Opc];
3778
3779 // Add the appropriate overloaded operators (C++ [over.match.oper])
3780 // to the candidate set.
3781 OverloadCandidateSet CandidateSet;
3782 if (OverOp != OO_None)
3783 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3784
3785 // Perform overload resolution.
3786 OverloadCandidateSet::iterator Best;
3787 switch (BestViableFunction(CandidateSet, Best)) {
3788 case OR_Success: {
3789 // We found a built-in operator or an overloaded operator.
3790 FunctionDecl *FnDecl = Best->Function;
3791
3792 if (FnDecl) {
3793 // We matched an overloaded operator. Build a call to that
3794 // operator.
3795
3796 // Convert the arguments.
3797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3798 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003799 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003800 } else {
3801 // Convert the arguments.
3802 if (PerformCopyInitialization(Input,
3803 FnDecl->getParamDecl(0)->getType(),
3804 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003805 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003806 }
3807
3808 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003809 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003810 = FnDecl->getType()->getAsFunctionType()->getResultType();
3811 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003812
Douglas Gregor74253732008-11-19 15:42:04 +00003813 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003814 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3815 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00003816 UsualUnaryConversions(FnExpr);
3817
Sebastian Redl0eb23302009-01-19 00:08:26 +00003818 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003819 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3820 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003821 } else {
3822 // We matched a built-in operator. Convert the arguments, then
3823 // break out so that we will build the appropriate built-in
3824 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003825 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3826 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003827 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003828
3829 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003830 }
Douglas Gregor74253732008-11-19 15:42:04 +00003831 }
3832
3833 case OR_No_Viable_Function:
3834 // No viable function; fall through to handling this as a
3835 // built-in operator, which will produce an error message for us.
3836 break;
3837
3838 case OR_Ambiguous:
3839 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3840 << UnaryOperator::getOpcodeStr(Opc)
3841 << Input->getSourceRange();
3842 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003843 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003844 }
3845
3846 // Either we found no viable overloaded operator or we matched a
3847 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003848 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003849 }
3850
Reid Spencer5f016e22007-07-11 17:01:13 +00003851 QualType resultType;
3852 switch (Opc) {
3853 default:
3854 assert(0 && "Unimplemented unary expr!");
3855 case UnaryOperator::PreInc:
3856 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003857 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3858 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003859 break;
3860 case UnaryOperator::AddrOf:
3861 resultType = CheckAddressOfOperand(Input, OpLoc);
3862 break;
3863 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003864 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003865 resultType = CheckIndirectionOperand(Input, OpLoc);
3866 break;
3867 case UnaryOperator::Plus:
3868 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003869 UsualUnaryConversions(Input);
3870 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003871 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3872 break;
3873 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3874 resultType->isEnumeralType())
3875 break;
3876 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3877 Opc == UnaryOperator::Plus &&
3878 resultType->isPointerType())
3879 break;
3880
Sebastian Redl0eb23302009-01-19 00:08:26 +00003881 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3882 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003883 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003884 UsualUnaryConversions(Input);
3885 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003886 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3887 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3888 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003889 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003890 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003891 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003892 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3893 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003894 break;
3895 case UnaryOperator::LNot: // logical negation
3896 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003897 DefaultFunctionArrayConversion(Input);
3898 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003899 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00003900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3901 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003902 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003903 // In C++, it's bool. C++ 5.3.1p8
3904 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003905 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003906 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003907 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003908 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003909 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003910 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003911 resultType = Input->getType();
3912 break;
3913 }
3914 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003915 return ExprError();
3916 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003917 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003918}
3919
Steve Naroff1b273c42007-09-16 14:56:35 +00003920/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3921Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003922 SourceLocation LabLoc,
3923 IdentifierInfo *LabelII) {
3924 // Look up the record for this label identifier.
3925 LabelStmt *&LabelDecl = LabelMap[LabelII];
3926
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003927 // If we haven't seen this label yet, create a forward reference. It
3928 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003929 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00003930 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00003931
3932 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003933 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3934 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003935}
3936
Steve Naroff1b273c42007-09-16 14:56:35 +00003937Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003938 SourceLocation RPLoc) { // "({..})"
3939 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3940 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3941 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3942
3943 // FIXME: there are a variety of strange constraints to enforce here, for
3944 // example, it is not possible to goto into a stmt expression apparently.
3945 // More semantic analysis is needed.
3946
3947 // FIXME: the last statement in the compount stmt has its value used. We
3948 // should not warn about it being unused.
3949
3950 // If there are sub stmts in the compound stmt, take the type of the last one
3951 // as the type of the stmtexpr.
3952 QualType Ty = Context.VoidTy;
3953
Chris Lattner611b2ec2008-07-26 19:51:01 +00003954 if (!Compound->body_empty()) {
3955 Stmt *LastStmt = Compound->body_back();
3956 // If LastStmt is a label, skip down through into the body.
3957 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3958 LastStmt = Label->getSubStmt();
3959
3960 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003961 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003962 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003963
Steve Naroff6ece14c2009-01-21 00:14:39 +00003964 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003965}
Steve Naroffd34e9152007-08-01 22:05:33 +00003966
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003967Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3968 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003969 SourceLocation TypeLoc,
3970 TypeTy *argty,
3971 OffsetOfComponent *CompPtr,
3972 unsigned NumComponents,
3973 SourceLocation RPLoc) {
3974 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3975 assert(!ArgTy.isNull() && "Missing type argument!");
3976
3977 // We must have at least one component that refers to the type, and the first
3978 // one is known to be a field designator. Verify that the ArgTy represents
3979 // a struct/union/class.
3980 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003981 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003982
3983 // Otherwise, create a compound literal expression as the base, and
3984 // iteratively process the offsetof designators.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003985 Expr *Res = new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, 0,
3986 false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003987
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003988 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3989 // GCC extension, diagnose them.
3990 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003991 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3992 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003993
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003994 for (unsigned i = 0; i != NumComponents; ++i) {
3995 const OffsetOfComponent &OC = CompPtr[i];
3996 if (OC.isBrackets) {
3997 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003998 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003999 if (!AT) {
4000 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004001 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004002 }
4003
Chris Lattner704fe352007-08-30 17:59:59 +00004004 // FIXME: C++: Verify that operator[] isn't overloaded.
4005
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004006 // C99 6.5.2.1p1
4007 Expr *Idx = static_cast<Expr*>(OC.U.E);
4008 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004009 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4010 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004011
Steve Naroff6ece14c2009-01-21 00:14:39 +00004012 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4013 OC.LocEnd);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004014 continue;
4015 }
4016
4017 const RecordType *RC = Res->getType()->getAsRecordType();
4018 if (!RC) {
4019 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004020 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004021 }
4022
4023 // Get the decl corresponding to this.
4024 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004025 FieldDecl *MemberDecl
4026 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
4027 Decl::IDNS_Ordinary,
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004028 S, RD, false, false).getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004029 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00004030 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4031 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00004032
4033 // FIXME: C++: Verify that MemberDecl isn't a static field.
4034 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00004035 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4036 // matter here.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004037 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4038 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004039 }
4040
Steve Naroff6ece14c2009-01-21 00:14:39 +00004041 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4042 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004043}
4044
4045
Steve Naroff1b273c42007-09-16 14:56:35 +00004046Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004047 TypeTy *arg1, TypeTy *arg2,
4048 SourceLocation RPLoc) {
4049 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4050 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4051
4052 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4053
Steve Naroff6ece14c2009-01-21 00:14:39 +00004054 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4055 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004056}
4057
Steve Naroff1b273c42007-09-16 14:56:35 +00004058Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004059 ExprTy *expr1, ExprTy *expr2,
4060 SourceLocation RPLoc) {
4061 Expr *CondExpr = static_cast<Expr*>(cond);
4062 Expr *LHSExpr = static_cast<Expr*>(expr1);
4063 Expr *RHSExpr = static_cast<Expr*>(expr2);
4064
4065 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4066
4067 // The conditional expression is required to be a constant expression.
4068 llvm::APSInt condEval(32);
4069 SourceLocation ExpLoc;
4070 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004071 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4072 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004073
4074 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4075 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4076 RHSExpr->getType();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004077 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4078 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004079}
4080
Steve Naroff4eb206b2008-09-03 18:15:37 +00004081//===----------------------------------------------------------------------===//
4082// Clang Extensions.
4083//===----------------------------------------------------------------------===//
4084
4085/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004086void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004087 // Analyze block parameters.
4088 BlockSemaInfo *BSI = new BlockSemaInfo();
4089
4090 // Add BSI to CurBlock.
4091 BSI->PrevBlockInfo = CurBlock;
4092 CurBlock = BSI;
4093
4094 BSI->ReturnType = 0;
4095 BSI->TheScope = BlockScope;
4096
Steve Naroff090276f2008-10-10 01:28:17 +00004097 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004098 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004099}
4100
4101void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004102 // Analyze arguments to block.
4103 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4104 "Not a function declarator!");
4105 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4106
Steve Naroff090276f2008-10-10 01:28:17 +00004107 CurBlock->hasPrototype = FTI.hasPrototype;
4108 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004109
4110 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4111 // no arguments, not a function that takes a single void argument.
4112 if (FTI.hasPrototype &&
4113 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4114 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4115 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4116 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004117 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004118 } else if (FTI.hasPrototype) {
4119 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004120 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4121 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004122 }
Steve Naroff090276f2008-10-10 01:28:17 +00004123 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4124
4125 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4126 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4127 // If this has an identifier, add it to the scope stack.
4128 if ((*AI)->getIdentifier())
4129 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004130}
4131
4132/// ActOnBlockError - If there is an error parsing a block, this callback
4133/// is invoked to pop the information about the block from the action impl.
4134void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4135 // Ensure that CurBlock is deleted.
4136 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4137
4138 // Pop off CurBlock, handle nested blocks.
4139 CurBlock = CurBlock->PrevBlockInfo;
4140
4141 // FIXME: Delete the ParmVarDecl objects as well???
4142
4143}
4144
4145/// ActOnBlockStmtExpr - This is called when the body of a block statement
4146/// literal was successfully completed. ^(int x){...}
4147Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4148 Scope *CurScope) {
4149 // Ensure that CurBlock is deleted.
4150 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4151 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4152
Steve Naroff090276f2008-10-10 01:28:17 +00004153 PopDeclContext();
4154
Steve Naroff4eb206b2008-09-03 18:15:37 +00004155 // Pop off CurBlock, handle nested blocks.
4156 CurBlock = CurBlock->PrevBlockInfo;
4157
4158 QualType RetTy = Context.VoidTy;
4159 if (BSI->ReturnType)
4160 RetTy = QualType(BSI->ReturnType, 0);
4161
4162 llvm::SmallVector<QualType, 8> ArgTypes;
4163 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4164 ArgTypes.push_back(BSI->Params[i]->getType());
4165
4166 QualType BlockTy;
4167 if (!BSI->hasPrototype)
4168 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4169 else
4170 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004171 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004172
4173 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004174
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004175 BSI->TheDecl->setBody(Body.take());
Steve Naroff6ece14c2009-01-21 00:14:39 +00004176 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004177}
4178
Nate Begeman67295d02008-01-30 20:50:20 +00004179/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004180/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004181/// The number of arguments has already been validated to match the number of
4182/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004183static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4184 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004185 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004186 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004187 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4188 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004189
4190 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004191 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004192 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004193 return true;
4194}
4195
4196Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4197 SourceLocation *CommaLocs,
4198 SourceLocation BuiltinLoc,
4199 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004200 // __builtin_overload requires at least 2 arguments
4201 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004202 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4203 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004204
Nate Begemane2ce1d92008-01-17 17:46:27 +00004205 // The first argument is required to be a constant expression. It tells us
4206 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004207 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004208 Expr *NParamsExpr = Args[0];
4209 llvm::APSInt constEval(32);
4210 SourceLocation ExpLoc;
4211 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004212 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4213 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004214
4215 // Verify that the number of parameters is > 0
4216 unsigned NumParams = constEval.getZExtValue();
4217 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004218 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4219 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004220 // Verify that we have at least 1 + NumParams arguments to the builtin.
4221 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004222 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4223 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004224
4225 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004226 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004227 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004228 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4229 // UsualUnaryConversions will convert the function DeclRefExpr into a
4230 // pointer to function.
4231 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004232 const FunctionTypeProto *FnType = 0;
4233 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4234 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004235
4236 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4237 // parameters, and the number of parameters must match the value passed to
4238 // the builtin.
4239 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004240 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4241 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004242
4243 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004244 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004245 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004246 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004247 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004248 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4249 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004250 // Remember our match, and continue processing the remaining arguments
4251 // to catch any errors.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004252 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor9d293df2008-10-28 00:22:11 +00004253 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004254 BuiltinLoc, RParenLoc);
4255 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004256 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004257 // Return the newly created OverloadExpr node, if we succeded in matching
4258 // exactly one of the candidate functions.
4259 if (OE)
4260 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004261
4262 // If we didn't find a matching function Expr in the __builtin_overload list
4263 // the return an error.
4264 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004265 for (unsigned i = 0; i != NumParams; ++i) {
4266 if (i != 0) typeNames += ", ";
4267 typeNames += Args[i+1]->getType().getAsString();
4268 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004269
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004270 return Diag(BuiltinLoc, diag::err_overload_no_match)
4271 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004272}
4273
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004274Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4275 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004276 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004277 Expr *E = static_cast<Expr*>(expr);
4278 QualType T = QualType::getFromOpaquePtr(type);
4279
4280 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004281
4282 // Get the va_list type
4283 QualType VaListType = Context.getBuiltinVaListType();
4284 // Deal with implicit array decay; for example, on x86-64,
4285 // va_list is an array, but it's supposed to decay to
4286 // a pointer for va_arg.
4287 if (VaListType->isArrayType())
4288 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004289 // Make sure the input expression also decays appropriately.
4290 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004291
4292 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004293 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004294 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004295 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004296
4297 // FIXME: Warn if a non-POD type is passed in.
4298
Steve Naroff6ece14c2009-01-21 00:14:39 +00004299 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004300}
4301
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004302Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4303 // The type of __null will be int or long, depending on the size of
4304 // pointers on the target.
4305 QualType Ty;
4306 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4307 Ty = Context.IntTy;
4308 else
4309 Ty = Context.LongTy;
4310
Steve Naroff6ece14c2009-01-21 00:14:39 +00004311 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004312}
4313
Chris Lattner5cf216b2008-01-04 18:04:52 +00004314bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4315 SourceLocation Loc,
4316 QualType DstType, QualType SrcType,
4317 Expr *SrcExpr, const char *Flavor) {
4318 // Decode the result (notice that AST's are still created for extensions).
4319 bool isInvalid = false;
4320 unsigned DiagKind;
4321 switch (ConvTy) {
4322 default: assert(0 && "Unknown conversion type");
4323 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004324 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004325 DiagKind = diag::ext_typecheck_convert_pointer_int;
4326 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004327 case IntToPointer:
4328 DiagKind = diag::ext_typecheck_convert_int_pointer;
4329 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004330 case IncompatiblePointer:
4331 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4332 break;
4333 case FunctionVoidPointer:
4334 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4335 break;
4336 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004337 // If the qualifiers lost were because we were applying the
4338 // (deprecated) C++ conversion from a string literal to a char*
4339 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4340 // Ideally, this check would be performed in
4341 // CheckPointerTypesForAssignment. However, that would require a
4342 // bit of refactoring (so that the second argument is an
4343 // expression, rather than a type), which should be done as part
4344 // of a larger effort to fix CheckPointerTypesForAssignment for
4345 // C++ semantics.
4346 if (getLangOptions().CPlusPlus &&
4347 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4348 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004349 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4350 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004351 case IntToBlockPointer:
4352 DiagKind = diag::err_int_to_block_pointer;
4353 break;
4354 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004355 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004356 break;
Steve Naroff39579072008-10-14 22:18:38 +00004357 case IncompatibleObjCQualifiedId:
4358 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4359 // it can give a more specific diagnostic.
4360 DiagKind = diag::warn_incompatible_qualified_id;
4361 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004362 case Incompatible:
4363 DiagKind = diag::err_typecheck_convert_incompatible;
4364 isInvalid = true;
4365 break;
4366 }
4367
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004368 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4369 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004370 return isInvalid;
4371}
Anders Carlssone21555e2008-11-30 19:50:32 +00004372
4373bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4374{
4375 Expr::EvalResult EvalResult;
4376
4377 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4378 EvalResult.HasSideEffects) {
4379 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4380
4381 if (EvalResult.Diag) {
4382 // We only show the note if it's not the usual "invalid subexpression"
4383 // or if it's actually in a subexpression.
4384 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4385 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4386 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4387 }
4388
4389 return true;
4390 }
4391
4392 if (EvalResult.Diag) {
4393 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4394 E->getSourceRange();
4395
4396 // Print the reason it's not a constant.
4397 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4398 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4399 }
4400
4401 if (Result)
4402 *Result = EvalResult.Val.getInt();
4403 return false;
4404}