blob: ddd5349c1564605f77a3a37616891332d2cc5800 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000024#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
Chris Lattner299b8842008-07-25 21:10:04 +000037 if (Ty->isFunctionType())
38 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000039 else if (Ty->isArrayType()) {
40 // In C90 mode, arrays only promote to pointers if the array expression is
41 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
42 // type 'array of type' is converted to an expression that has type 'pointer
43 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
44 // that has type 'array of type' ...". The relevant change is "an lvalue"
45 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000046 //
47 // C++ 4.2p1:
48 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
49 // T" can be converted to an rvalue of type "pointer to T".
50 //
51 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
52 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000053 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
54 }
Chris Lattner299b8842008-07-25 21:10:04 +000055}
56
57/// UsualUnaryConversions - Performs various conversions that are common to most
58/// operators (C99 6.3). The conversions of array and function types are
59/// sometimes surpressed. For example, the array->pointer conversion doesn't
60/// apply if the array is an argument to the sizeof or address (&) operators.
61/// In these instances, this routine should *not* be called.
62Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
63 QualType Ty = Expr->getType();
64 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
65
Chris Lattner299b8842008-07-25 21:10:04 +000066 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner9305c3d2008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000089// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
90// will warn if the resulting type is not a POD type.
91void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
92
93{
94 DefaultArgumentPromotion(Expr);
95
96 if (!Expr->getType()->isPODType()) {
97 Diag(Expr->getLocStart(),
98 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
99 Expr->getType() << CT;
100 }
101}
102
103
Chris Lattner299b8842008-07-25 21:10:04 +0000104/// UsualArithmeticConversions - Performs various conversions that are common to
105/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
106/// routine returns the first non-arithmetic type found. The client is
107/// responsible for emitting appropriate error diagnostics.
108/// FIXME: verify the conversion rules for "complex int" are consistent with
109/// GCC.
110QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
111 bool isCompAssign) {
112 if (!isCompAssign) {
113 UsualUnaryConversions(lhsExpr);
114 UsualUnaryConversions(rhsExpr);
115 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000116
Chris Lattner299b8842008-07-25 21:10:04 +0000117 // For conversion purposes, we ignore any qualifiers.
118 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000119 QualType lhs =
120 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
121 QualType rhs =
122 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000123
124 // If both types are identical, no conversion is needed.
125 if (lhs == rhs)
126 return lhs;
127
128 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
129 // The caller can deal with this (e.g. pointer + int).
130 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
131 return lhs;
132
133 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
134 if (!isCompAssign) {
135 ImpCastExprToType(lhsExpr, destType);
136 ImpCastExprToType(rhsExpr, destType);
137 }
138 return destType;
139}
140
141QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
142 // Perform the usual unary conversions. We do this early so that
143 // integral promotions to "int" can allow us to exit early, in the
144 // lhs == rhs check. Also, for conversion purposes, we ignore any
145 // qualifiers. For example, "const float" and "float" are
146 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000147 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
148 else lhs = lhs.getUnqualifiedType();
149 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
150 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000151
Chris Lattner299b8842008-07-25 21:10:04 +0000152 // If both types are identical, no conversion is needed.
153 if (lhs == rhs)
154 return lhs;
155
156 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
157 // The caller can deal with this (e.g. pointer + int).
158 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
159 return lhs;
160
161 // At this point, we have two different arithmetic types.
162
163 // Handle complex types first (C99 6.3.1.8p1).
164 if (lhs->isComplexType() || rhs->isComplexType()) {
165 // if we have an integer operand, the result is the complex type.
166 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
167 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000168 return lhs;
169 }
170 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
171 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000172 return rhs;
173 }
174 // This handles complex/complex, complex/float, or float/complex.
175 // When both operands are complex, the shorter operand is converted to the
176 // type of the longer, and that is the type of the result. This corresponds
177 // to what is done when combining two real floating-point operands.
178 // The fun begins when size promotion occur across type domains.
179 // From H&S 6.3.4: When one operand is complex and the other is a real
180 // floating-point type, the less precise type is converted, within it's
181 // real or complex domain, to the precision of the other type. For example,
182 // when combining a "long double" with a "double _Complex", the
183 // "double _Complex" is promoted to "long double _Complex".
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // The left side is bigger, convert rhs.
187 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000188 } else if (result < 0) { // The right side is bigger, convert lhs.
189 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000190 }
191 // At this point, lhs and rhs have the same rank/size. Now, make sure the
192 // domains match. This is a requirement for our implementation, C99
193 // does not require this promotion.
194 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
195 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000196 return rhs;
197 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return lhs;
199 }
200 }
201 return lhs; // The domain/size match exactly.
202 }
203 // Now handle "real" floating types (i.e. float, double, long double).
204 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
205 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000206 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000207 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return lhs;
209 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000210 if (rhs->isComplexIntegerType()) {
211 // convert rhs to the complex floating point type.
212 return Context.getComplexType(lhs);
213 }
214 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000215 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000218 if (lhs->isComplexIntegerType()) {
219 // convert lhs to the complex floating point type.
220 return Context.getComplexType(rhs);
221 }
Chris Lattner299b8842008-07-25 21:10:04 +0000222 // We have two real floating types, float/complex combos were handled above.
223 // Convert the smaller operand to the bigger result.
224 int result = Context.getFloatingTypeOrder(lhs, rhs);
225
226 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000227 return lhs;
228 }
229 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000230 return rhs;
231 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000232 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000233 }
234 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
235 // Handle GCC complex int extension.
236 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
237 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
238
239 if (lhsComplexInt && rhsComplexInt) {
240 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
241 rhsComplexInt->getElementType()) >= 0) {
242 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000243 return lhs;
244 }
Chris Lattner299b8842008-07-25 21:10:04 +0000245 return rhs;
246 } else if (lhsComplexInt && rhs->isIntegerType()) {
247 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000248 return lhs;
249 } else if (rhsComplexInt && lhs->isIntegerType()) {
250 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000251 return rhs;
252 }
253 }
254 // Finally, we have two differing integer types.
255 // The rules for this case are in C99 6.3.1.8
256 int compare = Context.getIntegerTypeOrder(lhs, rhs);
257 bool lhsSigned = lhs->isSignedIntegerType(),
258 rhsSigned = rhs->isSignedIntegerType();
259 QualType destType;
260 if (lhsSigned == rhsSigned) {
261 // Same signedness; use the higher-ranked type
262 destType = compare >= 0 ? lhs : rhs;
263 } else if (compare != (lhsSigned ? 1 : -1)) {
264 // The unsigned type has greater than or equal rank to the
265 // signed type, so use the unsigned type
266 destType = lhsSigned ? rhs : lhs;
267 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
268 // The two types are different widths; if we are here, that
269 // means the signed type is larger than the unsigned type, so
270 // use the signed type.
271 destType = lhsSigned ? lhs : rhs;
272 } else {
273 // The signed type is higher-ranked than the unsigned type,
274 // but isn't actually any bigger (like unsigned int and long
275 // on most 32-bit systems). Use the unsigned type corresponding
276 // to the signed type.
277 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
278 }
Chris Lattner299b8842008-07-25 21:10:04 +0000279 return destType;
280}
281
282//===----------------------------------------------------------------------===//
283// Semantic Analysis for various Expression Types
284//===----------------------------------------------------------------------===//
285
286
Steve Naroff87d58b42007-09-16 03:34:24 +0000287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000288/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
290/// multiple tokens. However, the common case is that StringToks points to one
291/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000292///
293Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000295 assert(NumStringToks && "Must have at least one string!");
296
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000297 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000298 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000299 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000300
301 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
302 for (unsigned i = 0; i != NumStringToks; ++i)
303 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000306 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000308
309 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
310 if (getLangOptions().CPlusPlus)
311 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000312
Chris Lattnera6dcce32008-02-11 00:02:17 +0000313 // Get an array type for the string, according to C99 6.4.5. This includes
314 // the nul terminator character as well as the string length for pascal
315 // strings.
316 StrTy = Context.getConstantArrayType(StrTy,
317 llvm::APInt(32, Literal.GetStringLength()+1),
318 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000319
Chris Lattner4b009652007-07-25 00:24:17 +0000320 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff774e4152009-01-21 00:14:39 +0000321 return Owned(new (Context) StringLiteral(Literal.GetString(),
322 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff0acc9c92007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
366 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor566782a2009-01-06 05:10:23 +0000370/// BuildDeclRefExpr - Build either a DeclRefExpr or a
371/// QualifiedDeclRefExpr based on whether or not SS is a
372/// nested-name-specifier.
373DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
374 bool TypeDependent, bool ValueDependent,
375 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000376 if (SS && !SS->isEmpty())
377 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000378 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000379 else
380 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000381}
382
Douglas Gregor723d3332009-01-07 00:43:41 +0000383/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
384/// variable corresponding to the anonymous union or struct whose type
385/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000386static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000387 assert(Record->isAnonymousStructOrUnion() &&
388 "Record must be an anonymous struct or union!");
389
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000390 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000391 // be an O(1) operation rather than a slow walk through DeclContext's
392 // vector (which itself will be eliminated). DeclGroups might make
393 // this even better.
394 DeclContext *Ctx = Record->getDeclContext();
395 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
396 DEnd = Ctx->decls_end();
397 D != DEnd; ++D) {
398 if (*D == Record) {
399 // The object for the anonymous struct/union directly
400 // follows its type in the list of declarations.
401 ++D;
402 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000403 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000404 return *D;
405 }
406 }
407
408 assert(false && "Missing object for anonymous record");
409 return 0;
410}
411
Sebastian Redlcd883f72009-01-18 18:53:16 +0000412Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000413Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
414 FieldDecl *Field,
415 Expr *BaseObjectExpr,
416 SourceLocation OpLoc) {
417 assert(Field->getDeclContext()->isRecord() &&
418 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
419 && "Field must be stored inside an anonymous struct or union");
420
421 // Construct the sequence of field member references
422 // we'll have to perform to get to the field in the anonymous
423 // union/struct. The list of members is built from the field
424 // outward, so traverse it backwards to go from an object in
425 // the current context to the field we found.
426 llvm::SmallVector<FieldDecl *, 4> AnonFields;
427 AnonFields.push_back(Field);
428 VarDecl *BaseObject = 0;
429 DeclContext *Ctx = Field->getDeclContext();
430 do {
431 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000432 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000433 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
434 AnonFields.push_back(AnonField);
435 else {
436 BaseObject = cast<VarDecl>(AnonObject);
437 break;
438 }
439 Ctx = Ctx->getParent();
440 } while (Ctx->isRecord() &&
441 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
442
443 // Build the expression that refers to the base object, from
444 // which we will build a sequence of member references to each
445 // of the anonymous union objects and, eventually, the field we
446 // found via name lookup.
447 bool BaseObjectIsPointer = false;
448 unsigned ExtraQuals = 0;
449 if (BaseObject) {
450 // BaseObject is an anonymous struct/union variable (and is,
451 // therefore, not part of another non-anonymous record).
452 delete BaseObjectExpr;
453
Steve Naroff774e4152009-01-21 00:14:39 +0000454 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000455 SourceLocation());
456 ExtraQuals
457 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
458 } else if (BaseObjectExpr) {
459 // The caller provided the base object expression. Determine
460 // whether its a pointer and whether it adds any qualifiers to the
461 // anonymous struct/union fields we're looking into.
462 QualType ObjectType = BaseObjectExpr->getType();
463 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
464 BaseObjectIsPointer = true;
465 ObjectType = ObjectPtr->getPointeeType();
466 }
467 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
468 } else {
469 // We've found a member of an anonymous struct/union that is
470 // inside a non-anonymous struct/union, so in a well-formed
471 // program our base object expression is "this".
472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
473 if (!MD->isStatic()) {
474 QualType AnonFieldType
475 = Context.getTagDeclType(
476 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
477 QualType ThisType = Context.getTagDeclType(MD->getParent());
478 if ((Context.getCanonicalType(AnonFieldType)
479 == Context.getCanonicalType(ThisType)) ||
480 IsDerivedFrom(ThisType, AnonFieldType)) {
481 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000482 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000483 MD->getThisType(Context));
484 BaseObjectIsPointer = true;
485 }
486 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000487 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
488 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000489 }
490 ExtraQuals = MD->getTypeQualifiers();
491 }
492
493 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000494 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
495 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000496 }
497
498 // Build the implicit member references to the field of the
499 // anonymous struct/union.
500 Expr *Result = BaseObjectExpr;
501 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
502 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
503 FI != FIEnd; ++FI) {
504 QualType MemberType = (*FI)->getType();
505 if (!(*FI)->isMutable()) {
506 unsigned combinedQualifiers
507 = MemberType.getCVRQualifiers() | ExtraQuals;
508 MemberType = MemberType.getQualifiedType(combinedQualifiers);
509 }
Steve Naroff774e4152009-01-21 00:14:39 +0000510 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
511 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000512 BaseObjectIsPointer = false;
513 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
514 OpLoc = SourceLocation();
515 }
516
Sebastian Redlcd883f72009-01-18 18:53:16 +0000517 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000518}
519
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000520/// ActOnDeclarationNameExpr - The parser has read some kind of name
521/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
522/// performs lookup on that name and returns an expression that refers
523/// to that name. This routine isn't directly called from the parser,
524/// because the parser doesn't know about DeclarationName. Rather,
525/// this routine is called by ActOnIdentifierExpr,
526/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
527/// which form the DeclarationName from the corresponding syntactic
528/// forms.
529///
530/// HasTrailingLParen indicates whether this identifier is used in a
531/// function call context. LookupCtx is only used for a C++
532/// qualified-id (foo::bar) to indicate the class or namespace that
533/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000534///
535/// If ForceResolution is true, then we will attempt to resolve the
536/// name even if it looks like a dependent name. This option is off by
537/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000538Sema::OwningExprResult
539Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
540 DeclarationName Name, bool HasTrailingLParen,
541 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000542 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
543 HasTrailingLParen && !SS && !ForceResolution) {
544 // We've seen something of the form
545 // identifier(
546 // and we are in a template, so it is likely that 's' is a
547 // dependent name. However, we won't know until we've parsed all
548 // of the call arguments. So, build a CXXDependentNameExpr node
549 // to represent this name. Then, if it turns out that none of the
550 // arguments are type-dependent, we'll force the resolution of the
551 // dependent name at that point.
Steve Naroff774e4152009-01-21 00:14:39 +0000552 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
553 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000554 }
555
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000556 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000557 Decl *D = 0;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000558 if (SS && SS->isInvalid())
559 return ExprError();
560 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000561
Sebastian Redlcd883f72009-01-18 18:53:16 +0000562 if (Lookup.isAmbiguous()) {
563 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
564 SS && SS->isSet() ? SS->getRange()
565 : SourceRange());
566 return ExprError();
567 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000568 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000569
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000570 // If this reference is in an Objective-C method, then ivar lookup happens as
571 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000572 IdentifierInfo *II = Name.getAsIdentifierInfo();
573 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000574 // There are two cases to handle here. 1) scoped lookup could have failed,
575 // in which case we should look for an ivar. 2) scoped lookup could have
576 // found a decl, but that decl is outside the current method (i.e. a global
577 // variable). In these two cases, we do a lookup for an ivar with this
578 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000579 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000580 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000581 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000582 // FIXME: This should use a new expr for a direct reference, don't turn
583 // this into Self->ivar, just return a BareIVarExpr or something.
584 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000585 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000586 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
587 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000588 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000589 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000590 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000591 }
592 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000593 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000594 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000595 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000596 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000597 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000598 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000599 }
Chris Lattner4b009652007-07-25 00:24:17 +0000600 if (D == 0) {
601 // Otherwise, this could be an implicitly declared function reference (legal
602 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000603 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000604 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000605 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000606 else {
607 // If this name wasn't predeclared and if this is not a function call,
608 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000609 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000610 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
611 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000612 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
613 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614 return ExprError(Diag(Loc, diag::err_undeclared_use)
615 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000616 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000617 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000618 }
619 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000620
621 // We may have found a field within an anonymous union or struct
622 // (C++ [class.union]).
623 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
624 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
625 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000626
Douglas Gregor3257fb52008-12-22 05:46:06 +0000627 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
628 if (!MD->isStatic()) {
629 // C++ [class.mfct.nonstatic]p2:
630 // [...] if name lookup (3.4.1) resolves the name in the
631 // id-expression to a nonstatic nontype member of class X or of
632 // a base class of X, the id-expression is transformed into a
633 // class member access expression (5.2.5) using (*this) (9.3.2)
634 // as the postfix-expression to the left of the '.' operator.
635 DeclContext *Ctx = 0;
636 QualType MemberType;
637 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
638 Ctx = FD->getDeclContext();
639 MemberType = FD->getType();
640
641 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
642 MemberType = RefType->getPointeeType();
643 else if (!FD->isMutable()) {
644 unsigned combinedQualifiers
645 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
646 MemberType = MemberType.getQualifiedType(combinedQualifiers);
647 }
648 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
649 if (!Method->isStatic()) {
650 Ctx = Method->getParent();
651 MemberType = Method->getType();
652 }
653 } else if (OverloadedFunctionDecl *Ovl
654 = dyn_cast<OverloadedFunctionDecl>(D)) {
655 for (OverloadedFunctionDecl::function_iterator
656 Func = Ovl->function_begin(),
657 FuncEnd = Ovl->function_end();
658 Func != FuncEnd; ++Func) {
659 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
660 if (!DMethod->isStatic()) {
661 Ctx = Ovl->getDeclContext();
662 MemberType = Context.OverloadTy;
663 break;
664 }
665 }
666 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000667
668 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000669 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
670 QualType ThisType = Context.getTagDeclType(MD->getParent());
671 if ((Context.getCanonicalType(CtxType)
672 == Context.getCanonicalType(ThisType)) ||
673 IsDerivedFrom(ThisType, CtxType)) {
674 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000675 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000676 MD->getThisType(Context));
Steve Naroff774e4152009-01-21 00:14:39 +0000677 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000678 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000679 }
680 }
681 }
682 }
683
Douglas Gregor8acb7272008-12-11 16:49:14 +0000684 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000685 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
686 if (MD->isStatic())
687 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000688 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
689 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000690 }
691
Douglas Gregor3257fb52008-12-22 05:46:06 +0000692 // Any other ways we could have found the field in a well-formed
693 // program would have been turned into implicit member expressions
694 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000695 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
696 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000697 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000698
Chris Lattner4b009652007-07-25 00:24:17 +0000699 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000700 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000701 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000702 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000703 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000704 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000705
Steve Naroffd6163f32008-09-05 22:11:13 +0000706 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000707 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000708 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
709 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000710
Steve Naroffd6163f32008-09-05 22:11:13 +0000711 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000712
Steve Naroffd6163f32008-09-05 22:11:13 +0000713 // check if referencing an identifier with __attribute__((deprecated)).
714 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000715 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
716
Douglas Gregor48840c72008-12-10 23:01:14 +0000717 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
718 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
719 Scope *CheckS = S;
720 while (CheckS) {
721 if (CheckS->isWithinElse() &&
722 CheckS->getControlParent()->isDeclScope(Var)) {
723 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000724 ExprError(Diag(Loc, diag::warn_value_always_false)
725 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000726 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000727 ExprError(Diag(Loc, diag::warn_value_always_zero)
728 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000729 break;
730 }
731
732 // Move up one more control parent to check again.
733 CheckS = CheckS->getControlParent();
734 if (CheckS)
735 CheckS = CheckS->getParent();
736 }
737 }
738 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000739
740 // Only create DeclRefExpr's for valid Decl's.
741 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError();
743
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000744 // If the identifier reference is inside a block, and it refers to a value
745 // that is outside the block, create a BlockDeclRefExpr instead of a
746 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
747 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000748 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000749 // We do not do this for things like enum constants, global variables, etc,
750 // as they do not get snapshotted.
751 //
752 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000753 // The BlocksAttr indicates the variable is bound by-reference.
754 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000755 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000756 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757
Steve Naroff52059382008-10-10 01:28:17 +0000758 // Variable will be bound by-copy, make it const within the closure.
759 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000760 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000761 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000762 }
763 // If this reference is not in a block or if the referenced variable is
764 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000765
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000766 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000767 bool ValueDependent = false;
768 if (getLangOptions().CPlusPlus) {
769 // C++ [temp.dep.expr]p3:
770 // An id-expression is type-dependent if it contains:
771 // - an identifier that was declared with a dependent type,
772 if (VD->getType()->isDependentType())
773 TypeDependent = true;
774 // - FIXME: a template-id that is dependent,
775 // - a conversion-function-id that specifies a dependent type,
776 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
777 Name.getCXXNameType()->isDependentType())
778 TypeDependent = true;
779 // - a nested-name-specifier that contains a class-name that
780 // names a dependent type.
781 else if (SS && !SS->isEmpty()) {
782 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
783 DC; DC = DC->getParent()) {
784 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000785 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000786 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
787 if (Context.getTypeDeclType(Record)->isDependentType()) {
788 TypeDependent = true;
789 break;
790 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000791 }
792 }
793 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000794
Douglas Gregora5d84612008-12-10 20:57:37 +0000795 // C++ [temp.dep.constexpr]p2:
796 //
797 // An identifier is value-dependent if it is:
798 // - a name declared with a dependent type,
799 if (TypeDependent)
800 ValueDependent = true;
801 // - the name of a non-type template parameter,
802 else if (isa<NonTypeTemplateParmDecl>(VD))
803 ValueDependent = true;
804 // - a constant with integral or enumeration type and is
805 // initialized with an expression that is value-dependent
806 // (FIXME!).
807 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000808
Sebastian Redlcd883f72009-01-18 18:53:16 +0000809 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
810 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000811}
812
Sebastian Redlcd883f72009-01-18 18:53:16 +0000813Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
814 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000815 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000816
Chris Lattner4b009652007-07-25 00:24:17 +0000817 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000818 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000819 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
820 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
821 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000822 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000823
Chris Lattner7e637512008-01-12 08:14:25 +0000824 // Pre-defined identifiers are of type char[x], where x is the length of the
825 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000826 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000827 if (FunctionDecl *FD = getCurFunctionDecl())
828 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000829 else if (ObjCMethodDecl *MD = getCurMethodDecl())
830 Length = MD->getSynthesizedMethodSize();
831 else {
832 Diag(Loc, diag::ext_predef_outside_function);
833 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
834 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
835 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000836
837
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000838 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000839 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000840 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000841 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000842}
843
Sebastian Redlcd883f72009-01-18 18:53:16 +0000844Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000845 llvm::SmallString<16> CharBuffer;
846 CharBuffer.resize(Tok.getLength());
847 const char *ThisTokBegin = &CharBuffer[0];
848 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849
Chris Lattner4b009652007-07-25 00:24:17 +0000850 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
851 Tok.getLocation(), PP);
852 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000854
855 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
856
Sebastian Redl75324932009-01-20 22:23:13 +0000857 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
858 Literal.isWide(),
859 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000860}
861
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
863 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000864 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
865 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000866 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000867 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000868 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000869 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000870 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000871
Chris Lattner4b009652007-07-25 00:24:17 +0000872 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000873 // Add padding so that NumericLiteralParser can overread by one character.
874 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000875 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000876
Chris Lattner4b009652007-07-25 00:24:17 +0000877 // Get the spelling of the token, which eliminates trigraphs, etc.
878 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000879
Chris Lattner4b009652007-07-25 00:24:17 +0000880 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
881 Tok.getLocation(), PP);
882 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000883 return ExprError();
884
Chris Lattner1de66eb2007-08-26 03:42:43 +0000885 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000886
Chris Lattner1de66eb2007-08-26 03:42:43 +0000887 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000888 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000889 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000890 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000891 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000892 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000893 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000894 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000895
896 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
897
Ted Kremenekddedbe22007-11-29 00:56:49 +0000898 // isExact will be set by GetFloatValue().
899 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000900 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
901 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000902
Chris Lattner1de66eb2007-08-26 03:42:43 +0000903 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000904 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000905 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000906 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000907
Neil Booth7421e9c2007-08-29 22:00:19 +0000908 // long long is a C99 feature.
909 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000910 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000911 Diag(Tok.getLocation(), diag::ext_longlong);
912
Chris Lattner4b009652007-07-25 00:24:17 +0000913 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000914 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000915
Chris Lattner4b009652007-07-25 00:24:17 +0000916 if (Literal.GetIntegerValue(ResultVal)) {
917 // If this value didn't fit into uintmax_t, warn and force to ull.
918 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000919 Ty = Context.UnsignedLongLongTy;
920 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000921 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000922 } else {
923 // If this value fits into a ULL, try to figure out what else it fits into
924 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000925
Chris Lattner4b009652007-07-25 00:24:17 +0000926 // Octal, Hexadecimal, and integers with a U suffix are allowed to
927 // be an unsigned int.
928 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
929
930 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000931 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000932 if (!Literal.isLong && !Literal.isLongLong) {
933 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000934 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Chris Lattner4b009652007-07-25 00:24:17 +0000936 // Does it fit in a unsigned int?
937 if (ResultVal.isIntN(IntSize)) {
938 // Does it fit in a signed int?
939 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000940 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000941 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000942 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000943 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000944 }
Chris Lattner4b009652007-07-25 00:24:17 +0000945 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000946
Chris Lattner4b009652007-07-25 00:24:17 +0000947 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000948 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000949 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000950
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // Does it fit in a unsigned long?
952 if (ResultVal.isIntN(LongSize)) {
953 // Does it fit in a signed long?
954 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000955 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000956 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000957 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000958 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000960 }
961
Chris Lattner4b009652007-07-25 00:24:17 +0000962 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000963 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000964 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965
Chris Lattner4b009652007-07-25 00:24:17 +0000966 // Does it fit in a unsigned long long?
967 if (ResultVal.isIntN(LongLongSize)) {
968 // Does it fit in a signed long long?
969 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000970 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000971 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000972 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000973 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000974 }
975 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976
Chris Lattner4b009652007-07-25 00:24:17 +0000977 // If we still couldn't decide a type, we probably have something that
978 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000979 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000980 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000981 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000982 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000983 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000984
Chris Lattnere4068872008-05-09 05:59:00 +0000985 if (ResultVal.getBitWidth() != Width)
986 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000987 }
Sebastian Redl75324932009-01-20 22:23:13 +0000988 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattner1de66eb2007-08-26 03:42:43 +0000991 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
992 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +0000993 Res = new (Context) ImaginaryLiteral(Res,
994 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000995
996 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +0000997}
998
Sebastian Redlcd883f72009-01-18 18:53:16 +0000999Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1000 SourceLocation R, ExprArg Val) {
1001 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001002 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001003 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001004}
1005
1006/// The UsualUnaryConversions() function is *not* called by this routine.
1007/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001008bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1009 SourceLocation OpLoc,
1010 const SourceRange &ExprRange,
1011 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001012 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001013 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001014 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001015 if (isSizeof)
1016 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1017 return false;
1018 }
1019
1020 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001021 Diag(OpLoc, diag::ext_sizeof_void_type)
1022 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001023 return false;
1024 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001025
Chris Lattner159fe082009-01-24 19:46:37 +00001026 return DiagnoseIncompleteType(OpLoc, exprType,
1027 isSizeof ? diag::err_sizeof_incomplete_type :
1028 diag::err_alignof_incomplete_type,
1029 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
Chris Lattner8d9f7962009-01-24 20:17:12 +00001032bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1033 const SourceRange &ExprRange) {
1034 E = E->IgnoreParens();
1035
1036 // alignof decl is always ok.
1037 if (isa<DeclRefExpr>(E))
1038 return false;
1039
1040 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1041 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1042 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001043 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001044 return true;
1045 }
1046 // Other fields are ok.
1047 return false;
1048 }
1049 }
1050 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1051}
1052
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001053/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1054/// the same for @c alignof and @c __alignof
1055/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001056Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001057Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1058 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001059 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001060 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001061
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001062 QualType ArgTy;
1063 SourceRange Range;
1064 if (isType) {
1065 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1066 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001067
1068 // Verify that the operand is valid.
1069 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1070 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001071 } else {
1072 // Get the end location.
1073 Expr *ArgEx = (Expr *)TyOrEx;
1074 Range = ArgEx->getSourceRange();
1075 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001076
1077 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001078 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001079 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001080 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001081 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1082 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1083 isInvalid = true;
1084 } else {
1085 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1086 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001087
1088 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001089 DeleteExpr(ArgEx);
1090 return ExprError();
1091 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001092 }
1093
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001094 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001095 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001096 Context.getSizeType(), OpLoc,
1097 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001098}
1099
Chris Lattner5110ad52007-08-24 21:41:10 +00001100QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001101 DefaultFunctionArrayConversion(V);
1102
Chris Lattnera16e42d2007-08-26 05:39:26 +00001103 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001104 if (const ComplexType *CT = V->getType()->getAsComplexType())
1105 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001106
1107 // Otherwise they pass through real integer and floating point types here.
1108 if (V->getType()->isArithmeticType())
1109 return V->getType();
1110
1111 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001112 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001113 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001114}
1115
1116
Chris Lattner4b009652007-07-25 00:24:17 +00001117
Sebastian Redl8b769972009-01-19 00:08:26 +00001118Action::OwningExprResult
1119Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1120 tok::TokenKind Kind, ExprArg Input) {
1121 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001122
Chris Lattner4b009652007-07-25 00:24:17 +00001123 UnaryOperator::Opcode Opc;
1124 switch (Kind) {
1125 default: assert(0 && "Unknown unary op!");
1126 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1127 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1128 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001129
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001130 if (getLangOptions().CPlusPlus &&
1131 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1132 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001133 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001134 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1135
1136 // C++ [over.inc]p1:
1137 //
1138 // [...] If the function is a member function with one
1139 // parameter (which shall be of type int) or a non-member
1140 // function with two parameters (the second of which shall be
1141 // of type int), it defines the postfix increment operator ++
1142 // for objects of that type. When the postfix increment is
1143 // called as a result of using the ++ operator, the int
1144 // argument will have value zero.
1145 Expr *Args[2] = {
1146 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001147 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1148 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001149 };
1150
1151 // Build the candidate set for overloading
1152 OverloadCandidateSet CandidateSet;
1153 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1154
1155 // Perform overload resolution.
1156 OverloadCandidateSet::iterator Best;
1157 switch (BestViableFunction(CandidateSet, Best)) {
1158 case OR_Success: {
1159 // We found a built-in operator or an overloaded operator.
1160 FunctionDecl *FnDecl = Best->Function;
1161
1162 if (FnDecl) {
1163 // We matched an overloaded operator. Build a call to that
1164 // operator.
1165
1166 // Convert the arguments.
1167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1168 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001169 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001170 } else {
1171 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001172 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001173 FnDecl->getParamDecl(0)->getType(),
1174 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001175 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001176 }
1177
1178 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001179 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001180 = FnDecl->getType()->getAsFunctionType()->getResultType();
1181 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001182
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001183 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001184 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001185 SourceLocation());
1186 UsualUnaryConversions(FnExpr);
1187
Sebastian Redl8b769972009-01-19 00:08:26 +00001188 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001189 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001190 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001191 } else {
1192 // We matched a built-in operator. Convert the arguments, then
1193 // break out so that we will build the appropriate built-in
1194 // operator node.
1195 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1196 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001197 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001198
1199 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001200 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001201 }
1202
1203 case OR_No_Viable_Function:
1204 // No viable function; fall through to handling this as a
1205 // built-in operator, which will produce an error message for us.
1206 break;
1207
1208 case OR_Ambiguous:
1209 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1210 << UnaryOperator::getOpcodeStr(Opc)
1211 << Arg->getSourceRange();
1212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001213 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001214 }
1215
1216 // Either we found no viable overloaded operator or we matched a
1217 // built-in operator. In either case, fall through to trying to
1218 // build a built-in operation.
1219 }
1220
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001221 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1222 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001223 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001224 return ExprError();
1225 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001226 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001227}
1228
Sebastian Redl8b769972009-01-19 00:08:26 +00001229Action::OwningExprResult
1230Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1231 ExprArg Idx, SourceLocation RLoc) {
1232 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1233 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001234
Douglas Gregor80723c52008-11-19 17:17:41 +00001235 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001236 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001237 LHSExp->getType()->isEnumeralType() ||
1238 RHSExp->getType()->isRecordType() ||
1239 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001240 // Add the appropriate overloaded operators (C++ [over.match.oper])
1241 // to the candidate set.
1242 OverloadCandidateSet CandidateSet;
1243 Expr *Args[2] = { LHSExp, RHSExp };
1244 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001245
Douglas Gregor80723c52008-11-19 17:17:41 +00001246 // Perform overload resolution.
1247 OverloadCandidateSet::iterator Best;
1248 switch (BestViableFunction(CandidateSet, Best)) {
1249 case OR_Success: {
1250 // We found a built-in operator or an overloaded operator.
1251 FunctionDecl *FnDecl = Best->Function;
1252
1253 if (FnDecl) {
1254 // We matched an overloaded operator. Build a call to that
1255 // operator.
1256
1257 // Convert the arguments.
1258 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1259 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1260 PerformCopyInitialization(RHSExp,
1261 FnDecl->getParamDecl(0)->getType(),
1262 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001263 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001264 } else {
1265 // Convert the arguments.
1266 if (PerformCopyInitialization(LHSExp,
1267 FnDecl->getParamDecl(0)->getType(),
1268 "passing") ||
1269 PerformCopyInitialization(RHSExp,
1270 FnDecl->getParamDecl(1)->getType(),
1271 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001272 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001273 }
1274
1275 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001276 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001277 = FnDecl->getType()->getAsFunctionType()->getResultType();
1278 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001279
Douglas Gregor80723c52008-11-19 17:17:41 +00001280 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001281 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001282 SourceLocation());
1283 UsualUnaryConversions(FnExpr);
1284
Sebastian Redl8b769972009-01-19 00:08:26 +00001285 Base.release();
1286 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001287 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1288 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001289 } else {
1290 // We matched a built-in operator. Convert the arguments, then
1291 // break out so that we will build the appropriate built-in
1292 // operator node.
1293 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1294 "passing") ||
1295 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1296 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001297 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001298
1299 break;
1300 }
1301 }
1302
1303 case OR_No_Viable_Function:
1304 // No viable function; fall through to handling this as a
1305 // built-in operator, which will produce an error message for us.
1306 break;
1307
1308 case OR_Ambiguous:
1309 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1310 << "[]"
1311 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1312 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001313 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001314 }
1315
1316 // Either we found no viable overloaded operator or we matched a
1317 // built-in operator. In either case, fall through to trying to
1318 // build a built-in operation.
1319 }
1320
Chris Lattner4b009652007-07-25 00:24:17 +00001321 // Perform default conversions.
1322 DefaultFunctionArrayConversion(LHSExp);
1323 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001324
Chris Lattner4b009652007-07-25 00:24:17 +00001325 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1326
1327 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001328 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001329 // in the subscript position. As a result, we need to derive the array base
1330 // and index from the expression types.
1331 Expr *BaseExpr, *IndexExpr;
1332 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001333 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001334 BaseExpr = LHSExp;
1335 IndexExpr = RHSExp;
1336 // FIXME: need to deal with const...
1337 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001338 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001339 // Handle the uncommon case of "123[Ptr]".
1340 BaseExpr = RHSExp;
1341 IndexExpr = LHSExp;
1342 // FIXME: need to deal with const...
1343 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001344 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1345 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001346 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001347
Chris Lattner4b009652007-07-25 00:24:17 +00001348 // FIXME: need to deal with const...
1349 ResultType = VTy->getElementType();
1350 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001351 return ExprError(Diag(LHSExp->getLocStart(),
1352 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1353 }
Chris Lattner4b009652007-07-25 00:24:17 +00001354 // C99 6.5.2.1p1
1355 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError(Diag(IndexExpr->getLocStart(),
1357 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001358
1359 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1360 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001361 // void (*)(int)) and pointers to incomplete types. Functions are not
1362 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001363 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001364 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001365 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001366 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001367
Sebastian Redl8b769972009-01-19 00:08:26 +00001368 Base.release();
1369 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001370 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1371 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001372}
1373
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001374QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001375CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001376 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001377 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001378
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001379 // The vector accessor can't exceed the number of elements.
1380 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001381
1382 // This flag determines whether or not the component is one of the four
1383 // special names that indicate a subset of exactly half the elements are
1384 // to be selected.
1385 bool HalvingSwizzle = false;
1386
1387 // This flag determines whether or not CompName has an 's' char prefix,
1388 // indicating that it is a string of hex values to be used as vector indices.
1389 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001390
1391 // Check that we've found one of the special components, or that the component
1392 // names must come from the same set.
1393 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001394 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1395 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001396 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001397 do
1398 compStr++;
1399 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001400 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001401 do
1402 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001403 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001404 }
Nate Begeman1486b502009-01-18 01:47:54 +00001405
1406 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001407 // We didn't get to the end of the string. This means the component names
1408 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001409 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1410 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001411 return QualType();
1412 }
Nate Begeman1486b502009-01-18 01:47:54 +00001413
1414 // Ensure no component accessor exceeds the width of the vector type it
1415 // operates on.
1416 if (!HalvingSwizzle) {
1417 compStr = CompName.getName();
1418
1419 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001420 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001421
1422 while (*compStr) {
1423 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1424 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1425 << baseType << SourceRange(CompLoc);
1426 return QualType();
1427 }
1428 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001429 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001430
Nate Begeman1486b502009-01-18 01:47:54 +00001431 // If this is a halving swizzle, verify that the base type has an even
1432 // number of elements.
1433 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001434 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001435 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001436 return QualType();
1437 }
1438
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001439 // The component accessor looks fine - now we need to compute the actual type.
1440 // The vector type is implied by the component accessor. For example,
1441 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001442 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001443 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001444 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1445 : CompName.getLength();
1446 if (HexSwizzle)
1447 CompSize--;
1448
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001449 if (CompSize == 1)
1450 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001451
Nate Begemanaf6ed502008-04-18 23:10:10 +00001452 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001453 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001454 // diagostics look bad. We want extended vector types to appear built-in.
1455 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1456 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1457 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001458 }
1459 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001460}
1461
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001462/// constructSetterName - Return the setter name for the given
1463/// identifier, i.e. "set" + Name where the initial character of Name
1464/// has been capitalized.
1465// FIXME: Merge with same routine in Parser. But where should this
1466// live?
1467static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1468 const IdentifierInfo *Name) {
1469 llvm::SmallString<100> SelectorName;
1470 SelectorName = "set";
1471 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1472 SelectorName[3] = toupper(SelectorName[3]);
1473 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1474}
1475
Sebastian Redl8b769972009-01-19 00:08:26 +00001476Action::OwningExprResult
1477Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1478 tok::TokenKind OpKind, SourceLocation MemberLoc,
1479 IdentifierInfo &Member) {
1480 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001481 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001482
1483 // Perform default conversions.
1484 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001485
Steve Naroff2cb66382007-07-26 03:11:44 +00001486 QualType BaseType = BaseExpr->getType();
1487 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001488
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001489 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1490 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001491 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001492 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001493 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001494 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1496 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001497 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001498 return ExprError(Diag(MemberLoc,
1499 diag::err_typecheck_member_reference_arrow)
1500 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001501 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001502
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001503 // Handle field access to simple records. This also handles access to fields
1504 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001505 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001506 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001507 if (DiagnoseIncompleteType(OpLoc, BaseType,
1508 diag::err_typecheck_incomplete_tag,
1509 BaseExpr->getSourceRange()))
1510 return ExprError();
1511
Steve Naroff2cb66382007-07-26 03:11:44 +00001512 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001513 // FIXME: Qualified name lookup for C++ is a bit more complicated
1514 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001515 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001516 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001517 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001518
1519 Decl *MemberDecl = 0;
1520 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001521 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1522 << &Member << BaseExpr->getSourceRange());
1523 else if (Result.isAmbiguous()) {
1524 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1525 MemberLoc, BaseExpr->getSourceRange());
1526 return ExprError();
1527 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001528 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001529
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001530 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001531 // We may have found a field within an anonymous union or struct
1532 // (C++ [class.union]).
1533 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001534 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001535 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001536
Douglas Gregor82d44772008-12-20 23:49:58 +00001537 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1538 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001539 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001540 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1541 MemberType = Ref->getPointeeType();
1542 else {
1543 unsigned combinedQualifiers =
1544 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001545 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001546 combinedQualifiers &= ~QualType::Const;
1547 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1548 }
Eli Friedman76b49832008-02-06 22:48:16 +00001549
Steve Naroff774e4152009-01-21 00:14:39 +00001550 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1551 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001552 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001553 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001554 Var, MemberLoc,
1555 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001556 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001557 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1558 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001559 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001560 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001561 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001562 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001563 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001564 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001566 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001567 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1568 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001569
Douglas Gregor82d44772008-12-20 23:49:58 +00001570 // We found a declaration kind that we didn't expect. This is a
1571 // generic error message that tells the user that she can't refer
1572 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001573 return ExprError(Diag(MemberLoc,
1574 diag::err_typecheck_member_reference_unknown)
1575 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001576 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001577
Chris Lattnere9d71612008-07-21 04:59:05 +00001578 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1579 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001580 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001581 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001582 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1583 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001584 OpKind == tok::arrow);
1585 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001587 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001588 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1589 << IFTy->getDecl()->getDeclName() << &Member
1590 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001591 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001592
Chris Lattnere9d71612008-07-21 04:59:05 +00001593 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1594 // pointer to a (potentially qualified) interface type.
1595 const PointerType *PTy;
1596 const ObjCInterfaceType *IFTy;
1597 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1598 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1599 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001600
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001601 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001602 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001603 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001604 MemberLoc, BaseExpr));
1605
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001606 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001607 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1608 E = IFTy->qual_end(); I != E; ++I)
1609 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001610 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001612
1613 // If that failed, look for an "implicit" property by seeing if the nullary
1614 // selector is implemented.
1615
1616 // FIXME: The logic for looking up nullary and unary selectors should be
1617 // shared with the code in ActOnInstanceMessage.
1618
1619 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1620 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001621
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001622 // If this reference is in an @implementation, check for 'private' methods.
1623 if (!Getter)
1624 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1625 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1626 if (ObjCImplementationDecl *ImpDecl =
1627 ObjCImplementations[ClassDecl->getIdentifier()])
1628 Getter = ImpDecl->getInstanceMethod(Sel);
1629
Steve Naroff04151f32008-10-22 19:16:27 +00001630 // Look through local category implementations associated with the class.
1631 if (!Getter) {
1632 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1633 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1634 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1635 }
1636 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001637 if (Getter) {
1638 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001639 // will look for the matching setter, in case it is needed.
1640 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1641 &Member);
1642 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1643 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1644 if (!Setter) {
1645 // If this reference is in an @implementation, also check for 'private'
1646 // methods.
1647 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1648 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1649 if (ObjCImplementationDecl *ImpDecl =
1650 ObjCImplementations[ClassDecl->getIdentifier()])
1651 Setter = ImpDecl->getInstanceMethod(SetterSel);
1652 }
1653 // Look through local category implementations associated with the class.
1654 if (!Setter) {
1655 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1656 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1657 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1658 }
1659 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001660
1661 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001662 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1663 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001664 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001665
1666 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1667 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001668 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001669 // Handle properties on qualified "id" protocols.
1670 const ObjCQualifiedIdType *QIdTy;
1671 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1672 // Check protocols on qualified interfaces.
1673 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001674 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001675 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001676 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001678 // Also must look for a getter name which uses property syntax.
1679 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1680 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001681 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1682 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001683 }
1684 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001685
1686 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1687 << &Member << BaseType);
1688 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001689 // Handle 'field access' to vectors, such as 'V.xx'.
1690 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001691 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1692 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001694 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1695 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001696 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001697
1698 return ExprError(Diag(MemberLoc,
1699 diag::err_typecheck_member_reference_struct_union)
1700 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001701}
1702
Douglas Gregor3257fb52008-12-22 05:46:06 +00001703/// ConvertArgumentsForCall - Converts the arguments specified in
1704/// Args/NumArgs to the parameter types of the function FDecl with
1705/// function prototype Proto. Call is the call expression itself, and
1706/// Fn is the function expression. For a C++ member function, this
1707/// routine does not attempt to convert the object argument. Returns
1708/// true if the call is ill-formed.
1709bool
1710Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1711 FunctionDecl *FDecl,
1712 const FunctionTypeProto *Proto,
1713 Expr **Args, unsigned NumArgs,
1714 SourceLocation RParenLoc) {
1715 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1716 // assignment, to the types of the corresponding parameter, ...
1717 unsigned NumArgsInProto = Proto->getNumArgs();
1718 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001719 bool Invalid = false;
1720
Douglas Gregor3257fb52008-12-22 05:46:06 +00001721 // If too few arguments are available (and we don't have default
1722 // arguments for the remaining parameters), don't make the call.
1723 if (NumArgs < NumArgsInProto) {
1724 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1725 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1726 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1727 // Use default arguments for missing arguments
1728 NumArgsToCheck = NumArgsInProto;
1729 Call->setNumArgs(NumArgsInProto);
1730 }
1731
1732 // If too many are passed and not variadic, error on the extras and drop
1733 // them.
1734 if (NumArgs > NumArgsInProto) {
1735 if (!Proto->isVariadic()) {
1736 Diag(Args[NumArgsInProto]->getLocStart(),
1737 diag::err_typecheck_call_too_many_args)
1738 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1739 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1740 Args[NumArgs-1]->getLocEnd());
1741 // This deletes the extra arguments.
1742 Call->setNumArgs(NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001743 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001744 }
1745 NumArgsToCheck = NumArgsInProto;
1746 }
1747
1748 // Continue to check argument types (even if we have too few/many args).
1749 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1750 QualType ProtoArgType = Proto->getArgType(i);
1751
1752 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001753 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001754 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001755
1756 // Pass the argument.
1757 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1758 return true;
1759 } else
1760 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001761 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001762 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001763
Douglas Gregor3257fb52008-12-22 05:46:06 +00001764 Call->setArg(i, Arg);
1765 }
1766
1767 // If this is a variadic call, handle args passed through "...".
1768 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001769 VariadicCallType CallType = VariadicFunction;
1770 if (Fn->getType()->isBlockPointerType())
1771 CallType = VariadicBlock; // Block
1772 else if (isa<MemberExpr>(Fn))
1773 CallType = VariadicMethod;
1774
Douglas Gregor3257fb52008-12-22 05:46:06 +00001775 // Promote the arguments (C99 6.5.2.2p7).
1776 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1777 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001778 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001779 Call->setArg(i, Arg);
1780 }
1781 }
1782
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001783 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001784}
1785
Steve Naroff87d58b42007-09-16 03:34:24 +00001786/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001787/// This provides the location of the left/right parens and a list of comma
1788/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001789Action::OwningExprResult
1790Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1791 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001792 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001793 unsigned NumArgs = args.size();
1794 Expr *Fn = static_cast<Expr *>(fn.release());
1795 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001796 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001797 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001798 OverloadedFunctionDecl *Ovl = NULL;
1799
Douglas Gregora133e262008-12-06 00:22:45 +00001800 // Determine whether this is a dependent call inside a C++ template,
1801 // in which case we won't do any semantic analysis now.
1802 bool Dependent = false;
1803 if (Fn->isTypeDependent()) {
1804 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1805 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1806 Dependent = true;
1807 else {
1808 // Resolve the CXXDependentNameExpr to an actual identifier;
1809 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001810 OwningExprResult Resolved
1811 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1812 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001813 /*HasTrailingLParen=*/true,
1814 /*SS=*/0,
1815 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001816 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001817 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001818 else {
1819 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001820 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001821 }
1822 }
1823 } else
1824 Dependent = true;
1825 } else
1826 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1827
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001828 // FIXME: Will need to cache the results of name lookup (including
1829 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001830 if (Dependent)
Steve Naroff774e4152009-01-21 00:14:39 +00001831 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1832 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001833
Douglas Gregor3257fb52008-12-22 05:46:06 +00001834 // Determine whether this is a call to an object (C++ [over.call.object]).
1835 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001836 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1837 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001838
1839 // Determine whether this is a call to a member function.
1840 if (getLangOptions().CPlusPlus) {
1841 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1842 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1843 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001844 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1845 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001846 }
1847
Douglas Gregord2baafd2008-10-21 16:13:35 +00001848 // If we're directly calling a function or a set of overloaded
1849 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001850 DeclRefExpr *DRExpr = NULL;
1851 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1852 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1853 else
1854 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001855
Douglas Gregor566782a2009-01-06 05:10:23 +00001856 if (DRExpr) {
1857 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1858 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001859 }
1860
Douglas Gregord2baafd2008-10-21 16:13:35 +00001861 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001862 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1863 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001864 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001865 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001866
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001867 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001868 Expr *NewFn = 0;
1869 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff774e4152009-01-21 00:14:39 +00001870 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor566782a2009-01-06 05:10:23 +00001871 QDRExpr->getLocation(), false, false,
1872 QDRExpr->getSourceRange().getBegin());
1873 else
Steve Naroff774e4152009-01-21 00:14:39 +00001874 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1875 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001876 Fn->Destroy(Context);
1877 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001878 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001879
1880 // Promote the function operand.
1881 UsualUnaryConversions(Fn);
1882
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001883 // Make the call expr early, before semantic checks. This guarantees cleanup
1884 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001885 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1886 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001887 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001888 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001889
Steve Naroffd6163f32008-09-05 22:11:13 +00001890 const FunctionType *FuncT;
1891 if (!Fn->getType()->isBlockPointerType()) {
1892 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1893 // have type pointer to function".
1894 const PointerType *PT = Fn->getType()->getAsPointerType();
1895 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001896 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1897 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001898 FuncT = PT->getPointeeType()->getAsFunctionType();
1899 } else { // This is a block call.
1900 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1901 getAsFunctionType();
1902 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001903 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001904 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1905 << Fn->getType() << Fn->getSourceRange());
1906
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001907 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001908 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001909
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001910 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001911 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1912 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001913 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001914 } else {
1915 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001916
Steve Naroffdb65e052007-08-28 23:30:39 +00001917 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001918 for (unsigned i = 0; i != NumArgs; i++) {
1919 Expr *Arg = Args[i];
1920 DefaultArgumentPromotion(Arg);
1921 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001922 }
Chris Lattner4b009652007-07-25 00:24:17 +00001923 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001924
Douglas Gregor3257fb52008-12-22 05:46:06 +00001925 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1926 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001927 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1928 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929
Chris Lattner2e64c072007-08-10 20:18:51 +00001930 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001931 if (FDecl)
1932 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001933
Sebastian Redl8b769972009-01-19 00:08:26 +00001934 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001935}
1936
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001937Action::OwningExprResult
1938Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1939 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001940 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001941 QualType literalType = QualType::getFromOpaquePtr(Ty);
1942 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001943 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001944 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001945
Eli Friedman8c2173d2008-05-20 05:22:08 +00001946 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001947 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001948 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1949 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001950 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1951 diag::err_typecheck_decl_incomplete_type,
1952 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001953 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001954
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001955 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001956 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001957 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001958
Chris Lattnere5cb5862008-12-04 23:50:19 +00001959 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001960 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001961 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001962 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001963 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001964 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001965 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1966 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001967}
1968
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001969Action::OwningExprResult
1970Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1971 InitListDesignations &Designators,
1972 SourceLocation RBraceLoc) {
1973 unsigned NumInit = initlist.size();
1974 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001975
Steve Naroff0acc9c92007-09-15 18:49:24 +00001976 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001977 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001978
Steve Naroff774e4152009-01-21 00:14:39 +00001979 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00001980 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00001981 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001982 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001983}
1984
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001985/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001986bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001987 UsualUnaryConversions(castExpr);
1988
1989 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1990 // type needs to be scalar.
1991 if (castType->isVoidType()) {
1992 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001993 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1994 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001995 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001996 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1997 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1998 (castType->isStructureType() || castType->isUnionType())) {
1999 // GCC struct/union extension: allow cast to self.
2000 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2001 << castType << castExpr->getSourceRange();
2002 } else if (castType->isUnionType()) {
2003 // GCC cast to union extension
2004 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2005 RecordDecl::field_iterator Field, FieldEnd;
2006 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2007 Field != FieldEnd; ++Field) {
2008 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2009 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2010 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2011 << castExpr->getSourceRange();
2012 break;
2013 }
2014 }
2015 if (Field == FieldEnd)
2016 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2017 << castExpr->getType() << castExpr->getSourceRange();
2018 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002019 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002020 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002021 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002022 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002023 } else if (!castExpr->getType()->isScalarType() &&
2024 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002025 return Diag(castExpr->getLocStart(),
2026 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002027 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002028 } else if (castExpr->getType()->isVectorType()) {
2029 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2030 return true;
2031 } else if (castType->isVectorType()) {
2032 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2033 return true;
2034 }
2035 return false;
2036}
2037
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002038bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002039 assert(VectorTy->isVectorType() && "Not a vector type!");
2040
2041 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002042 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002043 return Diag(R.getBegin(),
2044 Ty->isVectorType() ?
2045 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002046 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002047 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002048 } else
2049 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002050 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002051 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002052
2053 return false;
2054}
2055
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002056Action::OwningExprResult
2057Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2058 SourceLocation RParenLoc, ExprArg Op) {
2059 assert((Ty != 0) && (Op.get() != 0) &&
2060 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002061
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002062 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002063 QualType castType = QualType::getFromOpaquePtr(Ty);
2064
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002065 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002066 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002067 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002068 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002069}
2070
Chris Lattner98a425c2007-11-26 01:40:58 +00002071/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2072/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002073inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2074 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2075 UsualUnaryConversions(cond);
2076 UsualUnaryConversions(lex);
2077 UsualUnaryConversions(rex);
2078 QualType condT = cond->getType();
2079 QualType lexT = lex->getType();
2080 QualType rexT = rex->getType();
2081
2082 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002083 if (!cond->isTypeDependent()) {
2084 if (!condT->isScalarType()) { // C99 6.5.15p2
2085 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2086 return QualType();
2087 }
Chris Lattner4b009652007-07-25 00:24:17 +00002088 }
Chris Lattner992ae932008-01-06 22:42:25 +00002089
2090 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002091 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2092 return Context.DependentTy;
2093
Chris Lattner992ae932008-01-06 22:42:25 +00002094 // If both operands have arithmetic type, do the usual arithmetic conversions
2095 // to find a common type: C99 6.5.15p3,5.
2096 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002097 UsualArithmeticConversions(lex, rex);
2098 return lex->getType();
2099 }
Chris Lattner992ae932008-01-06 22:42:25 +00002100
2101 // If both operands are the same structure or union type, the result is that
2102 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002103 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002104 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002105 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002106 // "If both the operands have structure or union type, the result has
2107 // that type." This implies that CV qualifiers are dropped.
2108 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002109 }
Chris Lattner992ae932008-01-06 22:42:25 +00002110
2111 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002112 // The following || allows only one side to be void (a GCC-ism).
2113 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002114 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002115 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2116 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002117 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002118 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2119 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002120 ImpCastExprToType(lex, Context.VoidTy);
2121 ImpCastExprToType(rex, Context.VoidTy);
2122 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002123 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002124 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2125 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002126 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2127 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002128 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002129 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002130 return lexT;
2131 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002132 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2133 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002134 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002135 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002136 return rexT;
2137 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002138 // Handle the case where both operands are pointers before we handle null
2139 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002140 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2141 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2142 // get the "pointed to" types
2143 QualType lhptee = LHSPT->getPointeeType();
2144 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002145
Chris Lattner71225142007-07-31 21:27:01 +00002146 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2147 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002148 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002149 // Figure out necessary qualifiers (C99 6.5.15p6)
2150 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002151 QualType destType = Context.getPointerType(destPointee);
2152 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2153 ImpCastExprToType(rex, destType); // promote to void*
2154 return destType;
2155 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002156 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002157 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002158 QualType destType = Context.getPointerType(destPointee);
2159 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2160 ImpCastExprToType(rex, destType); // promote to void*
2161 return destType;
2162 }
Chris Lattner4b009652007-07-25 00:24:17 +00002163
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002164 QualType compositeType = lexT;
2165
2166 // If either type is an Objective-C object type then check
2167 // compatibility according to Objective-C.
2168 if (Context.isObjCObjectPointerType(lexT) ||
2169 Context.isObjCObjectPointerType(rexT)) {
2170 // If both operands are interfaces and either operand can be
2171 // assigned to the other, use that type as the composite
2172 // type. This allows
2173 // xxx ? (A*) a : (B*) b
2174 // where B is a subclass of A.
2175 //
2176 // Additionally, as for assignment, if either type is 'id'
2177 // allow silent coercion. Finally, if the types are
2178 // incompatible then make sure to use 'id' as the composite
2179 // type so the result is acceptable for sending messages to.
2180
2181 // FIXME: This code should not be localized to here. Also this
2182 // should use a compatible check instead of abusing the
2183 // canAssignObjCInterfaces code.
2184 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2185 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2186 if (LHSIface && RHSIface &&
2187 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2188 compositeType = lexT;
2189 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002190 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002191 compositeType = rexT;
2192 } else if (Context.isObjCIdType(lhptee) ||
2193 Context.isObjCIdType(rhptee)) {
2194 // FIXME: This code looks wrong, because isObjCIdType checks
2195 // the struct but getObjCIdType returns the pointer to
2196 // struct. This is horrible and should be fixed.
2197 compositeType = Context.getObjCIdType();
2198 } else {
2199 QualType incompatTy = Context.getObjCIdType();
2200 ImpCastExprToType(lex, incompatTy);
2201 ImpCastExprToType(rex, incompatTy);
2202 return incompatTy;
2203 }
2204 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2205 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002206 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002207 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002208 // In this situation, we assume void* type. No especially good
2209 // reason, but this is what gcc does, and we do have to pick
2210 // to get a consistent AST.
2211 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002212 ImpCastExprToType(lex, incompatTy);
2213 ImpCastExprToType(rex, incompatTy);
2214 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002215 }
2216 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002217 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2218 // differently qualified versions of compatible types, the result type is
2219 // a pointer to an appropriately qualified version of the *composite*
2220 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002221 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002222 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002223 ImpCastExprToType(lex, compositeType);
2224 ImpCastExprToType(rex, compositeType);
2225 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002226 }
Chris Lattner4b009652007-07-25 00:24:17 +00002227 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002228 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2229 // evaluates to "struct objc_object *" (and is handled above when comparing
2230 // id with statically typed objects).
2231 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2232 // GCC allows qualified id and any Objective-C type to devolve to
2233 // id. Currently localizing to here until clear this should be
2234 // part of ObjCQualifiedIdTypesAreCompatible.
2235 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2236 (lexT->isObjCQualifiedIdType() &&
2237 Context.isObjCObjectPointerType(rexT)) ||
2238 (rexT->isObjCQualifiedIdType() &&
2239 Context.isObjCObjectPointerType(lexT))) {
2240 // FIXME: This is not the correct composite type. This only
2241 // happens to work because id can more or less be used anywhere,
2242 // however this may change the type of method sends.
2243 // FIXME: gcc adds some type-checking of the arguments and emits
2244 // (confusing) incompatible comparison warnings in some
2245 // cases. Investigate.
2246 QualType compositeType = Context.getObjCIdType();
2247 ImpCastExprToType(lex, compositeType);
2248 ImpCastExprToType(rex, compositeType);
2249 return compositeType;
2250 }
2251 }
2252
Steve Naroff3eac7692008-09-10 19:17:48 +00002253 // Selection between block pointer types is ok as long as they are the same.
2254 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2255 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2256 return lexT;
2257
Chris Lattner992ae932008-01-06 22:42:25 +00002258 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002259 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002260 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002261 return QualType();
2262}
2263
Steve Naroff87d58b42007-09-16 03:34:24 +00002264/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002265/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002266Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2267 SourceLocation ColonLoc,
2268 ExprArg Cond, ExprArg LHS,
2269 ExprArg RHS) {
2270 Expr *CondExpr = (Expr *) Cond.get();
2271 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002272
2273 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2274 // was the condition.
2275 bool isLHSNull = LHSExpr == 0;
2276 if (isLHSNull)
2277 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002278
2279 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002280 RHSExpr, QuestionLoc);
2281 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002282 return ExprError();
2283
2284 Cond.release();
2285 LHS.release();
2286 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002287 return Owned(new (Context) ConditionalOperator(CondExpr,
2288 isLHSNull ? 0 : LHSExpr,
2289 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002290}
2291
Chris Lattner4b009652007-07-25 00:24:17 +00002292
2293// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2294// being closely modeled after the C99 spec:-). The odd characteristic of this
2295// routine is it effectively iqnores the qualifiers on the top level pointee.
2296// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2297// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002298Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002299Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2300 QualType lhptee, rhptee;
2301
2302 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002303 lhptee = lhsType->getAsPointerType()->getPointeeType();
2304 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002305
2306 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002307 lhptee = Context.getCanonicalType(lhptee);
2308 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002309
Chris Lattner005ed752008-01-04 18:04:52 +00002310 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002311
2312 // C99 6.5.16.1p1: This following citation is common to constraints
2313 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2314 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002315 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002316 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002317 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002318
2319 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2320 // incomplete type and the other is a pointer to a qualified or unqualified
2321 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002322 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002323 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002324 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002325
2326 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002327 assert(rhptee->isFunctionType());
2328 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002329 }
2330
2331 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002332 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002333 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002334
2335 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002336 assert(lhptee->isFunctionType());
2337 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002338 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002339
2340 // Check for ObjC interfaces
2341 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2342 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2343 if (LHSIface && RHSIface &&
2344 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2345 return ConvTy;
2346
2347 // ID acts sort of like void* for ObjC interfaces
2348 if (LHSIface && Context.isObjCIdType(rhptee))
2349 return ConvTy;
2350 if (RHSIface && Context.isObjCIdType(lhptee))
2351 return ConvTy;
2352
Chris Lattner4b009652007-07-25 00:24:17 +00002353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2354 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002355 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2356 rhptee.getUnqualifiedType()))
2357 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002358 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002359}
2360
Steve Naroff3454b6c2008-09-04 15:10:53 +00002361/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2362/// block pointer types are compatible or whether a block and normal pointer
2363/// are compatible. It is more restrict than comparing two function pointer
2364// types.
2365Sema::AssignConvertType
2366Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2367 QualType rhsType) {
2368 QualType lhptee, rhptee;
2369
2370 // get the "pointed to" type (ignoring qualifiers at the top level)
2371 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2372 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2373
2374 // make sure we operate on the canonical type
2375 lhptee = Context.getCanonicalType(lhptee);
2376 rhptee = Context.getCanonicalType(rhptee);
2377
2378 AssignConvertType ConvTy = Compatible;
2379
2380 // For blocks we enforce that qualifiers are identical.
2381 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2382 ConvTy = CompatiblePointerDiscardsQualifiers;
2383
2384 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2385 return IncompatibleBlockPointer;
2386 return ConvTy;
2387}
2388
Chris Lattner4b009652007-07-25 00:24:17 +00002389/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2390/// has code to accommodate several GCC extensions when type checking
2391/// pointers. Here are some objectionable examples that GCC considers warnings:
2392///
2393/// int a, *pint;
2394/// short *pshort;
2395/// struct foo *pfoo;
2396///
2397/// pint = pshort; // warning: assignment from incompatible pointer type
2398/// a = pint; // warning: assignment makes integer from pointer without a cast
2399/// pint = a; // warning: assignment makes pointer from integer without a cast
2400/// pint = pfoo; // warning: assignment from incompatible pointer type
2401///
2402/// As a result, the code for dealing with pointers is more complex than the
2403/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002404///
Chris Lattner005ed752008-01-04 18:04:52 +00002405Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002406Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002407 // Get canonical types. We're not formatting these types, just comparing
2408 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002409 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2410 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002411
2412 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002413 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002414
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002415 // If the left-hand side is a reference type, then we are in a
2416 // (rare!) case where we've allowed the use of references in C,
2417 // e.g., as a parameter type in a built-in function. In this case,
2418 // just make sure that the type referenced is compatible with the
2419 // right-hand side type. The caller is responsible for adjusting
2420 // lhsType so that the resulting expression does not have reference
2421 // type.
2422 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2423 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002424 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002425 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002426 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002427
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002428 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2429 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002430 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002431 // Relax integer conversions like we do for pointers below.
2432 if (rhsType->isIntegerType())
2433 return IntToPointer;
2434 if (lhsType->isIntegerType())
2435 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002436 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002437 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002438
Nate Begemanc5f0f652008-07-14 18:02:46 +00002439 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002440 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002441 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2442 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002443 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002444
Nate Begemanc5f0f652008-07-14 18:02:46 +00002445 // If we are allowing lax vector conversions, and LHS and RHS are both
2446 // vectors, the total size only needs to be the same. This is a bitcast;
2447 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002448 if (getLangOptions().LaxVectorConversions &&
2449 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002450 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002451 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002452 }
2453 return Incompatible;
2454 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002455
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002456 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002457 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002458
Chris Lattner390564e2008-04-07 06:49:41 +00002459 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002460 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002461 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002462
Chris Lattner390564e2008-04-07 06:49:41 +00002463 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002464 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002465
Steve Naroffa982c712008-09-29 18:10:17 +00002466 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002467 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002468 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002469
2470 // Treat block pointers as objects.
2471 if (getLangOptions().ObjC1 &&
2472 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2473 return Compatible;
2474 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002475 return Incompatible;
2476 }
2477
2478 if (isa<BlockPointerType>(lhsType)) {
2479 if (rhsType->isIntegerType())
2480 return IntToPointer;
2481
Steve Naroffa982c712008-09-29 18:10:17 +00002482 // Treat block pointers as objects.
2483 if (getLangOptions().ObjC1 &&
2484 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2485 return Compatible;
2486
Steve Naroff3454b6c2008-09-04 15:10:53 +00002487 if (rhsType->isBlockPointerType())
2488 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2489
2490 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2491 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002492 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002493 }
Chris Lattner1853da22008-01-04 23:18:45 +00002494 return Incompatible;
2495 }
2496
Chris Lattner390564e2008-04-07 06:49:41 +00002497 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002498 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002499 if (lhsType == Context.BoolTy)
2500 return Compatible;
2501
2502 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002503 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002504
Chris Lattner390564e2008-04-07 06:49:41 +00002505 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002506 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002507
2508 if (isa<BlockPointerType>(lhsType) &&
2509 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002510 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002511 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002512 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002513
Chris Lattner1853da22008-01-04 23:18:45 +00002514 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002515 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002516 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002517 }
2518 return Incompatible;
2519}
2520
Chris Lattner005ed752008-01-04 18:04:52 +00002521Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002522Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002523 if (getLangOptions().CPlusPlus) {
2524 if (!lhsType->isRecordType()) {
2525 // C++ 5.17p3: If the left operand is not of class type, the
2526 // expression is implicitly converted (C++ 4) to the
2527 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002528 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2529 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002530 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002531 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002532 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002533 }
2534
2535 // FIXME: Currently, we fall through and treat C++ classes like C
2536 // structures.
2537 }
2538
Steve Naroffcdee22d2007-11-27 17:58:44 +00002539 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2540 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002541 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2542 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002543 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002544 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002545 return Compatible;
2546 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002547
2548 // We don't allow conversion of non-null-pointer constants to integers.
2549 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2550 return IntToBlockPointer;
2551
Chris Lattner5f505bf2007-10-16 02:55:40 +00002552 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002553 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002554 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002555 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002556 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002557 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002558 if (!lhsType->isReferenceType())
2559 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002560
Chris Lattner005ed752008-01-04 18:04:52 +00002561 Sema::AssignConvertType result =
2562 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002563
2564 // C99 6.5.16.1p2: The value of the right operand is converted to the
2565 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002566 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2567 // so that we can use references in built-in functions even in C.
2568 // The getNonReferenceType() call makes sure that the resulting expression
2569 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002570 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002571 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002572 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002573}
2574
Chris Lattner005ed752008-01-04 18:04:52 +00002575Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002576Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2577 return CheckAssignmentConstraints(lhsType, rhsType);
2578}
2579
Chris Lattner1eafdea2008-11-18 01:30:42 +00002580QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002581 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002582 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002583 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002584 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002585}
2586
Chris Lattner1eafdea2008-11-18 01:30:42 +00002587inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002588 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002589 // For conversion purposes, we ignore any qualifiers.
2590 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002591 QualType lhsType =
2592 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2593 QualType rhsType =
2594 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002595
Nate Begemanc5f0f652008-07-14 18:02:46 +00002596 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002597 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002598 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002599
Nate Begemanc5f0f652008-07-14 18:02:46 +00002600 // Handle the case of a vector & extvector type of the same size and element
2601 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002602 if (getLangOptions().LaxVectorConversions) {
2603 // FIXME: Should we warn here?
2604 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002605 if (const VectorType *RV = rhsType->getAsVectorType())
2606 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002607 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002608 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002609 }
2610 }
2611 }
2612
Nate Begemanc5f0f652008-07-14 18:02:46 +00002613 // If the lhs is an extended vector and the rhs is a scalar of the same type
2614 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002615 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002616 QualType eltType = V->getElementType();
2617
2618 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2619 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2620 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002621 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002622 return lhsType;
2623 }
2624 }
2625
Nate Begemanc5f0f652008-07-14 18:02:46 +00002626 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002627 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002628 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002629 QualType eltType = V->getElementType();
2630
2631 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2632 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2633 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002634 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002635 return rhsType;
2636 }
2637 }
2638
Chris Lattner4b009652007-07-25 00:24:17 +00002639 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002640 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002641 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002642 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002643 return QualType();
2644}
2645
2646inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002647 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002648{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002649 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002650 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002651
Steve Naroff8f708362007-08-24 19:07:16 +00002652 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002653
Chris Lattner4b009652007-07-25 00:24:17 +00002654 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002655 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002656 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002657}
2658
2659inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002660 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002661{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002662 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2663 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2664 return CheckVectorOperands(Loc, lex, rex);
2665 return InvalidOperands(Loc, lex, rex);
2666 }
Chris Lattner4b009652007-07-25 00:24:17 +00002667
Steve Naroff8f708362007-08-24 19:07:16 +00002668 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002669
Chris Lattner4b009652007-07-25 00:24:17 +00002670 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002671 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002672 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002673}
2674
2675inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002676 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002677{
2678 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002679 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002680
Steve Naroff8f708362007-08-24 19:07:16 +00002681 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002682
Chris Lattner4b009652007-07-25 00:24:17 +00002683 // handle the common case first (both operands are arithmetic).
2684 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002685 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002686
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002687 // Put any potential pointer into PExp
2688 Expr* PExp = lex, *IExp = rex;
2689 if (IExp->getType()->isPointerType())
2690 std::swap(PExp, IExp);
2691
2692 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2693 if (IExp->getType()->isIntegerType()) {
2694 // Check for arithmetic on pointers to incomplete types
2695 if (!PTy->getPointeeType()->isObjectType()) {
2696 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002697 if (getLangOptions().CPlusPlus) {
2698 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2699 << lex->getSourceRange() << rex->getSourceRange();
2700 return QualType();
2701 }
2702
2703 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002704 Diag(Loc, diag::ext_gnu_void_ptr)
2705 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002706 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002707 if (getLangOptions().CPlusPlus) {
2708 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2709 << lex->getType() << lex->getSourceRange();
2710 return QualType();
2711 }
2712
2713 // GNU extension: arithmetic on pointer to function
2714 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002715 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002716 } else {
2717 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2718 diag::err_typecheck_arithmetic_incomplete_type,
2719 lex->getSourceRange(), SourceRange(),
2720 lex->getType());
2721 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002722 }
2723 }
2724 return PExp->getType();
2725 }
2726 }
2727
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002729}
2730
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002731// C99 6.5.6
2732QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002733 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002734 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002735 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002736
Steve Naroff8f708362007-08-24 19:07:16 +00002737 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002738
Chris Lattnerf6da2912007-12-09 21:53:25 +00002739 // Enforce type constraints: C99 6.5.6p3.
2740
2741 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002742 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002743 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002744
2745 // Either ptr - int or ptr - ptr.
2746 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002747 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002748
Chris Lattnerf6da2912007-12-09 21:53:25 +00002749 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002750 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002751 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002752 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002753 Diag(Loc, diag::ext_gnu_void_ptr)
2754 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002755 } else if (lpointee->isFunctionType()) {
2756 if (getLangOptions().CPlusPlus) {
2757 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2758 << lex->getType() << lex->getSourceRange();
2759 return QualType();
2760 }
2761
2762 // GNU extension: arithmetic on pointer to function
2763 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2764 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002765 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002766 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002767 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002768 return QualType();
2769 }
2770 }
2771
2772 // The result type of a pointer-int computation is the pointer type.
2773 if (rex->getType()->isIntegerType())
2774 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002775
Chris Lattnerf6da2912007-12-09 21:53:25 +00002776 // Handle pointer-pointer subtractions.
2777 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002778 QualType rpointee = RHSPTy->getPointeeType();
2779
Chris Lattnerf6da2912007-12-09 21:53:25 +00002780 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002781 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002782 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002783 if (rpointee->isVoidType()) {
2784 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002785 Diag(Loc, diag::ext_gnu_void_ptr)
2786 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002787 } else if (rpointee->isFunctionType()) {
2788 if (getLangOptions().CPlusPlus) {
2789 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2790 << rex->getType() << rex->getSourceRange();
2791 return QualType();
2792 }
2793
2794 // GNU extension: arithmetic on pointer to function
2795 if (!lpointee->isFunctionType())
2796 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2797 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002798 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002799 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002800 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002801 return QualType();
2802 }
2803 }
2804
2805 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002806 if (!Context.typesAreCompatible(
2807 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2808 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002809 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002810 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002811 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002812 return QualType();
2813 }
2814
2815 return Context.getPointerDiffType();
2816 }
2817 }
2818
Chris Lattner1eafdea2008-11-18 01:30:42 +00002819 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002820}
2821
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002822// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002823QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002824 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002825 // C99 6.5.7p2: Each of the operands shall have integer type.
2826 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002827 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002828
Chris Lattner2c8bff72007-12-12 05:47:28 +00002829 // Shifts don't perform usual arithmetic conversions, they just do integer
2830 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002831 if (!isCompAssign)
2832 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002833 UsualUnaryConversions(rex);
2834
2835 // "The type of the result is that of the promoted left operand."
2836 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002837}
2838
Eli Friedman0d9549b2008-08-22 00:56:42 +00002839static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2840 ASTContext& Context) {
2841 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2842 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2843 // ID acts sort of like void* for ObjC interfaces
2844 if (LHSIface && Context.isObjCIdType(RHS))
2845 return true;
2846 if (RHSIface && Context.isObjCIdType(LHS))
2847 return true;
2848 if (!LHSIface || !RHSIface)
2849 return false;
2850 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2851 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2852}
2853
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002854// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002855QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002856 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002857 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002858 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002859
Chris Lattner254f3bc2007-08-26 01:18:55 +00002860 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002861 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2862 UsualArithmeticConversions(lex, rex);
2863 else {
2864 UsualUnaryConversions(lex);
2865 UsualUnaryConversions(rex);
2866 }
Chris Lattner4b009652007-07-25 00:24:17 +00002867 QualType lType = lex->getType();
2868 QualType rType = rex->getType();
2869
Ted Kremenek486509e2007-10-29 17:13:39 +00002870 // For non-floating point types, check for self-comparisons of the form
2871 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2872 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002873 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002874 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2875 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002876 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002877 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002878 }
2879
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002880 // The result of comparisons is 'bool' in C++, 'int' in C.
2881 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2882
Chris Lattner254f3bc2007-08-26 01:18:55 +00002883 if (isRelational) {
2884 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002885 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002886 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002887 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002888 if (lType->isFloatingType()) {
2889 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002890 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002891 }
2892
Chris Lattner254f3bc2007-08-26 01:18:55 +00002893 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002894 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002895 }
Chris Lattner4b009652007-07-25 00:24:17 +00002896
Chris Lattner22be8422007-08-26 01:10:14 +00002897 bool LHSIsNull = lex->isNullPointerConstant(Context);
2898 bool RHSIsNull = rex->isNullPointerConstant(Context);
2899
Chris Lattner254f3bc2007-08-26 01:18:55 +00002900 // All of the following pointer related warnings are GCC extensions, except
2901 // when handling null pointer constants. One day, we can consider making them
2902 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002903 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002904 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002905 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002906 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002907 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002908
Steve Naroff3b435622007-11-13 14:57:38 +00002909 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002910 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2911 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002912 RCanPointeeTy.getUnqualifiedType()) &&
2913 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002914 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002915 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002916 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002917 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002918 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002919 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002920 // Handle block pointer types.
2921 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2922 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2923 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2924
2925 if (!LHSIsNull && !RHSIsNull &&
2926 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002927 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002928 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002929 }
2930 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002931 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002932 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002933 // Allow block pointers to be compared with null pointer constants.
2934 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2935 (lType->isPointerType() && rType->isBlockPointerType())) {
2936 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002937 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002938 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002939 }
2940 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002941 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002942 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002943
Steve Naroff936c4362008-06-03 14:04:54 +00002944 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002945 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002946 const PointerType *LPT = lType->getAsPointerType();
2947 const PointerType *RPT = rType->getAsPointerType();
2948 bool LPtrToVoid = LPT ?
2949 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2950 bool RPtrToVoid = RPT ?
2951 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2952
2953 if (!LPtrToVoid && !RPtrToVoid &&
2954 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002955 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002956 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002957 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002958 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002959 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002960 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002961 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002962 }
Steve Naroff936c4362008-06-03 14:04:54 +00002963 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2964 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002965 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002966 } else {
2967 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002968 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002969 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002970 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002971 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002972 }
Steve Naroff936c4362008-06-03 14:04:54 +00002973 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002974 }
Steve Naroff936c4362008-06-03 14:04:54 +00002975 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2976 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002977 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002978 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002979 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002980 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002981 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002982 }
Steve Naroff936c4362008-06-03 14:04:54 +00002983 if (lType->isIntegerType() &&
2984 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002985 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002986 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002987 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002988 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002989 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002990 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002991 // Handle block pointers.
2992 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2993 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002994 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002995 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002996 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002997 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002998 }
2999 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3000 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003001 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003003 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003004 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003005 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003006 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003007}
3008
Nate Begemanc5f0f652008-07-14 18:02:46 +00003009/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3010/// operates on extended vector types. Instead of producing an IntTy result,
3011/// like a scalar comparison, a vector comparison produces a vector of integer
3012/// types.
3013QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003014 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003015 bool isRelational) {
3016 // Check to make sure we're operating on vectors of the same type and width,
3017 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003018 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003019 if (vType.isNull())
3020 return vType;
3021
3022 QualType lType = lex->getType();
3023 QualType rType = rex->getType();
3024
3025 // For non-floating point types, check for self-comparisons of the form
3026 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3027 // often indicate logic errors in the program.
3028 if (!lType->isFloatingType()) {
3029 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3030 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3031 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003032 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003033 }
3034
3035 // Check for comparisons of floating point operands using != and ==.
3036 if (!isRelational && lType->isFloatingType()) {
3037 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003038 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003039 }
3040
3041 // Return the type for the comparison, which is the same as vector type for
3042 // integer vectors, or an integer type of identical size and number of
3043 // elements for floating point vectors.
3044 if (lType->isIntegerType())
3045 return lType;
3046
3047 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003048 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003049 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003050 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003051 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3052 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3053
3054 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3055 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003056 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3057}
3058
Chris Lattner4b009652007-07-25 00:24:17 +00003059inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003060 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003061{
3062 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003063 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003064
Steve Naroff8f708362007-08-24 19:07:16 +00003065 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003066
3067 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003068 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003069 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003070}
3071
3072inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003073 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003074{
3075 UsualUnaryConversions(lex);
3076 UsualUnaryConversions(rex);
3077
Eli Friedmanbea3f842008-05-13 20:16:47 +00003078 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003079 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003081}
3082
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003083/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3084/// is a read-only property; return true if so. A readonly property expression
3085/// depends on various declarations and thus must be treated specially.
3086///
3087static bool IsReadonlyProperty(Expr *E, Sema &S)
3088{
3089 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3090 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3091 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3092 QualType BaseType = PropExpr->getBase()->getType();
3093 if (const PointerType *PTy = BaseType->getAsPointerType())
3094 if (const ObjCInterfaceType *IFTy =
3095 PTy->getPointeeType()->getAsObjCInterfaceType())
3096 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3097 if (S.isPropertyReadonly(PDecl, IFace))
3098 return true;
3099 }
3100 }
3101 return false;
3102}
3103
Chris Lattner4c2642c2008-11-18 01:22:49 +00003104/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3105/// emit an error and return true. If so, return false.
3106static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003107 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3108 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3109 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003110 if (IsLV == Expr::MLV_Valid)
3111 return false;
3112
3113 unsigned Diag = 0;
3114 bool NeedType = false;
3115 switch (IsLV) { // C99 6.5.16p2
3116 default: assert(0 && "Unknown result from isModifiableLvalue!");
3117 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003118 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003119 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3120 NeedType = true;
3121 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003122 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003123 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3124 NeedType = true;
3125 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003126 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003127 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3128 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003129 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003130 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3131 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003132 case Expr::MLV_IncompleteType:
3133 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003134 return S.DiagnoseIncompleteType(Loc, E->getType(),
3135 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3136 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003137 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003138 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3139 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003140 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003141 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3142 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003143 case Expr::MLV_ReadonlyProperty:
3144 Diag = diag::error_readonly_property_assignment;
3145 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003146 case Expr::MLV_NoSetterProperty:
3147 Diag = diag::error_nosetter_property_assignment;
3148 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003149 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003150
Chris Lattner4c2642c2008-11-18 01:22:49 +00003151 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003152 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003153 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003154 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003155 return true;
3156}
3157
3158
3159
3160// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003161QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3162 SourceLocation Loc,
3163 QualType CompoundType) {
3164 // Verify that LHS is a modifiable lvalue, and emit error if not.
3165 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003166 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003167
3168 QualType LHSType = LHS->getType();
3169 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003170
Chris Lattner005ed752008-01-04 18:04:52 +00003171 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003172 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003173 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003174 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003175 // Special case of NSObject attributes on c-style pointer types.
3176 if (ConvTy == IncompatiblePointer &&
3177 ((Context.isObjCNSObjectType(LHSType) &&
3178 Context.isObjCObjectPointerType(RHSType)) ||
3179 (Context.isObjCNSObjectType(RHSType) &&
3180 Context.isObjCObjectPointerType(LHSType))))
3181 ConvTy = Compatible;
3182
Chris Lattner34c85082008-08-21 18:04:13 +00003183 // If the RHS is a unary plus or minus, check to see if they = and + are
3184 // right next to each other. If so, the user may have typo'd "x =+ 4"
3185 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003186 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003187 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3188 RHSCheck = ICE->getSubExpr();
3189 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3190 if ((UO->getOpcode() == UnaryOperator::Plus ||
3191 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003192 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003193 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003194 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003195 Diag(Loc, diag::warn_not_compound_assign)
3196 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3197 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003198 }
3199 } else {
3200 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003202 }
Chris Lattner005ed752008-01-04 18:04:52 +00003203
Chris Lattner1eafdea2008-11-18 01:30:42 +00003204 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3205 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003206 return QualType();
3207
Chris Lattner4b009652007-07-25 00:24:17 +00003208 // C99 6.5.16p3: The type of an assignment expression is the type of the
3209 // left operand unless the left operand has qualified type, in which case
3210 // it is the unqualified version of the type of the left operand.
3211 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3212 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003213 // C++ 5.17p1: the type of the assignment expression is that of its left
3214 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003215 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003216}
3217
Chris Lattner1eafdea2008-11-18 01:30:42 +00003218// C99 6.5.17
3219QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3220 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003221
3222 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003223 DefaultFunctionArrayConversion(RHS);
3224 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003225}
3226
3227/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3228/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003229QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3230 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003231 QualType ResType = Op->getType();
3232 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003233
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003234 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3235 // Decrement of bool is not allowed.
3236 if (!isInc) {
3237 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3238 return QualType();
3239 }
3240 // Increment of bool sets it to true, but is deprecated.
3241 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3242 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003243 // OK!
3244 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3245 // C99 6.5.2.4p2, 6.5.6p2
3246 if (PT->getPointeeType()->isObjectType()) {
3247 // Pointer to object is ok!
3248 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003249 if (getLangOptions().CPlusPlus) {
3250 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3251 << Op->getSourceRange();
3252 return QualType();
3253 }
3254
3255 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003256 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003257 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003258 if (getLangOptions().CPlusPlus) {
3259 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3260 << Op->getType() << Op->getSourceRange();
3261 return QualType();
3262 }
3263
3264 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003265 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003266 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003267 } else {
3268 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3269 diag::err_typecheck_arithmetic_incomplete_type,
3270 Op->getSourceRange(), SourceRange(),
3271 ResType);
3272 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003273 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003274 } else if (ResType->isComplexType()) {
3275 // C99 does not support ++/-- on complex types, we allow as an extension.
3276 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003277 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003278 } else {
3279 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003280 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003281 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003282 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003283 // At this point, we know we have a real, complex or pointer type.
3284 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003285 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003286 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003287 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003288}
3289
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003290/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003291/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003292/// where the declaration is needed for type checking. We only need to
3293/// handle cases when the expression references a function designator
3294/// or is an lvalue. Here are some examples:
3295/// - &(x) => x
3296/// - &*****f => f for f a function designator.
3297/// - &s.xx => s
3298/// - &s.zz[1].yy -> s, if zz is an array
3299/// - *(x + 1) -> x, if x is an array
3300/// - &"123"[2] -> 0
3301/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003302static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003303 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003304 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003305 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003306 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003307 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003308 // Fields cannot be declared with a 'register' storage class.
3309 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003310 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003311 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003312 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003313 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003314 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003315
Douglas Gregord2baafd2008-10-21 16:13:35 +00003316 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003317 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003318 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003319 return 0;
3320 else
3321 return VD;
3322 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003323 case Stmt::UnaryOperatorClass: {
3324 UnaryOperator *UO = cast<UnaryOperator>(E);
3325
3326 switch(UO->getOpcode()) {
3327 case UnaryOperator::Deref: {
3328 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003329 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3330 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3331 if (!VD || VD->getType()->isPointerType())
3332 return 0;
3333 return VD;
3334 }
3335 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003336 }
3337 case UnaryOperator::Real:
3338 case UnaryOperator::Imag:
3339 case UnaryOperator::Extension:
3340 return getPrimaryDecl(UO->getSubExpr());
3341 default:
3342 return 0;
3343 }
3344 }
3345 case Stmt::BinaryOperatorClass: {
3346 BinaryOperator *BO = cast<BinaryOperator>(E);
3347
3348 // Handle cases involving pointer arithmetic. The result of an
3349 // Assign or AddAssign is not an lvalue so they can be ignored.
3350
3351 // (x + n) or (n + x) => x
3352 if (BO->getOpcode() == BinaryOperator::Add) {
3353 if (BO->getLHS()->getType()->isPointerType()) {
3354 return getPrimaryDecl(BO->getLHS());
3355 } else if (BO->getRHS()->getType()->isPointerType()) {
3356 return getPrimaryDecl(BO->getRHS());
3357 }
3358 }
3359
3360 return 0;
3361 }
Chris Lattner4b009652007-07-25 00:24:17 +00003362 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003363 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003364 case Stmt::ImplicitCastExprClass:
3365 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003366 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003367 default:
3368 return 0;
3369 }
3370}
3371
3372/// CheckAddressOfOperand - The operand of & must be either a function
3373/// designator or an lvalue designating an object. If it is an lvalue, the
3374/// object cannot be declared with storage class register or be a bit field.
3375/// Note: The usual conversions are *not* applied to the operand of the &
3376/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003377/// In C++, the operand might be an overloaded function name, in which case
3378/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003379QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003380 if (op->isTypeDependent())
3381 return Context.DependentTy;
3382
Steve Naroff9c6c3592008-01-13 17:10:08 +00003383 if (getLangOptions().C99) {
3384 // Implement C99-only parts of addressof rules.
3385 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3386 if (uOp->getOpcode() == UnaryOperator::Deref)
3387 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3388 // (assuming the deref expression is valid).
3389 return uOp->getSubExpr()->getType();
3390 }
3391 // Technically, there should be a check for array subscript
3392 // expressions here, but the result of one is always an lvalue anyway.
3393 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003394 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003395 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003396
Chris Lattner4b009652007-07-25 00:24:17 +00003397 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003398 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3399 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003400 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3401 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003402 return QualType();
3403 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003404 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003405 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3406 if (Field->isBitField()) {
3407 Diag(OpLoc, diag::err_typecheck_address_of)
3408 << "bit-field" << op->getSourceRange();
3409 return QualType();
3410 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003411 }
3412 // Check for Apple extension for accessing vector components.
3413 } else if (isa<ArraySubscriptExpr>(op) &&
3414 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003415 Diag(OpLoc, diag::err_typecheck_address_of)
3416 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003417 return QualType();
3418 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003419 // We have an lvalue with a decl. Make sure the decl is not declared
3420 // with the register storage-class specifier.
3421 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3422 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003423 Diag(OpLoc, diag::err_typecheck_address_of)
3424 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003425 return QualType();
3426 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003427 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003428 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003429 } else if (isa<FieldDecl>(dcl)) {
3430 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003431 } else if (isa<FunctionDecl>(dcl)) {
3432 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003433 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003434 else
Chris Lattner4b009652007-07-25 00:24:17 +00003435 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003436 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003437
Chris Lattner4b009652007-07-25 00:24:17 +00003438 // If the operand has type "type", the result has type "pointer to type".
3439 return Context.getPointerType(op->getType());
3440}
3441
Chris Lattnerda5c0872008-11-23 09:13:29 +00003442QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3443 UsualUnaryConversions(Op);
3444 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003445
Chris Lattnerda5c0872008-11-23 09:13:29 +00003446 // Note that per both C89 and C99, this is always legal, even if ptype is an
3447 // incomplete type or void. It would be possible to warn about dereferencing
3448 // a void pointer, but it's completely well-defined, and such a warning is
3449 // unlikely to catch any mistakes.
3450 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003451 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003452
Chris Lattner77d52da2008-11-20 06:06:08 +00003453 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003454 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003455 return QualType();
3456}
3457
3458static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3459 tok::TokenKind Kind) {
3460 BinaryOperator::Opcode Opc;
3461 switch (Kind) {
3462 default: assert(0 && "Unknown binop!");
3463 case tok::star: Opc = BinaryOperator::Mul; break;
3464 case tok::slash: Opc = BinaryOperator::Div; break;
3465 case tok::percent: Opc = BinaryOperator::Rem; break;
3466 case tok::plus: Opc = BinaryOperator::Add; break;
3467 case tok::minus: Opc = BinaryOperator::Sub; break;
3468 case tok::lessless: Opc = BinaryOperator::Shl; break;
3469 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3470 case tok::lessequal: Opc = BinaryOperator::LE; break;
3471 case tok::less: Opc = BinaryOperator::LT; break;
3472 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3473 case tok::greater: Opc = BinaryOperator::GT; break;
3474 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3475 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3476 case tok::amp: Opc = BinaryOperator::And; break;
3477 case tok::caret: Opc = BinaryOperator::Xor; break;
3478 case tok::pipe: Opc = BinaryOperator::Or; break;
3479 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3480 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3481 case tok::equal: Opc = BinaryOperator::Assign; break;
3482 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3483 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3484 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3485 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3486 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3487 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3488 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3489 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3490 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3491 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3492 case tok::comma: Opc = BinaryOperator::Comma; break;
3493 }
3494 return Opc;
3495}
3496
3497static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3498 tok::TokenKind Kind) {
3499 UnaryOperator::Opcode Opc;
3500 switch (Kind) {
3501 default: assert(0 && "Unknown unary op!");
3502 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3503 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3504 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3505 case tok::star: Opc = UnaryOperator::Deref; break;
3506 case tok::plus: Opc = UnaryOperator::Plus; break;
3507 case tok::minus: Opc = UnaryOperator::Minus; break;
3508 case tok::tilde: Opc = UnaryOperator::Not; break;
3509 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003510 case tok::kw___real: Opc = UnaryOperator::Real; break;
3511 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3512 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3513 }
3514 return Opc;
3515}
3516
Douglas Gregord7f915e2008-11-06 23:29:22 +00003517/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3518/// operator @p Opc at location @c TokLoc. This routine only supports
3519/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003520Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3521 unsigned Op,
3522 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003523 QualType ResultTy; // Result type of the binary operator.
3524 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3525 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3526
3527 switch (Opc) {
3528 default:
3529 assert(0 && "Unknown binary expr!");
3530 case BinaryOperator::Assign:
3531 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3532 break;
3533 case BinaryOperator::Mul:
3534 case BinaryOperator::Div:
3535 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3536 break;
3537 case BinaryOperator::Rem:
3538 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3539 break;
3540 case BinaryOperator::Add:
3541 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3542 break;
3543 case BinaryOperator::Sub:
3544 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3545 break;
3546 case BinaryOperator::Shl:
3547 case BinaryOperator::Shr:
3548 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3549 break;
3550 case BinaryOperator::LE:
3551 case BinaryOperator::LT:
3552 case BinaryOperator::GE:
3553 case BinaryOperator::GT:
3554 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3555 break;
3556 case BinaryOperator::EQ:
3557 case BinaryOperator::NE:
3558 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3559 break;
3560 case BinaryOperator::And:
3561 case BinaryOperator::Xor:
3562 case BinaryOperator::Or:
3563 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3564 break;
3565 case BinaryOperator::LAnd:
3566 case BinaryOperator::LOr:
3567 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3568 break;
3569 case BinaryOperator::MulAssign:
3570 case BinaryOperator::DivAssign:
3571 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3572 if (!CompTy.isNull())
3573 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3574 break;
3575 case BinaryOperator::RemAssign:
3576 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3577 if (!CompTy.isNull())
3578 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3579 break;
3580 case BinaryOperator::AddAssign:
3581 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3582 if (!CompTy.isNull())
3583 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3584 break;
3585 case BinaryOperator::SubAssign:
3586 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3587 if (!CompTy.isNull())
3588 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3589 break;
3590 case BinaryOperator::ShlAssign:
3591 case BinaryOperator::ShrAssign:
3592 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3593 if (!CompTy.isNull())
3594 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3595 break;
3596 case BinaryOperator::AndAssign:
3597 case BinaryOperator::XorAssign:
3598 case BinaryOperator::OrAssign:
3599 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3600 if (!CompTy.isNull())
3601 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3602 break;
3603 case BinaryOperator::Comma:
3604 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3605 break;
3606 }
3607 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003608 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003609 if (CompTy.isNull())
3610 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3611 else
3612 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003613 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003614}
3615
Chris Lattner4b009652007-07-25 00:24:17 +00003616// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003617Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3618 tok::TokenKind Kind,
3619 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003620 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003621 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003622
Steve Naroff87d58b42007-09-16 03:34:24 +00003623 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3624 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003625
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003626 // If either expression is type-dependent, just build the AST.
3627 // FIXME: We'll need to perform some caching of the result of name
3628 // lookup for operator+.
3629 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003630 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3631 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003632 Context.DependentTy,
3633 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003634 else
3635 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3636 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003637 }
3638
Douglas Gregord7f915e2008-11-06 23:29:22 +00003639 if (getLangOptions().CPlusPlus &&
3640 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3641 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003642 // If this is one of the assignment operators, we only perform
3643 // overload resolution if the left-hand side is a class or
3644 // enumeration type (C++ [expr.ass]p3).
3645 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3646 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3647 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3648 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003649
Douglas Gregord7f915e2008-11-06 23:29:22 +00003650 // Determine which overloaded operator we're dealing with.
3651 static const OverloadedOperatorKind OverOps[] = {
3652 OO_Star, OO_Slash, OO_Percent,
3653 OO_Plus, OO_Minus,
3654 OO_LessLess, OO_GreaterGreater,
3655 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3656 OO_EqualEqual, OO_ExclaimEqual,
3657 OO_Amp,
3658 OO_Caret,
3659 OO_Pipe,
3660 OO_AmpAmp,
3661 OO_PipePipe,
3662 OO_Equal, OO_StarEqual,
3663 OO_SlashEqual, OO_PercentEqual,
3664 OO_PlusEqual, OO_MinusEqual,
3665 OO_LessLessEqual, OO_GreaterGreaterEqual,
3666 OO_AmpEqual, OO_CaretEqual,
3667 OO_PipeEqual,
3668 OO_Comma
3669 };
3670 OverloadedOperatorKind OverOp = OverOps[Opc];
3671
Douglas Gregor5ed15042008-11-18 23:14:02 +00003672 // Add the appropriate overloaded operators (C++ [over.match.oper])
3673 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003674 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003675 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003676 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003677
3678 // Perform overload resolution.
3679 OverloadCandidateSet::iterator Best;
3680 switch (BestViableFunction(CandidateSet, Best)) {
3681 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003682 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003683 FunctionDecl *FnDecl = Best->Function;
3684
Douglas Gregor70d26122008-11-12 17:17:38 +00003685 if (FnDecl) {
3686 // We matched an overloaded operator. Build a call to that
3687 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003688
Douglas Gregor70d26122008-11-12 17:17:38 +00003689 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3691 if (PerformObjectArgumentInitialization(lhs, Method) ||
3692 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3693 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003694 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003695 } else {
3696 // Convert the arguments.
3697 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3698 "passing") ||
3699 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3700 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003701 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003702 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003703
Douglas Gregor70d26122008-11-12 17:17:38 +00003704 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003705 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003706 = FnDecl->getType()->getAsFunctionType()->getResultType();
3707 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003708
Douglas Gregor70d26122008-11-12 17:17:38 +00003709 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003710 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3711 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003712 UsualUnaryConversions(FnExpr);
3713
Steve Naroff774e4152009-01-21 00:14:39 +00003714 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3715 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003716 } else {
3717 // We matched a built-in operator. Convert the arguments, then
3718 // break out so that we will build the appropriate built-in
3719 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003720 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3721 Best->Conversions[0], "passing") ||
3722 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3723 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003724 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003725
3726 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003727 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003728 }
3729
3730 case OR_No_Viable_Function:
3731 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003732 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003733 break;
3734
3735 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003736 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3737 << BinaryOperator::getOpcodeStr(Opc)
3738 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003739 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003740 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003741 }
3742
Douglas Gregor70d26122008-11-12 17:17:38 +00003743 // Either we found no viable overloaded operator or we matched a
3744 // built-in operator. In either case, fall through to trying to
3745 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003746 }
3747
Douglas Gregord7f915e2008-11-06 23:29:22 +00003748 // Build a built-in binary operation.
3749 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003750}
3751
3752// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003753Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3754 tok::TokenKind Op, ExprArg input) {
3755 // FIXME: Input is modified later, but smart pointer not reassigned.
3756 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003757 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003758
3759 if (getLangOptions().CPlusPlus &&
3760 (Input->getType()->isRecordType()
3761 || Input->getType()->isEnumeralType())) {
3762 // Determine which overloaded operator we're dealing with.
3763 static const OverloadedOperatorKind OverOps[] = {
3764 OO_None, OO_None,
3765 OO_PlusPlus, OO_MinusMinus,
3766 OO_Amp, OO_Star,
3767 OO_Plus, OO_Minus,
3768 OO_Tilde, OO_Exclaim,
3769 OO_None, OO_None,
3770 OO_None,
3771 OO_None
3772 };
3773 OverloadedOperatorKind OverOp = OverOps[Opc];
3774
3775 // Add the appropriate overloaded operators (C++ [over.match.oper])
3776 // to the candidate set.
3777 OverloadCandidateSet CandidateSet;
3778 if (OverOp != OO_None)
3779 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3780
3781 // Perform overload resolution.
3782 OverloadCandidateSet::iterator Best;
3783 switch (BestViableFunction(CandidateSet, Best)) {
3784 case OR_Success: {
3785 // We found a built-in operator or an overloaded operator.
3786 FunctionDecl *FnDecl = Best->Function;
3787
3788 if (FnDecl) {
3789 // We matched an overloaded operator. Build a call to that
3790 // operator.
3791
3792 // Convert the arguments.
3793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3794 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003795 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003796 } else {
3797 // Convert the arguments.
3798 if (PerformCopyInitialization(Input,
3799 FnDecl->getParamDecl(0)->getType(),
3800 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003801 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003802 }
3803
3804 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003805 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003806 = FnDecl->getType()->getAsFunctionType()->getResultType();
3807 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003808
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003809 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003810 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3811 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003812 UsualUnaryConversions(FnExpr);
3813
Sebastian Redl8b769972009-01-19 00:08:26 +00003814 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003815 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3816 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003817 } else {
3818 // We matched a built-in operator. Convert the arguments, then
3819 // break out so that we will build the appropriate built-in
3820 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003821 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3822 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003823 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003824
3825 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003826 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003827 }
3828
3829 case OR_No_Viable_Function:
3830 // No viable function; fall through to handling this as a
3831 // built-in operator, which will produce an error message for us.
3832 break;
3833
3834 case OR_Ambiguous:
3835 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3836 << UnaryOperator::getOpcodeStr(Opc)
3837 << Input->getSourceRange();
3838 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003839 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003840 }
3841
3842 // Either we found no viable overloaded operator or we matched a
3843 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003844 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003845 }
3846
Chris Lattner4b009652007-07-25 00:24:17 +00003847 QualType resultType;
3848 switch (Opc) {
3849 default:
3850 assert(0 && "Unimplemented unary expr!");
3851 case UnaryOperator::PreInc:
3852 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003853 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3854 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003855 break;
3856 case UnaryOperator::AddrOf:
3857 resultType = CheckAddressOfOperand(Input, OpLoc);
3858 break;
3859 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003860 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003861 resultType = CheckIndirectionOperand(Input, OpLoc);
3862 break;
3863 case UnaryOperator::Plus:
3864 case UnaryOperator::Minus:
3865 UsualUnaryConversions(Input);
3866 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003867 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3868 break;
3869 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3870 resultType->isEnumeralType())
3871 break;
3872 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3873 Opc == UnaryOperator::Plus &&
3874 resultType->isPointerType())
3875 break;
3876
Sebastian Redl8b769972009-01-19 00:08:26 +00003877 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3878 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003879 case UnaryOperator::Not: // bitwise complement
3880 UsualUnaryConversions(Input);
3881 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003882 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3883 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3884 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003885 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003886 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003887 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003888 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3889 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003890 break;
3891 case UnaryOperator::LNot: // logical negation
3892 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3893 DefaultFunctionArrayConversion(Input);
3894 resultType = Input->getType();
3895 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003896 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3897 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003898 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003899 // In C++, it's bool. C++ 5.3.1p8
3900 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003901 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003902 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003903 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003904 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003905 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003906 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003907 resultType = Input->getType();
3908 break;
3909 }
3910 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003911 return ExprError();
3912 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003913 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003914}
3915
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003916/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3917Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003918 SourceLocation LabLoc,
3919 IdentifierInfo *LabelII) {
3920 // Look up the record for this label identifier.
3921 LabelStmt *&LabelDecl = LabelMap[LabelII];
3922
Daniel Dunbar879788d2008-08-04 16:51:22 +00003923 // If we haven't seen this label yet, create a forward reference. It
3924 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003925 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00003926 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00003927
3928 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00003929 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3930 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003931}
3932
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003933Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003934 SourceLocation RPLoc) { // "({..})"
3935 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3936 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3937 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3938
Eli Friedmanbc941e12009-01-24 23:09:00 +00003939 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3940 if (isFileScope) {
3941 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
3942 }
3943
Chris Lattner4b009652007-07-25 00:24:17 +00003944 // FIXME: there are a variety of strange constraints to enforce here, for
3945 // example, it is not possible to goto into a stmt expression apparently.
3946 // More semantic analysis is needed.
3947
3948 // FIXME: the last statement in the compount stmt has its value used. We
3949 // should not warn about it being unused.
3950
3951 // If there are sub stmts in the compound stmt, take the type of the last one
3952 // as the type of the stmtexpr.
3953 QualType Ty = Context.VoidTy;
3954
Chris Lattner200964f2008-07-26 19:51:01 +00003955 if (!Compound->body_empty()) {
3956 Stmt *LastStmt = Compound->body_back();
3957 // If LastStmt is a label, skip down through into the body.
3958 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3959 LastStmt = Label->getSubStmt();
3960
3961 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003962 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003963 }
Chris Lattner4b009652007-07-25 00:24:17 +00003964
Steve Naroff774e4152009-01-21 00:14:39 +00003965 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00003966}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003967
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003968Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3969 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003970 SourceLocation TypeLoc,
3971 TypeTy *argty,
3972 OffsetOfComponent *CompPtr,
3973 unsigned NumComponents,
3974 SourceLocation RPLoc) {
3975 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3976 assert(!ArgTy.isNull() && "Missing type argument!");
3977
3978 // We must have at least one component that refers to the type, and the first
3979 // one is known to be a field designator. Verify that the ArgTy represents
3980 // a struct/union/class.
3981 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003982 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003983
3984 // Otherwise, create a compound literal expression as the base, and
3985 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00003986 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00003987 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00003988 IList->setType(ArgTy);
3989 Expr *Res =
3990 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
3991
Chris Lattnerb37522e2007-08-31 21:49:13 +00003992 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3993 // GCC extension, diagnose them.
3994 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003995 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3996 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003997
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003998 for (unsigned i = 0; i != NumComponents; ++i) {
3999 const OffsetOfComponent &OC = CompPtr[i];
4000 if (OC.isBrackets) {
4001 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004002 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004003 if (!AT) {
4004 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004005 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004006 }
4007
Chris Lattner2af6a802007-08-30 17:59:59 +00004008 // FIXME: C++: Verify that operator[] isn't overloaded.
4009
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004010 // C99 6.5.2.1p1
4011 Expr *Idx = static_cast<Expr*>(OC.U.E);
4012 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004013 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4014 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004015
Steve Naroff774e4152009-01-21 00:14:39 +00004016 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4017 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004018 continue;
4019 }
4020
4021 const RecordType *RC = Res->getType()->getAsRecordType();
4022 if (!RC) {
4023 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004024 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004025 }
4026
4027 // Get the decl corresponding to this.
4028 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004029 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004030 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4031 LookupMemberName)
4032 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004033 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004034 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4035 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004036
4037 // FIXME: C++: Verify that MemberDecl isn't a static field.
4038 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004039 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4040 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004041 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4042 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004043 }
4044
Steve Naroff774e4152009-01-21 00:14:39 +00004045 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4046 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004047}
4048
4049
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004050Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004051 TypeTy *arg1, TypeTy *arg2,
4052 SourceLocation RPLoc) {
4053 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4054 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4055
4056 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4057
Steve Naroff774e4152009-01-21 00:14:39 +00004058 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4059 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004060}
4061
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004062Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004063 ExprTy *expr1, ExprTy *expr2,
4064 SourceLocation RPLoc) {
4065 Expr *CondExpr = static_cast<Expr*>(cond);
4066 Expr *LHSExpr = static_cast<Expr*>(expr1);
4067 Expr *RHSExpr = static_cast<Expr*>(expr2);
4068
4069 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4070
4071 // The conditional expression is required to be a constant expression.
4072 llvm::APSInt condEval(32);
4073 SourceLocation ExpLoc;
4074 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004075 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4076 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004077
4078 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4079 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4080 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004081 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4082 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004083}
4084
Steve Naroff52a81c02008-09-03 18:15:37 +00004085//===----------------------------------------------------------------------===//
4086// Clang Extensions.
4087//===----------------------------------------------------------------------===//
4088
4089/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004090void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004091 // Analyze block parameters.
4092 BlockSemaInfo *BSI = new BlockSemaInfo();
4093
4094 // Add BSI to CurBlock.
4095 BSI->PrevBlockInfo = CurBlock;
4096 CurBlock = BSI;
4097
4098 BSI->ReturnType = 0;
4099 BSI->TheScope = BlockScope;
4100
Steve Naroff52059382008-10-10 01:28:17 +00004101 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004102 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004103}
4104
4105void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004106 // Analyze arguments to block.
4107 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4108 "Not a function declarator!");
4109 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4110
Steve Naroff52059382008-10-10 01:28:17 +00004111 CurBlock->hasPrototype = FTI.hasPrototype;
4112 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004113
4114 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4115 // no arguments, not a function that takes a single void argument.
4116 if (FTI.hasPrototype &&
4117 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4118 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4119 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4120 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004121 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004122 } else if (FTI.hasPrototype) {
4123 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004124 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4125 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004126 }
Steve Naroff52059382008-10-10 01:28:17 +00004127 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4128
4129 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4130 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4131 // If this has an identifier, add it to the scope stack.
4132 if ((*AI)->getIdentifier())
4133 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004134}
4135
4136/// ActOnBlockError - If there is an error parsing a block, this callback
4137/// is invoked to pop the information about the block from the action impl.
4138void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4139 // Ensure that CurBlock is deleted.
4140 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4141
4142 // Pop off CurBlock, handle nested blocks.
4143 CurBlock = CurBlock->PrevBlockInfo;
4144
4145 // FIXME: Delete the ParmVarDecl objects as well???
4146
4147}
4148
4149/// ActOnBlockStmtExpr - This is called when the body of a block statement
4150/// literal was successfully completed. ^(int x){...}
4151Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4152 Scope *CurScope) {
4153 // Ensure that CurBlock is deleted.
4154 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4155 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4156
Steve Naroff52059382008-10-10 01:28:17 +00004157 PopDeclContext();
4158
Steve Naroff52a81c02008-09-03 18:15:37 +00004159 // Pop off CurBlock, handle nested blocks.
4160 CurBlock = CurBlock->PrevBlockInfo;
4161
4162 QualType RetTy = Context.VoidTy;
4163 if (BSI->ReturnType)
4164 RetTy = QualType(BSI->ReturnType, 0);
4165
4166 llvm::SmallVector<QualType, 8> ArgTypes;
4167 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4168 ArgTypes.push_back(BSI->Params[i]->getType());
4169
4170 QualType BlockTy;
4171 if (!BSI->hasPrototype)
4172 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4173 else
4174 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004175 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004176
4177 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004178
Steve Naroff95029d92008-10-08 18:44:00 +00004179 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004180 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004181}
4182
Nate Begemanbd881ef2008-01-30 20:50:20 +00004183/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004184/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004185/// The number of arguments has already been validated to match the number of
4186/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004187static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4188 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004189 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004190 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004191 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4192 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004193
4194 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004195 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004196 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004197 return true;
4198}
4199
4200Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4201 SourceLocation *CommaLocs,
4202 SourceLocation BuiltinLoc,
4203 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004204 // __builtin_overload requires at least 2 arguments
4205 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004206 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4207 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004208
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004209 // The first argument is required to be a constant expression. It tells us
4210 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004211 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004212 Expr *NParamsExpr = Args[0];
4213 llvm::APSInt constEval(32);
4214 SourceLocation ExpLoc;
4215 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004216 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4217 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004218
4219 // Verify that the number of parameters is > 0
4220 unsigned NumParams = constEval.getZExtValue();
4221 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004222 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4223 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004224 // Verify that we have at least 1 + NumParams arguments to the builtin.
4225 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004226 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4227 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004228
4229 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004230 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004231 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004232 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4233 // UsualUnaryConversions will convert the function DeclRefExpr into a
4234 // pointer to function.
4235 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004236 const FunctionTypeProto *FnType = 0;
4237 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4238 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004239
4240 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4241 // parameters, and the number of parameters must match the value passed to
4242 // the builtin.
4243 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004244 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4245 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004246
4247 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004248 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004249 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004250 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004251 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004252 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4253 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004254 // Remember our match, and continue processing the remaining arguments
4255 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004256 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004257 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004258 BuiltinLoc, RParenLoc);
4259 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004260 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004261 // Return the newly created OverloadExpr node, if we succeded in matching
4262 // exactly one of the candidate functions.
4263 if (OE)
4264 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004265
4266 // If we didn't find a matching function Expr in the __builtin_overload list
4267 // the return an error.
4268 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004269 for (unsigned i = 0; i != NumParams; ++i) {
4270 if (i != 0) typeNames += ", ";
4271 typeNames += Args[i+1]->getType().getAsString();
4272 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004273
Chris Lattner77d52da2008-11-20 06:06:08 +00004274 return Diag(BuiltinLoc, diag::err_overload_no_match)
4275 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004276}
4277
Anders Carlsson36760332007-10-15 20:28:48 +00004278Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4279 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004280 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004281 Expr *E = static_cast<Expr*>(expr);
4282 QualType T = QualType::getFromOpaquePtr(type);
4283
4284 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004285
4286 // Get the va_list type
4287 QualType VaListType = Context.getBuiltinVaListType();
4288 // Deal with implicit array decay; for example, on x86-64,
4289 // va_list is an array, but it's supposed to decay to
4290 // a pointer for va_arg.
4291 if (VaListType->isArrayType())
4292 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004293 // Make sure the input expression also decays appropriately.
4294 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004295
4296 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004297 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004298 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004299 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004300
4301 // FIXME: Warn if a non-POD type is passed in.
4302
Steve Naroff774e4152009-01-21 00:14:39 +00004303 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004304}
4305
Douglas Gregorad4b3792008-11-29 04:51:27 +00004306Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4307 // The type of __null will be int or long, depending on the size of
4308 // pointers on the target.
4309 QualType Ty;
4310 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4311 Ty = Context.IntTy;
4312 else
4313 Ty = Context.LongTy;
4314
Steve Naroff774e4152009-01-21 00:14:39 +00004315 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004316}
4317
Chris Lattner005ed752008-01-04 18:04:52 +00004318bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4319 SourceLocation Loc,
4320 QualType DstType, QualType SrcType,
4321 Expr *SrcExpr, const char *Flavor) {
4322 // Decode the result (notice that AST's are still created for extensions).
4323 bool isInvalid = false;
4324 unsigned DiagKind;
4325 switch (ConvTy) {
4326 default: assert(0 && "Unknown conversion type");
4327 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004328 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004329 DiagKind = diag::ext_typecheck_convert_pointer_int;
4330 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004331 case IntToPointer:
4332 DiagKind = diag::ext_typecheck_convert_int_pointer;
4333 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004334 case IncompatiblePointer:
4335 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4336 break;
4337 case FunctionVoidPointer:
4338 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4339 break;
4340 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004341 // If the qualifiers lost were because we were applying the
4342 // (deprecated) C++ conversion from a string literal to a char*
4343 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4344 // Ideally, this check would be performed in
4345 // CheckPointerTypesForAssignment. However, that would require a
4346 // bit of refactoring (so that the second argument is an
4347 // expression, rather than a type), which should be done as part
4348 // of a larger effort to fix CheckPointerTypesForAssignment for
4349 // C++ semantics.
4350 if (getLangOptions().CPlusPlus &&
4351 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4352 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004353 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4354 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004355 case IntToBlockPointer:
4356 DiagKind = diag::err_int_to_block_pointer;
4357 break;
4358 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004359 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004360 break;
Steve Naroff19608432008-10-14 22:18:38 +00004361 case IncompatibleObjCQualifiedId:
4362 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4363 // it can give a more specific diagnostic.
4364 DiagKind = diag::warn_incompatible_qualified_id;
4365 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004366 case IncompatibleVectors:
4367 DiagKind = diag::warn_incompatible_vectors;
4368 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004369 case Incompatible:
4370 DiagKind = diag::err_typecheck_convert_incompatible;
4371 isInvalid = true;
4372 break;
4373 }
4374
Chris Lattner271d4c22008-11-24 05:29:24 +00004375 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4376 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004377 return isInvalid;
4378}
Anders Carlssond5201b92008-11-30 19:50:32 +00004379
4380bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4381{
4382 Expr::EvalResult EvalResult;
4383
4384 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4385 EvalResult.HasSideEffects) {
4386 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4387
4388 if (EvalResult.Diag) {
4389 // We only show the note if it's not the usual "invalid subexpression"
4390 // or if it's actually in a subexpression.
4391 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4392 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4393 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4394 }
4395
4396 return true;
4397 }
4398
4399 if (EvalResult.Diag) {
4400 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4401 E->getSourceRange();
4402
4403 // Print the reason it's not a constant.
4404 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4405 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4406 }
4407
4408 if (Result)
4409 *Result = EvalResult.Val.getInt();
4410 return false;
4411}