blob: 5ebec0270b5020b80fdfc2c7aea830216af1d7b1 [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;
558 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000559 if (SS && !SS->isEmpty()) {
560 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000562 return ExprError();
Steve Naroffc349ee22009-01-29 00:07:50 +0000563 Lookup = LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000564 } else
Steve Naroffc349ee22009-01-29 00:07:50 +0000565 Lookup = LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000566
Sebastian Redlcd883f72009-01-18 18:53:16 +0000567 if (Lookup.isAmbiguous()) {
568 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
569 SS && SS->isSet() ? SS->getRange()
570 : SourceRange());
571 return ExprError();
572 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000573 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000574
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000575 // If this reference is in an Objective-C method, then ivar lookup happens as
576 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000577 IdentifierInfo *II = Name.getAsIdentifierInfo();
578 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000579 // There are two cases to handle here. 1) scoped lookup could have failed,
580 // in which case we should look for an ivar. 2) scoped lookup could have
581 // found a decl, but that decl is outside the current method (i.e. a global
582 // variable). In these two cases, we do a lookup for an ivar with this
583 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000584 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000585 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000586 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000587 // FIXME: This should use a new expr for a direct reference, don't turn
588 // this into Self->ivar, just return a BareIVarExpr or something.
589 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000590 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000591 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
592 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000593 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000594 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000595 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000596 }
597 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000598 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000599 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000600 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000601 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000602 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000603 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +0000605 if (D == 0) {
606 // Otherwise, this could be an implicitly declared function reference (legal
607 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000609 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000610 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000611 else {
612 // If this name wasn't predeclared and if this is not a function call,
613 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000614 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
616 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000617 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
618 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_undeclared_use)
620 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000621 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000622 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000623 }
624 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000625
626 // We may have found a field within an anonymous union or struct
627 // (C++ [class.union]).
628 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
629 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
630 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000631
Douglas Gregor3257fb52008-12-22 05:46:06 +0000632 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
633 if (!MD->isStatic()) {
634 // C++ [class.mfct.nonstatic]p2:
635 // [...] if name lookup (3.4.1) resolves the name in the
636 // id-expression to a nonstatic nontype member of class X or of
637 // a base class of X, the id-expression is transformed into a
638 // class member access expression (5.2.5) using (*this) (9.3.2)
639 // as the postfix-expression to the left of the '.' operator.
640 DeclContext *Ctx = 0;
641 QualType MemberType;
642 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
643 Ctx = FD->getDeclContext();
644 MemberType = FD->getType();
645
646 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
647 MemberType = RefType->getPointeeType();
648 else if (!FD->isMutable()) {
649 unsigned combinedQualifiers
650 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
651 MemberType = MemberType.getQualifiedType(combinedQualifiers);
652 }
653 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
654 if (!Method->isStatic()) {
655 Ctx = Method->getParent();
656 MemberType = Method->getType();
657 }
658 } else if (OverloadedFunctionDecl *Ovl
659 = dyn_cast<OverloadedFunctionDecl>(D)) {
660 for (OverloadedFunctionDecl::function_iterator
661 Func = Ovl->function_begin(),
662 FuncEnd = Ovl->function_end();
663 Func != FuncEnd; ++Func) {
664 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
665 if (!DMethod->isStatic()) {
666 Ctx = Ovl->getDeclContext();
667 MemberType = Context.OverloadTy;
668 break;
669 }
670 }
671 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000672
673 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000674 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
675 QualType ThisType = Context.getTagDeclType(MD->getParent());
676 if ((Context.getCanonicalType(CtxType)
677 == Context.getCanonicalType(ThisType)) ||
678 IsDerivedFrom(ThisType, CtxType)) {
679 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000680 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000681 MD->getThisType(Context));
Steve Naroff774e4152009-01-21 00:14:39 +0000682 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000683 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000684 }
685 }
686 }
687 }
688
Douglas Gregor8acb7272008-12-11 16:49:14 +0000689 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000690 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
691 if (MD->isStatic())
692 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000693 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
694 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000695 }
696
Douglas Gregor3257fb52008-12-22 05:46:06 +0000697 // Any other ways we could have found the field in a well-formed
698 // program would have been turned into implicit member expressions
699 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000700 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
701 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000702 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000703
Chris Lattner4b009652007-07-25 00:24:17 +0000704 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000705 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000706 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000707 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000708 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000710
Steve Naroffd6163f32008-09-05 22:11:13 +0000711 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000712 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000713 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
714 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000715
Steve Naroffd6163f32008-09-05 22:11:13 +0000716 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000717
Steve Naroffd6163f32008-09-05 22:11:13 +0000718 // check if referencing an identifier with __attribute__((deprecated)).
719 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000720 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
721
Douglas Gregor48840c72008-12-10 23:01:14 +0000722 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
723 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
724 Scope *CheckS = S;
725 while (CheckS) {
726 if (CheckS->isWithinElse() &&
727 CheckS->getControlParent()->isDeclScope(Var)) {
728 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000729 ExprError(Diag(Loc, diag::warn_value_always_false)
730 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000731 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000732 ExprError(Diag(Loc, diag::warn_value_always_zero)
733 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000734 break;
735 }
736
737 // Move up one more control parent to check again.
738 CheckS = CheckS->getControlParent();
739 if (CheckS)
740 CheckS = CheckS->getParent();
741 }
742 }
743 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000744
745 // Only create DeclRefExpr's for valid Decl's.
746 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000747 return ExprError();
748
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000749 // If the identifier reference is inside a block, and it refers to a value
750 // that is outside the block, create a BlockDeclRefExpr instead of a
751 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
752 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000753 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000754 // We do not do this for things like enum constants, global variables, etc,
755 // as they do not get snapshotted.
756 //
757 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000758 // The BlocksAttr indicates the variable is bound by-reference.
759 if (VD->getAttr<BlocksAttr>())
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, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000762
Steve Naroff52059382008-10-10 01:28:17 +0000763 // Variable will be bound by-copy, make it const within the closure.
764 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000765 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000766 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000767 }
768 // If this reference is not in a block or if the referenced variable is
769 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000770
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000771 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000772 bool ValueDependent = false;
773 if (getLangOptions().CPlusPlus) {
774 // C++ [temp.dep.expr]p3:
775 // An id-expression is type-dependent if it contains:
776 // - an identifier that was declared with a dependent type,
777 if (VD->getType()->isDependentType())
778 TypeDependent = true;
779 // - FIXME: a template-id that is dependent,
780 // - a conversion-function-id that specifies a dependent type,
781 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
782 Name.getCXXNameType()->isDependentType())
783 TypeDependent = true;
784 // - a nested-name-specifier that contains a class-name that
785 // names a dependent type.
786 else if (SS && !SS->isEmpty()) {
787 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
788 DC; DC = DC->getParent()) {
789 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000790 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000791 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
792 if (Context.getTypeDeclType(Record)->isDependentType()) {
793 TypeDependent = true;
794 break;
795 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000796 }
797 }
798 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000799
Douglas Gregora5d84612008-12-10 20:57:37 +0000800 // C++ [temp.dep.constexpr]p2:
801 //
802 // An identifier is value-dependent if it is:
803 // - a name declared with a dependent type,
804 if (TypeDependent)
805 ValueDependent = true;
806 // - the name of a non-type template parameter,
807 else if (isa<NonTypeTemplateParmDecl>(VD))
808 ValueDependent = true;
809 // - a constant with integral or enumeration type and is
810 // initialized with an expression that is value-dependent
811 // (FIXME!).
812 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000813
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
815 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000816}
817
Sebastian Redlcd883f72009-01-18 18:53:16 +0000818Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
819 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000820 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000821
Chris Lattner4b009652007-07-25 00:24:17 +0000822 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000823 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000824 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
825 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
826 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000827 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000828
Chris Lattner7e637512008-01-12 08:14:25 +0000829 // Pre-defined identifiers are of type char[x], where x is the length of the
830 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000831 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000832 if (FunctionDecl *FD = getCurFunctionDecl())
833 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000834 else if (ObjCMethodDecl *MD = getCurMethodDecl())
835 Length = MD->getSynthesizedMethodSize();
836 else {
837 Diag(Loc, diag::ext_predef_outside_function);
838 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
839 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
840 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841
842
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000843 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000844 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000845 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000846 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000847}
848
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000850 llvm::SmallString<16> CharBuffer;
851 CharBuffer.resize(Tok.getLength());
852 const char *ThisTokBegin = &CharBuffer[0];
853 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000854
Chris Lattner4b009652007-07-25 00:24:17 +0000855 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
856 Tok.getLocation(), PP);
857 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000858 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000859
860 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
861
Sebastian Redl75324932009-01-20 22:23:13 +0000862 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
863 Literal.isWide(),
864 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000865}
866
Sebastian Redlcd883f72009-01-18 18:53:16 +0000867Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
868 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000869 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
870 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000871 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000872 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000873 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000874 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000876
Chris Lattner4b009652007-07-25 00:24:17 +0000877 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000878 // Add padding so that NumericLiteralParser can overread by one character.
879 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000880 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000881
Chris Lattner4b009652007-07-25 00:24:17 +0000882 // Get the spelling of the token, which eliminates trigraphs, etc.
883 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000884
Chris Lattner4b009652007-07-25 00:24:17 +0000885 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
886 Tok.getLocation(), PP);
887 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000888 return ExprError();
889
Chris Lattner1de66eb2007-08-26 03:42:43 +0000890 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000891
Chris Lattner1de66eb2007-08-26 03:42:43 +0000892 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000893 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000894 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000895 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000896 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000897 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000898 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000899 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000900
901 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
902
Ted Kremenekddedbe22007-11-29 00:56:49 +0000903 // isExact will be set by GetFloatValue().
904 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000905 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
906 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000907
Chris Lattner1de66eb2007-08-26 03:42:43 +0000908 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000909 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000910 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000911 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000912
Neil Booth7421e9c2007-08-29 22:00:19 +0000913 // long long is a C99 feature.
914 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000915 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000916 Diag(Tok.getLocation(), diag::ext_longlong);
917
Chris Lattner4b009652007-07-25 00:24:17 +0000918 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000919 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000920
Chris Lattner4b009652007-07-25 00:24:17 +0000921 if (Literal.GetIntegerValue(ResultVal)) {
922 // If this value didn't fit into uintmax_t, warn and force to ull.
923 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000924 Ty = Context.UnsignedLongLongTy;
925 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000926 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000927 } else {
928 // If this value fits into a ULL, try to figure out what else it fits into
929 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Chris Lattner4b009652007-07-25 00:24:17 +0000931 // Octal, Hexadecimal, and integers with a U suffix are allowed to
932 // be an unsigned int.
933 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
934
935 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000936 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000937 if (!Literal.isLong && !Literal.isLongLong) {
938 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000939 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000940
Chris Lattner4b009652007-07-25 00:24:17 +0000941 // Does it fit in a unsigned int?
942 if (ResultVal.isIntN(IntSize)) {
943 // Does it fit in a signed int?
944 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000945 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000946 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000947 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000948 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
Chris Lattner4b009652007-07-25 00:24:17 +0000950 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000951
Chris Lattner4b009652007-07-25 00:24:17 +0000952 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000953 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000954 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000955
Chris Lattner4b009652007-07-25 00:24:17 +0000956 // Does it fit in a unsigned long?
957 if (ResultVal.isIntN(LongSize)) {
958 // Does it fit in a signed long?
959 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000960 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000961 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000963 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000964 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 }
966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000968 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000969 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 // Does it fit in a unsigned long long?
972 if (ResultVal.isIntN(LongLongSize)) {
973 // Does it fit in a signed long long?
974 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000975 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000977 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000978 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000979 }
980 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000981
Chris Lattner4b009652007-07-25 00:24:17 +0000982 // If we still couldn't decide a type, we probably have something that
983 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000984 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000985 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000986 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000987 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000989
Chris Lattnere4068872008-05-09 05:59:00 +0000990 if (ResultVal.getBitWidth() != Width)
991 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000992 }
Sebastian Redl75324932009-01-20 22:23:13 +0000993 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000995
Chris Lattner1de66eb2007-08-26 03:42:43 +0000996 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
997 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +0000998 Res = new (Context) ImaginaryLiteral(Res,
999 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001000
1001 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001002}
1003
Sebastian Redlcd883f72009-01-18 18:53:16 +00001004Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1005 SourceLocation R, ExprArg Val) {
1006 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001007 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001008 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001009}
1010
1011/// The UsualUnaryConversions() function is *not* called by this routine.
1012/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001013bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1014 SourceLocation OpLoc,
1015 const SourceRange &ExprRange,
1016 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001017 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001018 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001019 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001020 if (isSizeof)
1021 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1022 return false;
1023 }
1024
1025 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001026 Diag(OpLoc, diag::ext_sizeof_void_type)
1027 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001028 return false;
1029 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001030
Chris Lattner159fe082009-01-24 19:46:37 +00001031 return DiagnoseIncompleteType(OpLoc, exprType,
1032 isSizeof ? diag::err_sizeof_incomplete_type :
1033 diag::err_alignof_incomplete_type,
1034 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001035}
1036
Chris Lattner8d9f7962009-01-24 20:17:12 +00001037bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1038 const SourceRange &ExprRange) {
1039 E = E->IgnoreParens();
1040
1041 // alignof decl is always ok.
1042 if (isa<DeclRefExpr>(E))
1043 return false;
1044
1045 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1046 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1047 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001048 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001049 return true;
1050 }
1051 // Other fields are ok.
1052 return false;
1053 }
1054 }
1055 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1056}
1057
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001058/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1059/// the same for @c alignof and @c __alignof
1060/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001061Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001062Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1063 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001064 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001065 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001066
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001067 QualType ArgTy;
1068 SourceRange Range;
1069 if (isType) {
1070 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1071 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001072
1073 // Verify that the operand is valid.
1074 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1075 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001076 } else {
1077 // Get the end location.
1078 Expr *ArgEx = (Expr *)TyOrEx;
1079 Range = ArgEx->getSourceRange();
1080 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001081
1082 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001083 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001084 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001085 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001086 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1087 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1088 isInvalid = true;
1089 } else {
1090 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1091 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001092
1093 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001094 DeleteExpr(ArgEx);
1095 return ExprError();
1096 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001097 }
1098
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001099 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001100 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001101 Context.getSizeType(), OpLoc,
1102 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001103}
1104
Chris Lattner5110ad52007-08-24 21:41:10 +00001105QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001106 DefaultFunctionArrayConversion(V);
1107
Chris Lattnera16e42d2007-08-26 05:39:26 +00001108 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001109 if (const ComplexType *CT = V->getType()->getAsComplexType())
1110 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001111
1112 // Otherwise they pass through real integer and floating point types here.
1113 if (V->getType()->isArithmeticType())
1114 return V->getType();
1115
1116 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001117 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001118 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001119}
1120
1121
Chris Lattner4b009652007-07-25 00:24:17 +00001122
Sebastian Redl8b769972009-01-19 00:08:26 +00001123Action::OwningExprResult
1124Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1125 tok::TokenKind Kind, ExprArg Input) {
1126 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001127
Chris Lattner4b009652007-07-25 00:24:17 +00001128 UnaryOperator::Opcode Opc;
1129 switch (Kind) {
1130 default: assert(0 && "Unknown unary op!");
1131 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1132 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1133 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001134
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001135 if (getLangOptions().CPlusPlus &&
1136 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1137 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001138 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001139 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1140
1141 // C++ [over.inc]p1:
1142 //
1143 // [...] If the function is a member function with one
1144 // parameter (which shall be of type int) or a non-member
1145 // function with two parameters (the second of which shall be
1146 // of type int), it defines the postfix increment operator ++
1147 // for objects of that type. When the postfix increment is
1148 // called as a result of using the ++ operator, the int
1149 // argument will have value zero.
1150 Expr *Args[2] = {
1151 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001152 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1153 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001154 };
1155
1156 // Build the candidate set for overloading
1157 OverloadCandidateSet CandidateSet;
1158 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1159
1160 // Perform overload resolution.
1161 OverloadCandidateSet::iterator Best;
1162 switch (BestViableFunction(CandidateSet, Best)) {
1163 case OR_Success: {
1164 // We found a built-in operator or an overloaded operator.
1165 FunctionDecl *FnDecl = Best->Function;
1166
1167 if (FnDecl) {
1168 // We matched an overloaded operator. Build a call to that
1169 // operator.
1170
1171 // Convert the arguments.
1172 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1173 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001174 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001175 } else {
1176 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001177 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178 FnDecl->getParamDecl(0)->getType(),
1179 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001180 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001181 }
1182
1183 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001184 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001185 = FnDecl->getType()->getAsFunctionType()->getResultType();
1186 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001187
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001188 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001189 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001190 SourceLocation());
1191 UsualUnaryConversions(FnExpr);
1192
Sebastian Redl8b769972009-01-19 00:08:26 +00001193 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001194 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001195 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001196 } else {
1197 // We matched a built-in operator. Convert the arguments, then
1198 // break out so that we will build the appropriate built-in
1199 // operator node.
1200 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1201 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001202 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001203
1204 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001205 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001206 }
1207
1208 case OR_No_Viable_Function:
1209 // No viable function; fall through to handling this as a
1210 // built-in operator, which will produce an error message for us.
1211 break;
1212
1213 case OR_Ambiguous:
1214 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1215 << UnaryOperator::getOpcodeStr(Opc)
1216 << Arg->getSourceRange();
1217 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001218 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001219 }
1220
1221 // Either we found no viable overloaded operator or we matched a
1222 // built-in operator. In either case, fall through to trying to
1223 // build a built-in operation.
1224 }
1225
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001226 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1227 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001228 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001229 return ExprError();
1230 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001231 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001232}
1233
Sebastian Redl8b769972009-01-19 00:08:26 +00001234Action::OwningExprResult
1235Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1236 ExprArg Idx, SourceLocation RLoc) {
1237 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1238 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001239
Douglas Gregor80723c52008-11-19 17:17:41 +00001240 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001241 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001242 LHSExp->getType()->isEnumeralType() ||
1243 RHSExp->getType()->isRecordType() ||
1244 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001245 // Add the appropriate overloaded operators (C++ [over.match.oper])
1246 // to the candidate set.
1247 OverloadCandidateSet CandidateSet;
1248 Expr *Args[2] = { LHSExp, RHSExp };
1249 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001250
Douglas Gregor80723c52008-11-19 17:17:41 +00001251 // Perform overload resolution.
1252 OverloadCandidateSet::iterator Best;
1253 switch (BestViableFunction(CandidateSet, Best)) {
1254 case OR_Success: {
1255 // We found a built-in operator or an overloaded operator.
1256 FunctionDecl *FnDecl = Best->Function;
1257
1258 if (FnDecl) {
1259 // We matched an overloaded operator. Build a call to that
1260 // operator.
1261
1262 // Convert the arguments.
1263 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1264 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1265 PerformCopyInitialization(RHSExp,
1266 FnDecl->getParamDecl(0)->getType(),
1267 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001268 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001269 } else {
1270 // Convert the arguments.
1271 if (PerformCopyInitialization(LHSExp,
1272 FnDecl->getParamDecl(0)->getType(),
1273 "passing") ||
1274 PerformCopyInitialization(RHSExp,
1275 FnDecl->getParamDecl(1)->getType(),
1276 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001277 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001278 }
1279
1280 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001281 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001282 = FnDecl->getType()->getAsFunctionType()->getResultType();
1283 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001284
Douglas Gregor80723c52008-11-19 17:17:41 +00001285 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001286 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001287 SourceLocation());
1288 UsualUnaryConversions(FnExpr);
1289
Sebastian Redl8b769972009-01-19 00:08:26 +00001290 Base.release();
1291 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001292 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1293 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001294 } else {
1295 // We matched a built-in operator. Convert the arguments, then
1296 // break out so that we will build the appropriate built-in
1297 // operator node.
1298 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1299 "passing") ||
1300 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1301 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001302 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001303
1304 break;
1305 }
1306 }
1307
1308 case OR_No_Viable_Function:
1309 // No viable function; fall through to handling this as a
1310 // built-in operator, which will produce an error message for us.
1311 break;
1312
1313 case OR_Ambiguous:
1314 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1315 << "[]"
1316 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1317 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001318 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001319 }
1320
1321 // Either we found no viable overloaded operator or we matched a
1322 // built-in operator. In either case, fall through to trying to
1323 // build a built-in operation.
1324 }
1325
Chris Lattner4b009652007-07-25 00:24:17 +00001326 // Perform default conversions.
1327 DefaultFunctionArrayConversion(LHSExp);
1328 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001329
Chris Lattner4b009652007-07-25 00:24:17 +00001330 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1331
1332 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001333 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001334 // in the subscript position. As a result, we need to derive the array base
1335 // and index from the expression types.
1336 Expr *BaseExpr, *IndexExpr;
1337 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001338 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001339 BaseExpr = LHSExp;
1340 IndexExpr = RHSExp;
1341 // FIXME: need to deal with const...
1342 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001343 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001344 // Handle the uncommon case of "123[Ptr]".
1345 BaseExpr = RHSExp;
1346 IndexExpr = LHSExp;
1347 // FIXME: need to deal with const...
1348 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001349 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1350 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001351 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001352
Chris Lattner4b009652007-07-25 00:24:17 +00001353 // FIXME: need to deal with const...
1354 ResultType = VTy->getElementType();
1355 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError(Diag(LHSExp->getLocStart(),
1357 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1358 }
Chris Lattner4b009652007-07-25 00:24:17 +00001359 // C99 6.5.2.1p1
1360 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001361 return ExprError(Diag(IndexExpr->getLocStart(),
1362 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001363
1364 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1365 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001366 // void (*)(int)) and pointers to incomplete types. Functions are not
1367 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001368 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001369 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001370 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001371 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001372
Sebastian Redl8b769972009-01-19 00:08:26 +00001373 Base.release();
1374 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001375 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1376 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001377}
1378
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001379QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001380CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001381 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001382 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001383
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001384 // The vector accessor can't exceed the number of elements.
1385 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001386
1387 // This flag determines whether or not the component is one of the four
1388 // special names that indicate a subset of exactly half the elements are
1389 // to be selected.
1390 bool HalvingSwizzle = false;
1391
1392 // This flag determines whether or not CompName has an 's' char prefix,
1393 // indicating that it is a string of hex values to be used as vector indices.
1394 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001395
1396 // Check that we've found one of the special components, or that the component
1397 // names must come from the same set.
1398 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001399 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1400 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001401 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001402 do
1403 compStr++;
1404 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001405 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001406 do
1407 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001408 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001409 }
Nate Begeman1486b502009-01-18 01:47:54 +00001410
1411 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001412 // We didn't get to the end of the string. This means the component names
1413 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001414 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1415 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001416 return QualType();
1417 }
Nate Begeman1486b502009-01-18 01:47:54 +00001418
1419 // Ensure no component accessor exceeds the width of the vector type it
1420 // operates on.
1421 if (!HalvingSwizzle) {
1422 compStr = CompName.getName();
1423
1424 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001425 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001426
1427 while (*compStr) {
1428 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1429 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1430 << baseType << SourceRange(CompLoc);
1431 return QualType();
1432 }
1433 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001434 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001435
Nate Begeman1486b502009-01-18 01:47:54 +00001436 // If this is a halving swizzle, verify that the base type has an even
1437 // number of elements.
1438 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001439 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001440 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001441 return QualType();
1442 }
1443
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001444 // The component accessor looks fine - now we need to compute the actual type.
1445 // The vector type is implied by the component accessor. For example,
1446 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001447 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001448 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001449 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1450 : CompName.getLength();
1451 if (HexSwizzle)
1452 CompSize--;
1453
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001454 if (CompSize == 1)
1455 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001456
Nate Begemanaf6ed502008-04-18 23:10:10 +00001457 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001458 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001459 // diagostics look bad. We want extended vector types to appear built-in.
1460 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1461 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1462 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001463 }
1464 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001465}
1466
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001467/// constructSetterName - Return the setter name for the given
1468/// identifier, i.e. "set" + Name where the initial character of Name
1469/// has been capitalized.
1470// FIXME: Merge with same routine in Parser. But where should this
1471// live?
1472static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1473 const IdentifierInfo *Name) {
1474 llvm::SmallString<100> SelectorName;
1475 SelectorName = "set";
1476 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1477 SelectorName[3] = toupper(SelectorName[3]);
1478 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1479}
1480
Sebastian Redl8b769972009-01-19 00:08:26 +00001481Action::OwningExprResult
1482Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1483 tok::TokenKind OpKind, SourceLocation MemberLoc,
1484 IdentifierInfo &Member) {
1485 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001486 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001487
1488 // Perform default conversions.
1489 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001490
Steve Naroff2cb66382007-07-26 03:11:44 +00001491 QualType BaseType = BaseExpr->getType();
1492 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001493
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001494 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1495 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001496 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001497 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001498 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001499 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1501 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001502 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001503 return ExprError(Diag(MemberLoc,
1504 diag::err_typecheck_member_reference_arrow)
1505 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001506 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001507
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001508 // Handle field access to simple records. This also handles access to fields
1509 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001510 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001511 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001512 if (DiagnoseIncompleteType(OpLoc, BaseType,
1513 diag::err_typecheck_incomplete_tag,
1514 BaseExpr->getSourceRange()))
1515 return ExprError();
1516
Steve Naroff2cb66382007-07-26 03:11:44 +00001517 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001518 // FIXME: Qualified name lookup for C++ is a bit more complicated
1519 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001520 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001521 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1522 LookupCriteria(LookupCriteria::Member,
1523 /*RedeclarationOnly=*/false,
1524 getLangOptions().CPlusPlus));
1525
1526 Decl *MemberDecl = 0;
1527 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001528 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1529 << &Member << BaseExpr->getSourceRange());
1530 else if (Result.isAmbiguous()) {
1531 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1532 MemberLoc, BaseExpr->getSourceRange());
1533 return ExprError();
1534 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001535 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001536
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001537 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001538 // We may have found a field within an anonymous union or struct
1539 // (C++ [class.union]).
1540 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001541 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001543
Douglas Gregor82d44772008-12-20 23:49:58 +00001544 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1545 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001546 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001547 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1548 MemberType = Ref->getPointeeType();
1549 else {
1550 unsigned combinedQualifiers =
1551 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001552 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001553 combinedQualifiers &= ~QualType::Const;
1554 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1555 }
Eli Friedman76b49832008-02-06 22:48:16 +00001556
Steve Naroff774e4152009-01-21 00:14:39 +00001557 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1558 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001559 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001560 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 Var, MemberLoc,
1562 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001563 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001564 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1565 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001567 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001568 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001569 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001570 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001571 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001572 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001573 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001574 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1575 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001576
Douglas Gregor82d44772008-12-20 23:49:58 +00001577 // We found a declaration kind that we didn't expect. This is a
1578 // generic error message that tells the user that she can't refer
1579 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001580 return ExprError(Diag(MemberLoc,
1581 diag::err_typecheck_member_reference_unknown)
1582 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001583 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001584
Chris Lattnere9d71612008-07-21 04:59:05 +00001585 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1586 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001587 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001588 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001589 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1590 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001591 OpKind == tok::arrow);
1592 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001593 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001594 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001595 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1596 << IFTy->getDecl()->getDeclName() << &Member
1597 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001598 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001599
Chris Lattnere9d71612008-07-21 04:59:05 +00001600 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1601 // pointer to a (potentially qualified) interface type.
1602 const PointerType *PTy;
1603 const ObjCInterfaceType *IFTy;
1604 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1605 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1606 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001607
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001608 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001609 if (ObjCPropertyDecl *PD = IFace->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));
1612
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001613 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001614 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1615 E = IFTy->qual_end(); I != E; ++I)
1616 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001617 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001618 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001619
1620 // If that failed, look for an "implicit" property by seeing if the nullary
1621 // selector is implemented.
1622
1623 // FIXME: The logic for looking up nullary and unary selectors should be
1624 // shared with the code in ActOnInstanceMessage.
1625
1626 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1627 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001628
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001629 // If this reference is in an @implementation, check for 'private' methods.
1630 if (!Getter)
1631 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1632 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1633 if (ObjCImplementationDecl *ImpDecl =
1634 ObjCImplementations[ClassDecl->getIdentifier()])
1635 Getter = ImpDecl->getInstanceMethod(Sel);
1636
Steve Naroff04151f32008-10-22 19:16:27 +00001637 // Look through local category implementations associated with the class.
1638 if (!Getter) {
1639 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1640 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1641 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1642 }
1643 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001644 if (Getter) {
1645 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001646 // will look for the matching setter, in case it is needed.
1647 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1648 &Member);
1649 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1650 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1651 if (!Setter) {
1652 // If this reference is in an @implementation, also check for 'private'
1653 // methods.
1654 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1655 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1656 if (ObjCImplementationDecl *ImpDecl =
1657 ObjCImplementations[ClassDecl->getIdentifier()])
1658 Setter = ImpDecl->getInstanceMethod(SetterSel);
1659 }
1660 // Look through local category implementations associated with the class.
1661 if (!Setter) {
1662 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1663 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1664 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1665 }
1666 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001667
1668 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001669 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1670 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001671 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001672
1673 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1674 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001675 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001676 // Handle properties on qualified "id" protocols.
1677 const ObjCQualifiedIdType *QIdTy;
1678 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1679 // Check protocols on qualified interfaces.
1680 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001681 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001682 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001683 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001685 // Also must look for a getter name which uses property syntax.
1686 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1687 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001688 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1689 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001690 }
1691 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001692
1693 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1694 << &Member << BaseType);
1695 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001696 // Handle 'field access' to vectors, such as 'V.xx'.
1697 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001698 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1699 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001700 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001701 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1702 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001703 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001704
1705 return ExprError(Diag(MemberLoc,
1706 diag::err_typecheck_member_reference_struct_union)
1707 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
Douglas Gregor3257fb52008-12-22 05:46:06 +00001710/// ConvertArgumentsForCall - Converts the arguments specified in
1711/// Args/NumArgs to the parameter types of the function FDecl with
1712/// function prototype Proto. Call is the call expression itself, and
1713/// Fn is the function expression. For a C++ member function, this
1714/// routine does not attempt to convert the object argument. Returns
1715/// true if the call is ill-formed.
1716bool
1717Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1718 FunctionDecl *FDecl,
1719 const FunctionTypeProto *Proto,
1720 Expr **Args, unsigned NumArgs,
1721 SourceLocation RParenLoc) {
1722 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1723 // assignment, to the types of the corresponding parameter, ...
1724 unsigned NumArgsInProto = Proto->getNumArgs();
1725 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001726 bool Invalid = false;
1727
Douglas Gregor3257fb52008-12-22 05:46:06 +00001728 // If too few arguments are available (and we don't have default
1729 // arguments for the remaining parameters), don't make the call.
1730 if (NumArgs < NumArgsInProto) {
1731 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1732 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1733 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1734 // Use default arguments for missing arguments
1735 NumArgsToCheck = NumArgsInProto;
1736 Call->setNumArgs(NumArgsInProto);
1737 }
1738
1739 // If too many are passed and not variadic, error on the extras and drop
1740 // them.
1741 if (NumArgs > NumArgsInProto) {
1742 if (!Proto->isVariadic()) {
1743 Diag(Args[NumArgsInProto]->getLocStart(),
1744 diag::err_typecheck_call_too_many_args)
1745 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1746 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1747 Args[NumArgs-1]->getLocEnd());
1748 // This deletes the extra arguments.
1749 Call->setNumArgs(NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001750 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001751 }
1752 NumArgsToCheck = NumArgsInProto;
1753 }
1754
1755 // Continue to check argument types (even if we have too few/many args).
1756 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1757 QualType ProtoArgType = Proto->getArgType(i);
1758
1759 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001760 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001761 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001762
1763 // Pass the argument.
1764 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1765 return true;
1766 } else
1767 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001768 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001769 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001770
Douglas Gregor3257fb52008-12-22 05:46:06 +00001771 Call->setArg(i, Arg);
1772 }
1773
1774 // If this is a variadic call, handle args passed through "...".
1775 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001776 VariadicCallType CallType = VariadicFunction;
1777 if (Fn->getType()->isBlockPointerType())
1778 CallType = VariadicBlock; // Block
1779 else if (isa<MemberExpr>(Fn))
1780 CallType = VariadicMethod;
1781
Douglas Gregor3257fb52008-12-22 05:46:06 +00001782 // Promote the arguments (C99 6.5.2.2p7).
1783 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1784 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001785 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001786 Call->setArg(i, Arg);
1787 }
1788 }
1789
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001790 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001791}
1792
Steve Naroff87d58b42007-09-16 03:34:24 +00001793/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001794/// This provides the location of the left/right parens and a list of comma
1795/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001796Action::OwningExprResult
1797Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1798 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001799 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001800 unsigned NumArgs = args.size();
1801 Expr *Fn = static_cast<Expr *>(fn.release());
1802 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001803 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001804 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001805 OverloadedFunctionDecl *Ovl = NULL;
1806
Douglas Gregora133e262008-12-06 00:22:45 +00001807 // Determine whether this is a dependent call inside a C++ template,
1808 // in which case we won't do any semantic analysis now.
1809 bool Dependent = false;
1810 if (Fn->isTypeDependent()) {
1811 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1812 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1813 Dependent = true;
1814 else {
1815 // Resolve the CXXDependentNameExpr to an actual identifier;
1816 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001817 OwningExprResult Resolved
1818 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1819 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001820 /*HasTrailingLParen=*/true,
1821 /*SS=*/0,
1822 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001823 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001824 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001825 else {
1826 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001827 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001828 }
1829 }
1830 } else
1831 Dependent = true;
1832 } else
1833 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1834
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001835 // FIXME: Will need to cache the results of name lookup (including
1836 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001837 if (Dependent)
Steve Naroff774e4152009-01-21 00:14:39 +00001838 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1839 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001840
Douglas Gregor3257fb52008-12-22 05:46:06 +00001841 // Determine whether this is a call to an object (C++ [over.call.object]).
1842 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001843 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1844 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001845
1846 // Determine whether this is a call to a member function.
1847 if (getLangOptions().CPlusPlus) {
1848 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1849 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1850 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001851 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1852 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001853 }
1854
Douglas Gregord2baafd2008-10-21 16:13:35 +00001855 // If we're directly calling a function or a set of overloaded
1856 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001857 DeclRefExpr *DRExpr = NULL;
1858 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1859 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1860 else
1861 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001862
Douglas Gregor566782a2009-01-06 05:10:23 +00001863 if (DRExpr) {
1864 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1865 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001866 }
1867
Douglas Gregord2baafd2008-10-21 16:13:35 +00001868 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001869 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1870 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001871 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001872 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001873
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001874 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001875 Expr *NewFn = 0;
1876 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff774e4152009-01-21 00:14:39 +00001877 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor566782a2009-01-06 05:10:23 +00001878 QDRExpr->getLocation(), false, false,
1879 QDRExpr->getSourceRange().getBegin());
1880 else
Steve Naroff774e4152009-01-21 00:14:39 +00001881 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1882 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001883 Fn->Destroy(Context);
1884 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001885 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001886
1887 // Promote the function operand.
1888 UsualUnaryConversions(Fn);
1889
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001890 // Make the call expr early, before semantic checks. This guarantees cleanup
1891 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001892 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1893 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001894 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001895 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001896
Steve Naroffd6163f32008-09-05 22:11:13 +00001897 const FunctionType *FuncT;
1898 if (!Fn->getType()->isBlockPointerType()) {
1899 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1900 // have type pointer to function".
1901 const PointerType *PT = Fn->getType()->getAsPointerType();
1902 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001903 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1904 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001905 FuncT = PT->getPointeeType()->getAsFunctionType();
1906 } else { // This is a block call.
1907 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1908 getAsFunctionType();
1909 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001910 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001911 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1912 << Fn->getType() << Fn->getSourceRange());
1913
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001914 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001915 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001916
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001917 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001918 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1919 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001920 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001921 } else {
1922 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001923
Steve Naroffdb65e052007-08-28 23:30:39 +00001924 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001925 for (unsigned i = 0; i != NumArgs; i++) {
1926 Expr *Arg = Args[i];
1927 DefaultArgumentPromotion(Arg);
1928 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001929 }
Chris Lattner4b009652007-07-25 00:24:17 +00001930 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001931
Douglas Gregor3257fb52008-12-22 05:46:06 +00001932 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1933 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001934 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1935 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001936
Chris Lattner2e64c072007-08-10 20:18:51 +00001937 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001938 if (FDecl)
1939 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001940
Sebastian Redl8b769972009-01-19 00:08:26 +00001941 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001942}
1943
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001944Action::OwningExprResult
1945Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1946 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001947 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001948 QualType literalType = QualType::getFromOpaquePtr(Ty);
1949 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001950 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001951 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001952
Eli Friedman8c2173d2008-05-20 05:22:08 +00001953 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001954 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001955 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1956 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001957 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1958 diag::err_typecheck_decl_incomplete_type,
1959 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001960 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001961
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001962 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001963 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001964 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001965
Chris Lattnere5cb5862008-12-04 23:50:19 +00001966 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001967 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001968 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001969 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001970 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001971 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001972 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1973 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001974}
1975
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001976Action::OwningExprResult
1977Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1978 InitListDesignations &Designators,
1979 SourceLocation RBraceLoc) {
1980 unsigned NumInit = initlist.size();
1981 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001982
Steve Naroff0acc9c92007-09-15 18:49:24 +00001983 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001984 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001985
Steve Naroff774e4152009-01-21 00:14:39 +00001986 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00001987 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00001988 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001989 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001990}
1991
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001992/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001993bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001994 UsualUnaryConversions(castExpr);
1995
1996 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1997 // type needs to be scalar.
1998 if (castType->isVoidType()) {
1999 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002000 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2001 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002002 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002003 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2004 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2005 (castType->isStructureType() || castType->isUnionType())) {
2006 // GCC struct/union extension: allow cast to self.
2007 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2008 << castType << castExpr->getSourceRange();
2009 } else if (castType->isUnionType()) {
2010 // GCC cast to union extension
2011 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2012 RecordDecl::field_iterator Field, FieldEnd;
2013 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2014 Field != FieldEnd; ++Field) {
2015 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2016 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2017 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2018 << castExpr->getSourceRange();
2019 break;
2020 }
2021 }
2022 if (Field == FieldEnd)
2023 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2024 << castExpr->getType() << castExpr->getSourceRange();
2025 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002026 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002027 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002028 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002029 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002030 } else if (!castExpr->getType()->isScalarType() &&
2031 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002032 return Diag(castExpr->getLocStart(),
2033 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002034 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002035 } else if (castExpr->getType()->isVectorType()) {
2036 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2037 return true;
2038 } else if (castType->isVectorType()) {
2039 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2040 return true;
2041 }
2042 return false;
2043}
2044
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002045bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002046 assert(VectorTy->isVectorType() && "Not a vector type!");
2047
2048 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002049 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002050 return Diag(R.getBegin(),
2051 Ty->isVectorType() ?
2052 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002053 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002054 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002055 } else
2056 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002057 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002058 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002059
2060 return false;
2061}
2062
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002063Action::OwningExprResult
2064Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2065 SourceLocation RParenLoc, ExprArg Op) {
2066 assert((Ty != 0) && (Op.get() != 0) &&
2067 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002068
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002069 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002070 QualType castType = QualType::getFromOpaquePtr(Ty);
2071
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002072 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002073 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002074 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002075 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002076}
2077
Chris Lattner98a425c2007-11-26 01:40:58 +00002078/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2079/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002080inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2081 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2082 UsualUnaryConversions(cond);
2083 UsualUnaryConversions(lex);
2084 UsualUnaryConversions(rex);
2085 QualType condT = cond->getType();
2086 QualType lexT = lex->getType();
2087 QualType rexT = rex->getType();
2088
2089 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002090 if (!cond->isTypeDependent()) {
2091 if (!condT->isScalarType()) { // C99 6.5.15p2
2092 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2093 return QualType();
2094 }
Chris Lattner4b009652007-07-25 00:24:17 +00002095 }
Chris Lattner992ae932008-01-06 22:42:25 +00002096
2097 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002098 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2099 return Context.DependentTy;
2100
Chris Lattner992ae932008-01-06 22:42:25 +00002101 // If both operands have arithmetic type, do the usual arithmetic conversions
2102 // to find a common type: C99 6.5.15p3,5.
2103 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002104 UsualArithmeticConversions(lex, rex);
2105 return lex->getType();
2106 }
Chris Lattner992ae932008-01-06 22:42:25 +00002107
2108 // If both operands are the same structure or union type, the result is that
2109 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002110 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002111 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002112 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002113 // "If both the operands have structure or union type, the result has
2114 // that type." This implies that CV qualifiers are dropped.
2115 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002116 }
Chris Lattner992ae932008-01-06 22:42:25 +00002117
2118 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002119 // The following || allows only one side to be void (a GCC-ism).
2120 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002121 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002122 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2123 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002124 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002125 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2126 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002127 ImpCastExprToType(lex, Context.VoidTy);
2128 ImpCastExprToType(rex, Context.VoidTy);
2129 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002130 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002131 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2132 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002133 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2134 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002135 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002136 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002137 return lexT;
2138 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002139 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2140 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002141 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002142 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002143 return rexT;
2144 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002145 // Handle the case where both operands are pointers before we handle null
2146 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002147 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2148 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2149 // get the "pointed to" types
2150 QualType lhptee = LHSPT->getPointeeType();
2151 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002152
Chris Lattner71225142007-07-31 21:27:01 +00002153 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2154 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002155 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002156 // Figure out necessary qualifiers (C99 6.5.15p6)
2157 QualType destPointee=lhptee.getQualifiedType(rhptee.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 Lattner9db553e2008-04-02 06:59:01 +00002163 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002164 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002165 QualType destType = Context.getPointerType(destPointee);
2166 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2167 ImpCastExprToType(rex, destType); // promote to void*
2168 return destType;
2169 }
Chris Lattner4b009652007-07-25 00:24:17 +00002170
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002171 QualType compositeType = lexT;
2172
2173 // If either type is an Objective-C object type then check
2174 // compatibility according to Objective-C.
2175 if (Context.isObjCObjectPointerType(lexT) ||
2176 Context.isObjCObjectPointerType(rexT)) {
2177 // If both operands are interfaces and either operand can be
2178 // assigned to the other, use that type as the composite
2179 // type. This allows
2180 // xxx ? (A*) a : (B*) b
2181 // where B is a subclass of A.
2182 //
2183 // Additionally, as for assignment, if either type is 'id'
2184 // allow silent coercion. Finally, if the types are
2185 // incompatible then make sure to use 'id' as the composite
2186 // type so the result is acceptable for sending messages to.
2187
2188 // FIXME: This code should not be localized to here. Also this
2189 // should use a compatible check instead of abusing the
2190 // canAssignObjCInterfaces code.
2191 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2192 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2193 if (LHSIface && RHSIface &&
2194 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2195 compositeType = lexT;
2196 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002197 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002198 compositeType = rexT;
2199 } else if (Context.isObjCIdType(lhptee) ||
2200 Context.isObjCIdType(rhptee)) {
2201 // FIXME: This code looks wrong, because isObjCIdType checks
2202 // the struct but getObjCIdType returns the pointer to
2203 // struct. This is horrible and should be fixed.
2204 compositeType = Context.getObjCIdType();
2205 } else {
2206 QualType incompatTy = Context.getObjCIdType();
2207 ImpCastExprToType(lex, incompatTy);
2208 ImpCastExprToType(rex, incompatTy);
2209 return incompatTy;
2210 }
2211 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2212 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002213 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002214 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002215 // In this situation, we assume void* type. No especially good
2216 // reason, but this is what gcc does, and we do have to pick
2217 // to get a consistent AST.
2218 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002219 ImpCastExprToType(lex, incompatTy);
2220 ImpCastExprToType(rex, incompatTy);
2221 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002222 }
2223 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002224 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2225 // differently qualified versions of compatible types, the result type is
2226 // a pointer to an appropriately qualified version of the *composite*
2227 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002228 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002229 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002230 ImpCastExprToType(lex, compositeType);
2231 ImpCastExprToType(rex, compositeType);
2232 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002233 }
Chris Lattner4b009652007-07-25 00:24:17 +00002234 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002235 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2236 // evaluates to "struct objc_object *" (and is handled above when comparing
2237 // id with statically typed objects).
2238 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2239 // GCC allows qualified id and any Objective-C type to devolve to
2240 // id. Currently localizing to here until clear this should be
2241 // part of ObjCQualifiedIdTypesAreCompatible.
2242 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2243 (lexT->isObjCQualifiedIdType() &&
2244 Context.isObjCObjectPointerType(rexT)) ||
2245 (rexT->isObjCQualifiedIdType() &&
2246 Context.isObjCObjectPointerType(lexT))) {
2247 // FIXME: This is not the correct composite type. This only
2248 // happens to work because id can more or less be used anywhere,
2249 // however this may change the type of method sends.
2250 // FIXME: gcc adds some type-checking of the arguments and emits
2251 // (confusing) incompatible comparison warnings in some
2252 // cases. Investigate.
2253 QualType compositeType = Context.getObjCIdType();
2254 ImpCastExprToType(lex, compositeType);
2255 ImpCastExprToType(rex, compositeType);
2256 return compositeType;
2257 }
2258 }
2259
Steve Naroff3eac7692008-09-10 19:17:48 +00002260 // Selection between block pointer types is ok as long as they are the same.
2261 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2262 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2263 return lexT;
2264
Chris Lattner992ae932008-01-06 22:42:25 +00002265 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002266 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002267 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002268 return QualType();
2269}
2270
Steve Naroff87d58b42007-09-16 03:34:24 +00002271/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002272/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002273Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2274 SourceLocation ColonLoc,
2275 ExprArg Cond, ExprArg LHS,
2276 ExprArg RHS) {
2277 Expr *CondExpr = (Expr *) Cond.get();
2278 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002279
2280 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2281 // was the condition.
2282 bool isLHSNull = LHSExpr == 0;
2283 if (isLHSNull)
2284 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002285
2286 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002287 RHSExpr, QuestionLoc);
2288 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002289 return ExprError();
2290
2291 Cond.release();
2292 LHS.release();
2293 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002294 return Owned(new (Context) ConditionalOperator(CondExpr,
2295 isLHSNull ? 0 : LHSExpr,
2296 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002297}
2298
Chris Lattner4b009652007-07-25 00:24:17 +00002299
2300// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2301// being closely modeled after the C99 spec:-). The odd characteristic of this
2302// routine is it effectively iqnores the qualifiers on the top level pointee.
2303// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2304// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002305Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002306Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2307 QualType lhptee, rhptee;
2308
2309 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002310 lhptee = lhsType->getAsPointerType()->getPointeeType();
2311 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002312
2313 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002314 lhptee = Context.getCanonicalType(lhptee);
2315 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002316
Chris Lattner005ed752008-01-04 18:04:52 +00002317 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002318
2319 // C99 6.5.16.1p1: This following citation is common to constraints
2320 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2321 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002322 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002323 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002324 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002325
2326 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2327 // incomplete type and the other is a pointer to a qualified or unqualified
2328 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002329 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002330 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002331 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002332
2333 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002334 assert(rhptee->isFunctionType());
2335 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002336 }
2337
2338 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002339 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002340 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002341
2342 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002343 assert(lhptee->isFunctionType());
2344 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002345 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002346
2347 // Check for ObjC interfaces
2348 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2349 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2350 if (LHSIface && RHSIface &&
2351 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2352 return ConvTy;
2353
2354 // ID acts sort of like void* for ObjC interfaces
2355 if (LHSIface && Context.isObjCIdType(rhptee))
2356 return ConvTy;
2357 if (RHSIface && Context.isObjCIdType(lhptee))
2358 return ConvTy;
2359
Chris Lattner4b009652007-07-25 00:24:17 +00002360 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2361 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002362 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2363 rhptee.getUnqualifiedType()))
2364 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002365 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002366}
2367
Steve Naroff3454b6c2008-09-04 15:10:53 +00002368/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2369/// block pointer types are compatible or whether a block and normal pointer
2370/// are compatible. It is more restrict than comparing two function pointer
2371// types.
2372Sema::AssignConvertType
2373Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2374 QualType rhsType) {
2375 QualType lhptee, rhptee;
2376
2377 // get the "pointed to" type (ignoring qualifiers at the top level)
2378 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2379 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2380
2381 // make sure we operate on the canonical type
2382 lhptee = Context.getCanonicalType(lhptee);
2383 rhptee = Context.getCanonicalType(rhptee);
2384
2385 AssignConvertType ConvTy = Compatible;
2386
2387 // For blocks we enforce that qualifiers are identical.
2388 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2389 ConvTy = CompatiblePointerDiscardsQualifiers;
2390
2391 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2392 return IncompatibleBlockPointer;
2393 return ConvTy;
2394}
2395
Chris Lattner4b009652007-07-25 00:24:17 +00002396/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2397/// has code to accommodate several GCC extensions when type checking
2398/// pointers. Here are some objectionable examples that GCC considers warnings:
2399///
2400/// int a, *pint;
2401/// short *pshort;
2402/// struct foo *pfoo;
2403///
2404/// pint = pshort; // warning: assignment from incompatible pointer type
2405/// a = pint; // warning: assignment makes integer from pointer without a cast
2406/// pint = a; // warning: assignment makes pointer from integer without a cast
2407/// pint = pfoo; // warning: assignment from incompatible pointer type
2408///
2409/// As a result, the code for dealing with pointers is more complex than the
2410/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002411///
Chris Lattner005ed752008-01-04 18:04:52 +00002412Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002413Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002414 // Get canonical types. We're not formatting these types, just comparing
2415 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002416 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2417 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002418
2419 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002420 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002421
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002422 // If the left-hand side is a reference type, then we are in a
2423 // (rare!) case where we've allowed the use of references in C,
2424 // e.g., as a parameter type in a built-in function. In this case,
2425 // just make sure that the type referenced is compatible with the
2426 // right-hand side type. The caller is responsible for adjusting
2427 // lhsType so that the resulting expression does not have reference
2428 // type.
2429 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2430 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002431 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002432 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002433 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002434
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002435 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2436 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002437 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002438 // Relax integer conversions like we do for pointers below.
2439 if (rhsType->isIntegerType())
2440 return IntToPointer;
2441 if (lhsType->isIntegerType())
2442 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002443 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002444 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002445
Nate Begemanc5f0f652008-07-14 18:02:46 +00002446 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002447 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002448 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2449 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002450 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002451
Nate Begemanc5f0f652008-07-14 18:02:46 +00002452 // If we are allowing lax vector conversions, and LHS and RHS are both
2453 // vectors, the total size only needs to be the same. This is a bitcast;
2454 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002455 if (getLangOptions().LaxVectorConversions &&
2456 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002457 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2458 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002459 }
2460 return Incompatible;
2461 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002462
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002463 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002464 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002465
Chris Lattner390564e2008-04-07 06:49:41 +00002466 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002467 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002468 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002469
Chris Lattner390564e2008-04-07 06:49:41 +00002470 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002471 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002472
Steve Naroffa982c712008-09-29 18:10:17 +00002473 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002474 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002475 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002476
2477 // Treat block pointers as objects.
2478 if (getLangOptions().ObjC1 &&
2479 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2480 return Compatible;
2481 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002482 return Incompatible;
2483 }
2484
2485 if (isa<BlockPointerType>(lhsType)) {
2486 if (rhsType->isIntegerType())
2487 return IntToPointer;
2488
Steve Naroffa982c712008-09-29 18:10:17 +00002489 // Treat block pointers as objects.
2490 if (getLangOptions().ObjC1 &&
2491 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2492 return Compatible;
2493
Steve Naroff3454b6c2008-09-04 15:10:53 +00002494 if (rhsType->isBlockPointerType())
2495 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2496
2497 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2498 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002499 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002500 }
Chris Lattner1853da22008-01-04 23:18:45 +00002501 return Incompatible;
2502 }
2503
Chris Lattner390564e2008-04-07 06:49:41 +00002504 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002505 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002506 if (lhsType == Context.BoolTy)
2507 return Compatible;
2508
2509 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002510 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002511
Chris Lattner390564e2008-04-07 06:49:41 +00002512 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002513 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002514
2515 if (isa<BlockPointerType>(lhsType) &&
2516 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002517 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002518 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002519 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002520
Chris Lattner1853da22008-01-04 23:18:45 +00002521 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002522 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002523 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002524 }
2525 return Incompatible;
2526}
2527
Chris Lattner005ed752008-01-04 18:04:52 +00002528Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002529Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002530 if (getLangOptions().CPlusPlus) {
2531 if (!lhsType->isRecordType()) {
2532 // C++ 5.17p3: If the left operand is not of class type, the
2533 // expression is implicitly converted (C++ 4) to the
2534 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002535 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2536 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002537 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002538 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002539 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002540 }
2541
2542 // FIXME: Currently, we fall through and treat C++ classes like C
2543 // structures.
2544 }
2545
Steve Naroffcdee22d2007-11-27 17:58:44 +00002546 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2547 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002548 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2549 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002550 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002551 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002552 return Compatible;
2553 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002554
2555 // We don't allow conversion of non-null-pointer constants to integers.
2556 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2557 return IntToBlockPointer;
2558
Chris Lattner5f505bf2007-10-16 02:55:40 +00002559 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002560 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002561 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002562 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002563 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002564 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002565 if (!lhsType->isReferenceType())
2566 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002567
Chris Lattner005ed752008-01-04 18:04:52 +00002568 Sema::AssignConvertType result =
2569 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002570
2571 // C99 6.5.16.1p2: The value of the right operand is converted to the
2572 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002573 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2574 // so that we can use references in built-in functions even in C.
2575 // The getNonReferenceType() call makes sure that the resulting expression
2576 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002577 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002578 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002579 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002580}
2581
Chris Lattner005ed752008-01-04 18:04:52 +00002582Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002583Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2584 return CheckAssignmentConstraints(lhsType, rhsType);
2585}
2586
Chris Lattner1eafdea2008-11-18 01:30:42 +00002587QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002588 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002589 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002590 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002591 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002592}
2593
Chris Lattner1eafdea2008-11-18 01:30:42 +00002594inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002595 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002596 // For conversion purposes, we ignore any qualifiers.
2597 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002598 QualType lhsType =
2599 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2600 QualType rhsType =
2601 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002602
Nate Begemanc5f0f652008-07-14 18:02:46 +00002603 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002604 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002605 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002606
Nate Begemanc5f0f652008-07-14 18:02:46 +00002607 // Handle the case of a vector & extvector type of the same size and element
2608 // type. It would be nice if we only had one vector type someday.
2609 if (getLangOptions().LaxVectorConversions)
2610 if (const VectorType *LV = lhsType->getAsVectorType())
2611 if (const VectorType *RV = rhsType->getAsVectorType())
2612 if (LV->getElementType() == RV->getElementType() &&
2613 LV->getNumElements() == RV->getNumElements())
2614 return lhsType->isExtVectorType() ? lhsType : rhsType;
2615
2616 // If the lhs is an extended vector and the rhs is a scalar of the same type
2617 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002618 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002619 QualType eltType = V->getElementType();
2620
2621 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2622 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2623 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002624 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002625 return lhsType;
2626 }
2627 }
2628
Nate Begemanc5f0f652008-07-14 18:02:46 +00002629 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002630 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002631 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002632 QualType eltType = V->getElementType();
2633
2634 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2635 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2636 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002637 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002638 return rhsType;
2639 }
2640 }
2641
Chris Lattner4b009652007-07-25 00:24:17 +00002642 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002643 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002644 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002645 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002646 return QualType();
2647}
2648
2649inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002650 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002651{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002652 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002653 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002654
Steve Naroff8f708362007-08-24 19:07:16 +00002655 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002656
Chris Lattner4b009652007-07-25 00:24:17 +00002657 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002658 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002659 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002660}
2661
2662inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002663 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002664{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002665 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2666 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2667 return CheckVectorOperands(Loc, lex, rex);
2668 return InvalidOperands(Loc, lex, rex);
2669 }
Chris Lattner4b009652007-07-25 00:24:17 +00002670
Steve Naroff8f708362007-08-24 19:07:16 +00002671 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002672
Chris Lattner4b009652007-07-25 00:24:17 +00002673 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002674 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002675 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002676}
2677
2678inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002679 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002680{
2681 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002682 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002683
Steve Naroff8f708362007-08-24 19:07:16 +00002684 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002685
Chris Lattner4b009652007-07-25 00:24:17 +00002686 // handle the common case first (both operands are arithmetic).
2687 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002688 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002689
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002690 // Put any potential pointer into PExp
2691 Expr* PExp = lex, *IExp = rex;
2692 if (IExp->getType()->isPointerType())
2693 std::swap(PExp, IExp);
2694
2695 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2696 if (IExp->getType()->isIntegerType()) {
2697 // Check for arithmetic on pointers to incomplete types
2698 if (!PTy->getPointeeType()->isObjectType()) {
2699 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002700 if (getLangOptions().CPlusPlus) {
2701 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2702 << lex->getSourceRange() << rex->getSourceRange();
2703 return QualType();
2704 }
2705
2706 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002707 Diag(Loc, diag::ext_gnu_void_ptr)
2708 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002709 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002710 if (getLangOptions().CPlusPlus) {
2711 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2712 << lex->getType() << lex->getSourceRange();
2713 return QualType();
2714 }
2715
2716 // GNU extension: arithmetic on pointer to function
2717 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002718 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002719 } else {
2720 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2721 diag::err_typecheck_arithmetic_incomplete_type,
2722 lex->getSourceRange(), SourceRange(),
2723 lex->getType());
2724 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002725 }
2726 }
2727 return PExp->getType();
2728 }
2729 }
2730
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002732}
2733
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002734// C99 6.5.6
2735QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002736 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002737 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002738 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002739
Steve Naroff8f708362007-08-24 19:07:16 +00002740 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002741
Chris Lattnerf6da2912007-12-09 21:53:25 +00002742 // Enforce type constraints: C99 6.5.6p3.
2743
2744 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002745 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002746 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002747
2748 // Either ptr - int or ptr - ptr.
2749 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002750 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002751
Chris Lattnerf6da2912007-12-09 21:53:25 +00002752 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002753 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002754 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002755 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002756 Diag(Loc, diag::ext_gnu_void_ptr)
2757 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002758 } else if (lpointee->isFunctionType()) {
2759 if (getLangOptions().CPlusPlus) {
2760 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2761 << lex->getType() << lex->getSourceRange();
2762 return QualType();
2763 }
2764
2765 // GNU extension: arithmetic on pointer to function
2766 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2767 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002768 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002769 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002770 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002771 return QualType();
2772 }
2773 }
2774
2775 // The result type of a pointer-int computation is the pointer type.
2776 if (rex->getType()->isIntegerType())
2777 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002778
Chris Lattnerf6da2912007-12-09 21:53:25 +00002779 // Handle pointer-pointer subtractions.
2780 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002781 QualType rpointee = RHSPTy->getPointeeType();
2782
Chris Lattnerf6da2912007-12-09 21:53:25 +00002783 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002784 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002785 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002786 if (rpointee->isVoidType()) {
2787 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002788 Diag(Loc, diag::ext_gnu_void_ptr)
2789 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002790 } else if (rpointee->isFunctionType()) {
2791 if (getLangOptions().CPlusPlus) {
2792 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2793 << rex->getType() << rex->getSourceRange();
2794 return QualType();
2795 }
2796
2797 // GNU extension: arithmetic on pointer to function
2798 if (!lpointee->isFunctionType())
2799 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2800 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002801 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002802 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002803 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002804 return QualType();
2805 }
2806 }
2807
2808 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002809 if (!Context.typesAreCompatible(
2810 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2811 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002812 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002813 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002814 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002815 return QualType();
2816 }
2817
2818 return Context.getPointerDiffType();
2819 }
2820 }
2821
Chris Lattner1eafdea2008-11-18 01:30:42 +00002822 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002823}
2824
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002825// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002826QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002827 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002828 // C99 6.5.7p2: Each of the operands shall have integer type.
2829 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002830 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002831
Chris Lattner2c8bff72007-12-12 05:47:28 +00002832 // Shifts don't perform usual arithmetic conversions, they just do integer
2833 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002834 if (!isCompAssign)
2835 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002836 UsualUnaryConversions(rex);
2837
2838 // "The type of the result is that of the promoted left operand."
2839 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002840}
2841
Eli Friedman0d9549b2008-08-22 00:56:42 +00002842static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2843 ASTContext& Context) {
2844 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2845 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2846 // ID acts sort of like void* for ObjC interfaces
2847 if (LHSIface && Context.isObjCIdType(RHS))
2848 return true;
2849 if (RHSIface && Context.isObjCIdType(LHS))
2850 return true;
2851 if (!LHSIface || !RHSIface)
2852 return false;
2853 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2854 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2855}
2856
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002857// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002858QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002859 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002861 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002862
Chris Lattner254f3bc2007-08-26 01:18:55 +00002863 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002864 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2865 UsualArithmeticConversions(lex, rex);
2866 else {
2867 UsualUnaryConversions(lex);
2868 UsualUnaryConversions(rex);
2869 }
Chris Lattner4b009652007-07-25 00:24:17 +00002870 QualType lType = lex->getType();
2871 QualType rType = rex->getType();
2872
Ted Kremenek486509e2007-10-29 17:13:39 +00002873 // For non-floating point types, check for self-comparisons of the form
2874 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2875 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002876 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002877 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2878 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002879 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002880 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002881 }
2882
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002883 // The result of comparisons is 'bool' in C++, 'int' in C.
2884 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2885
Chris Lattner254f3bc2007-08-26 01:18:55 +00002886 if (isRelational) {
2887 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002888 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002889 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002890 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002891 if (lType->isFloatingType()) {
2892 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002893 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002894 }
2895
Chris Lattner254f3bc2007-08-26 01:18:55 +00002896 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002897 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002898 }
Chris Lattner4b009652007-07-25 00:24:17 +00002899
Chris Lattner22be8422007-08-26 01:10:14 +00002900 bool LHSIsNull = lex->isNullPointerConstant(Context);
2901 bool RHSIsNull = rex->isNullPointerConstant(Context);
2902
Chris Lattner254f3bc2007-08-26 01:18:55 +00002903 // All of the following pointer related warnings are GCC extensions, except
2904 // when handling null pointer constants. One day, we can consider making them
2905 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002906 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002907 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002908 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002909 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002910 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002911
Steve Naroff3b435622007-11-13 14:57:38 +00002912 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002913 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2914 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002915 RCanPointeeTy.getUnqualifiedType()) &&
2916 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002917 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002918 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002919 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002920 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002921 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002922 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002923 // Handle block pointer types.
2924 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2925 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2926 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2927
2928 if (!LHSIsNull && !RHSIsNull &&
2929 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002930 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002931 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002932 }
2933 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002934 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002935 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002936 // Allow block pointers to be compared with null pointer constants.
2937 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2938 (lType->isPointerType() && rType->isBlockPointerType())) {
2939 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002940 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002941 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002942 }
2943 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002944 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002945 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002946
Steve Naroff936c4362008-06-03 14:04:54 +00002947 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002948 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002949 const PointerType *LPT = lType->getAsPointerType();
2950 const PointerType *RPT = rType->getAsPointerType();
2951 bool LPtrToVoid = LPT ?
2952 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2953 bool RPtrToVoid = RPT ?
2954 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2955
2956 if (!LPtrToVoid && !RPtrToVoid &&
2957 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002958 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002959 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002960 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002961 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002962 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002963 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002964 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002965 }
Steve Naroff936c4362008-06-03 14:04:54 +00002966 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2967 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002968 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002969 } else {
2970 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002971 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002972 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002973 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002974 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002975 }
Steve Naroff936c4362008-06-03 14:04:54 +00002976 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002977 }
Steve Naroff936c4362008-06-03 14:04:54 +00002978 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2979 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002980 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002981 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002982 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002983 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002984 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002985 }
Steve Naroff936c4362008-06-03 14:04:54 +00002986 if (lType->isIntegerType() &&
2987 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002988 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002989 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002990 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002991 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002992 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002993 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002994 // Handle block pointers.
2995 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2996 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002997 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002998 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002999 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003000 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003001 }
3002 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3003 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003004 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003005 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003006 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003007 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003008 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003009 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003010}
3011
Nate Begemanc5f0f652008-07-14 18:02:46 +00003012/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3013/// operates on extended vector types. Instead of producing an IntTy result,
3014/// like a scalar comparison, a vector comparison produces a vector of integer
3015/// types.
3016QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003017 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003018 bool isRelational) {
3019 // Check to make sure we're operating on vectors of the same type and width,
3020 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003021 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003022 if (vType.isNull())
3023 return vType;
3024
3025 QualType lType = lex->getType();
3026 QualType rType = rex->getType();
3027
3028 // For non-floating point types, check for self-comparisons of the form
3029 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3030 // often indicate logic errors in the program.
3031 if (!lType->isFloatingType()) {
3032 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3033 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3034 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003035 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003036 }
3037
3038 // Check for comparisons of floating point operands using != and ==.
3039 if (!isRelational && lType->isFloatingType()) {
3040 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003041 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003042 }
3043
3044 // Return the type for the comparison, which is the same as vector type for
3045 // integer vectors, or an integer type of identical size and number of
3046 // elements for floating point vectors.
3047 if (lType->isIntegerType())
3048 return lType;
3049
3050 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003051 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003052 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003053 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003054 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3055 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3056
3057 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3058 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003059 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3060}
3061
Chris Lattner4b009652007-07-25 00:24:17 +00003062inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003063 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003064{
3065 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003067
Steve Naroff8f708362007-08-24 19:07:16 +00003068 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003069
3070 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003071 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003072 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003073}
3074
3075inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003076 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003077{
3078 UsualUnaryConversions(lex);
3079 UsualUnaryConversions(rex);
3080
Eli Friedmanbea3f842008-05-13 20:16:47 +00003081 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003082 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003083 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003084}
3085
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003086/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3087/// is a read-only property; return true if so. A readonly property expression
3088/// depends on various declarations and thus must be treated specially.
3089///
3090static bool IsReadonlyProperty(Expr *E, Sema &S)
3091{
3092 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3093 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3094 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3095 QualType BaseType = PropExpr->getBase()->getType();
3096 if (const PointerType *PTy = BaseType->getAsPointerType())
3097 if (const ObjCInterfaceType *IFTy =
3098 PTy->getPointeeType()->getAsObjCInterfaceType())
3099 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3100 if (S.isPropertyReadonly(PDecl, IFace))
3101 return true;
3102 }
3103 }
3104 return false;
3105}
3106
Chris Lattner4c2642c2008-11-18 01:22:49 +00003107/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3108/// emit an error and return true. If so, return false.
3109static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003110 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3111 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3112 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003113 if (IsLV == Expr::MLV_Valid)
3114 return false;
3115
3116 unsigned Diag = 0;
3117 bool NeedType = false;
3118 switch (IsLV) { // C99 6.5.16p2
3119 default: assert(0 && "Unknown result from isModifiableLvalue!");
3120 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003121 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003122 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3123 NeedType = true;
3124 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003125 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003126 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3127 NeedType = true;
3128 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003129 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003130 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3131 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003132 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003133 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3134 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003135 case Expr::MLV_IncompleteType:
3136 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003137 return S.DiagnoseIncompleteType(Loc, E->getType(),
3138 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3139 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003140 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003141 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3142 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003143 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003144 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3145 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003146 case Expr::MLV_ReadonlyProperty:
3147 Diag = diag::error_readonly_property_assignment;
3148 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003149 case Expr::MLV_NoSetterProperty:
3150 Diag = diag::error_nosetter_property_assignment;
3151 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003152 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003153
Chris Lattner4c2642c2008-11-18 01:22:49 +00003154 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003155 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003156 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003157 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003158 return true;
3159}
3160
3161
3162
3163// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003164QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3165 SourceLocation Loc,
3166 QualType CompoundType) {
3167 // Verify that LHS is a modifiable lvalue, and emit error if not.
3168 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003169 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003170
3171 QualType LHSType = LHS->getType();
3172 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003173
Chris Lattner005ed752008-01-04 18:04:52 +00003174 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003175 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003176 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003177 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003178 // Special case of NSObject attributes on c-style pointer types.
3179 if (ConvTy == IncompatiblePointer &&
3180 ((Context.isObjCNSObjectType(LHSType) &&
3181 Context.isObjCObjectPointerType(RHSType)) ||
3182 (Context.isObjCNSObjectType(RHSType) &&
3183 Context.isObjCObjectPointerType(LHSType))))
3184 ConvTy = Compatible;
3185
Chris Lattner34c85082008-08-21 18:04:13 +00003186 // If the RHS is a unary plus or minus, check to see if they = and + are
3187 // right next to each other. If so, the user may have typo'd "x =+ 4"
3188 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003189 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003190 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3191 RHSCheck = ICE->getSubExpr();
3192 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3193 if ((UO->getOpcode() == UnaryOperator::Plus ||
3194 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003195 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003196 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003197 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003198 Diag(Loc, diag::warn_not_compound_assign)
3199 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3200 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003201 }
3202 } else {
3203 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003204 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003205 }
Chris Lattner005ed752008-01-04 18:04:52 +00003206
Chris Lattner1eafdea2008-11-18 01:30:42 +00003207 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3208 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003209 return QualType();
3210
Chris Lattner4b009652007-07-25 00:24:17 +00003211 // C99 6.5.16p3: The type of an assignment expression is the type of the
3212 // left operand unless the left operand has qualified type, in which case
3213 // it is the unqualified version of the type of the left operand.
3214 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3215 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003216 // C++ 5.17p1: the type of the assignment expression is that of its left
3217 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003218 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003219}
3220
Chris Lattner1eafdea2008-11-18 01:30:42 +00003221// C99 6.5.17
3222QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3223 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003224
3225 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003226 DefaultFunctionArrayConversion(RHS);
3227 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003228}
3229
3230/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3231/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003232QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3233 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003234 QualType ResType = Op->getType();
3235 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003236
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003237 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3238 // Decrement of bool is not allowed.
3239 if (!isInc) {
3240 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3241 return QualType();
3242 }
3243 // Increment of bool sets it to true, but is deprecated.
3244 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3245 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003246 // OK!
3247 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3248 // C99 6.5.2.4p2, 6.5.6p2
3249 if (PT->getPointeeType()->isObjectType()) {
3250 // Pointer to object is ok!
3251 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003252 if (getLangOptions().CPlusPlus) {
3253 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3254 << Op->getSourceRange();
3255 return QualType();
3256 }
3257
3258 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003259 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003260 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003261 if (getLangOptions().CPlusPlus) {
3262 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3263 << Op->getType() << Op->getSourceRange();
3264 return QualType();
3265 }
3266
3267 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003268 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003269 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003270 } else {
3271 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3272 diag::err_typecheck_arithmetic_incomplete_type,
3273 Op->getSourceRange(), SourceRange(),
3274 ResType);
3275 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003276 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003277 } else if (ResType->isComplexType()) {
3278 // C99 does not support ++/-- on complex types, we allow as an extension.
3279 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003280 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003281 } else {
3282 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003283 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003284 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003285 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003286 // At this point, we know we have a real, complex or pointer type.
3287 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003288 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003289 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003290 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003291}
3292
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003293/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003294/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003295/// where the declaration is needed for type checking. We only need to
3296/// handle cases when the expression references a function designator
3297/// or is an lvalue. Here are some examples:
3298/// - &(x) => x
3299/// - &*****f => f for f a function designator.
3300/// - &s.xx => s
3301/// - &s.zz[1].yy -> s, if zz is an array
3302/// - *(x + 1) -> x, if x is an array
3303/// - &"123"[2] -> 0
3304/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003305static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003306 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003307 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003308 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003309 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003310 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003311 // Fields cannot be declared with a 'register' storage class.
3312 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003313 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003314 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003315 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003316 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003317 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003318
Douglas Gregord2baafd2008-10-21 16:13:35 +00003319 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003320 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003321 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003322 return 0;
3323 else
3324 return VD;
3325 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003326 case Stmt::UnaryOperatorClass: {
3327 UnaryOperator *UO = cast<UnaryOperator>(E);
3328
3329 switch(UO->getOpcode()) {
3330 case UnaryOperator::Deref: {
3331 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003332 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3333 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3334 if (!VD || VD->getType()->isPointerType())
3335 return 0;
3336 return VD;
3337 }
3338 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003339 }
3340 case UnaryOperator::Real:
3341 case UnaryOperator::Imag:
3342 case UnaryOperator::Extension:
3343 return getPrimaryDecl(UO->getSubExpr());
3344 default:
3345 return 0;
3346 }
3347 }
3348 case Stmt::BinaryOperatorClass: {
3349 BinaryOperator *BO = cast<BinaryOperator>(E);
3350
3351 // Handle cases involving pointer arithmetic. The result of an
3352 // Assign or AddAssign is not an lvalue so they can be ignored.
3353
3354 // (x + n) or (n + x) => x
3355 if (BO->getOpcode() == BinaryOperator::Add) {
3356 if (BO->getLHS()->getType()->isPointerType()) {
3357 return getPrimaryDecl(BO->getLHS());
3358 } else if (BO->getRHS()->getType()->isPointerType()) {
3359 return getPrimaryDecl(BO->getRHS());
3360 }
3361 }
3362
3363 return 0;
3364 }
Chris Lattner4b009652007-07-25 00:24:17 +00003365 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003366 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003367 case Stmt::ImplicitCastExprClass:
3368 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003369 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003370 default:
3371 return 0;
3372 }
3373}
3374
3375/// CheckAddressOfOperand - The operand of & must be either a function
3376/// designator or an lvalue designating an object. If it is an lvalue, the
3377/// object cannot be declared with storage class register or be a bit field.
3378/// Note: The usual conversions are *not* applied to the operand of the &
3379/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003380/// In C++, the operand might be an overloaded function name, in which case
3381/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003382QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003383 if (op->isTypeDependent())
3384 return Context.DependentTy;
3385
Steve Naroff9c6c3592008-01-13 17:10:08 +00003386 if (getLangOptions().C99) {
3387 // Implement C99-only parts of addressof rules.
3388 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3389 if (uOp->getOpcode() == UnaryOperator::Deref)
3390 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3391 // (assuming the deref expression is valid).
3392 return uOp->getSubExpr()->getType();
3393 }
3394 // Technically, there should be a check for array subscript
3395 // expressions here, but the result of one is always an lvalue anyway.
3396 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003397 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003398 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003399
Chris Lattner4b009652007-07-25 00:24:17 +00003400 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003401 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3402 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003403 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3404 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003405 return QualType();
3406 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003407 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003408 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3409 if (Field->isBitField()) {
3410 Diag(OpLoc, diag::err_typecheck_address_of)
3411 << "bit-field" << op->getSourceRange();
3412 return QualType();
3413 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003414 }
3415 // Check for Apple extension for accessing vector components.
3416 } else if (isa<ArraySubscriptExpr>(op) &&
3417 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003418 Diag(OpLoc, diag::err_typecheck_address_of)
3419 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003420 return QualType();
3421 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003422 // We have an lvalue with a decl. Make sure the decl is not declared
3423 // with the register storage-class specifier.
3424 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3425 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003426 Diag(OpLoc, diag::err_typecheck_address_of)
3427 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003428 return QualType();
3429 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003430 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003431 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003432 } else if (isa<FieldDecl>(dcl)) {
3433 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003434 } else if (isa<FunctionDecl>(dcl)) {
3435 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003436 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003437 else
Chris Lattner4b009652007-07-25 00:24:17 +00003438 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003439 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003440
Chris Lattner4b009652007-07-25 00:24:17 +00003441 // If the operand has type "type", the result has type "pointer to type".
3442 return Context.getPointerType(op->getType());
3443}
3444
Chris Lattnerda5c0872008-11-23 09:13:29 +00003445QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3446 UsualUnaryConversions(Op);
3447 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003448
Chris Lattnerda5c0872008-11-23 09:13:29 +00003449 // Note that per both C89 and C99, this is always legal, even if ptype is an
3450 // incomplete type or void. It would be possible to warn about dereferencing
3451 // a void pointer, but it's completely well-defined, and such a warning is
3452 // unlikely to catch any mistakes.
3453 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003454 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003455
Chris Lattner77d52da2008-11-20 06:06:08 +00003456 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003457 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003458 return QualType();
3459}
3460
3461static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3462 tok::TokenKind Kind) {
3463 BinaryOperator::Opcode Opc;
3464 switch (Kind) {
3465 default: assert(0 && "Unknown binop!");
3466 case tok::star: Opc = BinaryOperator::Mul; break;
3467 case tok::slash: Opc = BinaryOperator::Div; break;
3468 case tok::percent: Opc = BinaryOperator::Rem; break;
3469 case tok::plus: Opc = BinaryOperator::Add; break;
3470 case tok::minus: Opc = BinaryOperator::Sub; break;
3471 case tok::lessless: Opc = BinaryOperator::Shl; break;
3472 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3473 case tok::lessequal: Opc = BinaryOperator::LE; break;
3474 case tok::less: Opc = BinaryOperator::LT; break;
3475 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3476 case tok::greater: Opc = BinaryOperator::GT; break;
3477 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3478 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3479 case tok::amp: Opc = BinaryOperator::And; break;
3480 case tok::caret: Opc = BinaryOperator::Xor; break;
3481 case tok::pipe: Opc = BinaryOperator::Or; break;
3482 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3483 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3484 case tok::equal: Opc = BinaryOperator::Assign; break;
3485 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3486 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3487 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3488 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3489 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3490 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3491 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3492 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3493 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3494 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3495 case tok::comma: Opc = BinaryOperator::Comma; break;
3496 }
3497 return Opc;
3498}
3499
3500static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3501 tok::TokenKind Kind) {
3502 UnaryOperator::Opcode Opc;
3503 switch (Kind) {
3504 default: assert(0 && "Unknown unary op!");
3505 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3506 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3507 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3508 case tok::star: Opc = UnaryOperator::Deref; break;
3509 case tok::plus: Opc = UnaryOperator::Plus; break;
3510 case tok::minus: Opc = UnaryOperator::Minus; break;
3511 case tok::tilde: Opc = UnaryOperator::Not; break;
3512 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003513 case tok::kw___real: Opc = UnaryOperator::Real; break;
3514 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3515 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3516 }
3517 return Opc;
3518}
3519
Douglas Gregord7f915e2008-11-06 23:29:22 +00003520/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3521/// operator @p Opc at location @c TokLoc. This routine only supports
3522/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003523Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3524 unsigned Op,
3525 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003526 QualType ResultTy; // Result type of the binary operator.
3527 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3528 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3529
3530 switch (Opc) {
3531 default:
3532 assert(0 && "Unknown binary expr!");
3533 case BinaryOperator::Assign:
3534 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3535 break;
3536 case BinaryOperator::Mul:
3537 case BinaryOperator::Div:
3538 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3539 break;
3540 case BinaryOperator::Rem:
3541 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3542 break;
3543 case BinaryOperator::Add:
3544 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3545 break;
3546 case BinaryOperator::Sub:
3547 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3548 break;
3549 case BinaryOperator::Shl:
3550 case BinaryOperator::Shr:
3551 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3552 break;
3553 case BinaryOperator::LE:
3554 case BinaryOperator::LT:
3555 case BinaryOperator::GE:
3556 case BinaryOperator::GT:
3557 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3558 break;
3559 case BinaryOperator::EQ:
3560 case BinaryOperator::NE:
3561 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3562 break;
3563 case BinaryOperator::And:
3564 case BinaryOperator::Xor:
3565 case BinaryOperator::Or:
3566 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3567 break;
3568 case BinaryOperator::LAnd:
3569 case BinaryOperator::LOr:
3570 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3571 break;
3572 case BinaryOperator::MulAssign:
3573 case BinaryOperator::DivAssign:
3574 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3575 if (!CompTy.isNull())
3576 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3577 break;
3578 case BinaryOperator::RemAssign:
3579 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3580 if (!CompTy.isNull())
3581 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3582 break;
3583 case BinaryOperator::AddAssign:
3584 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3585 if (!CompTy.isNull())
3586 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3587 break;
3588 case BinaryOperator::SubAssign:
3589 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3590 if (!CompTy.isNull())
3591 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3592 break;
3593 case BinaryOperator::ShlAssign:
3594 case BinaryOperator::ShrAssign:
3595 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3596 if (!CompTy.isNull())
3597 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3598 break;
3599 case BinaryOperator::AndAssign:
3600 case BinaryOperator::XorAssign:
3601 case BinaryOperator::OrAssign:
3602 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3603 if (!CompTy.isNull())
3604 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3605 break;
3606 case BinaryOperator::Comma:
3607 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3608 break;
3609 }
3610 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003611 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003612 if (CompTy.isNull())
3613 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3614 else
3615 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003616 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003617}
3618
Chris Lattner4b009652007-07-25 00:24:17 +00003619// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003620Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3621 tok::TokenKind Kind,
3622 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003623 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003624 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003625
Steve Naroff87d58b42007-09-16 03:34:24 +00003626 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3627 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003628
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003629 // If either expression is type-dependent, just build the AST.
3630 // FIXME: We'll need to perform some caching of the result of name
3631 // lookup for operator+.
3632 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003633 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3634 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003635 Context.DependentTy,
3636 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003637 else
3638 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3639 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003640 }
3641
Douglas Gregord7f915e2008-11-06 23:29:22 +00003642 if (getLangOptions().CPlusPlus &&
3643 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3644 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003645 // If this is one of the assignment operators, we only perform
3646 // overload resolution if the left-hand side is a class or
3647 // enumeration type (C++ [expr.ass]p3).
3648 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3649 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3650 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3651 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003652
Douglas Gregord7f915e2008-11-06 23:29:22 +00003653 // Determine which overloaded operator we're dealing with.
3654 static const OverloadedOperatorKind OverOps[] = {
3655 OO_Star, OO_Slash, OO_Percent,
3656 OO_Plus, OO_Minus,
3657 OO_LessLess, OO_GreaterGreater,
3658 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3659 OO_EqualEqual, OO_ExclaimEqual,
3660 OO_Amp,
3661 OO_Caret,
3662 OO_Pipe,
3663 OO_AmpAmp,
3664 OO_PipePipe,
3665 OO_Equal, OO_StarEqual,
3666 OO_SlashEqual, OO_PercentEqual,
3667 OO_PlusEqual, OO_MinusEqual,
3668 OO_LessLessEqual, OO_GreaterGreaterEqual,
3669 OO_AmpEqual, OO_CaretEqual,
3670 OO_PipeEqual,
3671 OO_Comma
3672 };
3673 OverloadedOperatorKind OverOp = OverOps[Opc];
3674
Douglas Gregor5ed15042008-11-18 23:14:02 +00003675 // Add the appropriate overloaded operators (C++ [over.match.oper])
3676 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003677 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003678 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003679 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003680
3681 // Perform overload resolution.
3682 OverloadCandidateSet::iterator Best;
3683 switch (BestViableFunction(CandidateSet, Best)) {
3684 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003685 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003686 FunctionDecl *FnDecl = Best->Function;
3687
Douglas Gregor70d26122008-11-12 17:17:38 +00003688 if (FnDecl) {
3689 // We matched an overloaded operator. Build a call to that
3690 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003691
Douglas Gregor70d26122008-11-12 17:17:38 +00003692 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3694 if (PerformObjectArgumentInitialization(lhs, Method) ||
3695 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3696 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003697 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003698 } else {
3699 // Convert the arguments.
3700 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3701 "passing") ||
3702 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3703 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003704 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003705 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003706
Douglas Gregor70d26122008-11-12 17:17:38 +00003707 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003708 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003709 = FnDecl->getType()->getAsFunctionType()->getResultType();
3710 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003711
Douglas Gregor70d26122008-11-12 17:17:38 +00003712 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003713 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3714 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003715 UsualUnaryConversions(FnExpr);
3716
Steve Naroff774e4152009-01-21 00:14:39 +00003717 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3718 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003719 } else {
3720 // We matched a built-in operator. Convert the arguments, then
3721 // break out so that we will build the appropriate built-in
3722 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003723 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3724 Best->Conversions[0], "passing") ||
3725 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3726 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003727 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003728
3729 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003730 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003731 }
3732
3733 case OR_No_Viable_Function:
3734 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003735 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003736 break;
3737
3738 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003739 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3740 << BinaryOperator::getOpcodeStr(Opc)
3741 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003742 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003743 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003744 }
3745
Douglas Gregor70d26122008-11-12 17:17:38 +00003746 // Either we found no viable overloaded operator or we matched a
3747 // built-in operator. In either case, fall through to trying to
3748 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003749 }
3750
Douglas Gregord7f915e2008-11-06 23:29:22 +00003751 // Build a built-in binary operation.
3752 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003753}
3754
3755// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003756Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3757 tok::TokenKind Op, ExprArg input) {
3758 // FIXME: Input is modified later, but smart pointer not reassigned.
3759 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003760 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003761
3762 if (getLangOptions().CPlusPlus &&
3763 (Input->getType()->isRecordType()
3764 || Input->getType()->isEnumeralType())) {
3765 // Determine which overloaded operator we're dealing with.
3766 static const OverloadedOperatorKind OverOps[] = {
3767 OO_None, OO_None,
3768 OO_PlusPlus, OO_MinusMinus,
3769 OO_Amp, OO_Star,
3770 OO_Plus, OO_Minus,
3771 OO_Tilde, OO_Exclaim,
3772 OO_None, OO_None,
3773 OO_None,
3774 OO_None
3775 };
3776 OverloadedOperatorKind OverOp = OverOps[Opc];
3777
3778 // Add the appropriate overloaded operators (C++ [over.match.oper])
3779 // to the candidate set.
3780 OverloadCandidateSet CandidateSet;
3781 if (OverOp != OO_None)
3782 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3783
3784 // Perform overload resolution.
3785 OverloadCandidateSet::iterator Best;
3786 switch (BestViableFunction(CandidateSet, Best)) {
3787 case OR_Success: {
3788 // We found a built-in operator or an overloaded operator.
3789 FunctionDecl *FnDecl = Best->Function;
3790
3791 if (FnDecl) {
3792 // We matched an overloaded operator. Build a call to that
3793 // operator.
3794
3795 // Convert the arguments.
3796 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3797 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003798 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003799 } else {
3800 // Convert the arguments.
3801 if (PerformCopyInitialization(Input,
3802 FnDecl->getParamDecl(0)->getType(),
3803 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003804 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003805 }
3806
3807 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003808 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003809 = FnDecl->getType()->getAsFunctionType()->getResultType();
3810 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003811
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003812 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003813 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3814 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003815 UsualUnaryConversions(FnExpr);
3816
Sebastian Redl8b769972009-01-19 00:08:26 +00003817 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003818 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3819 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003820 } else {
3821 // We matched a built-in operator. Convert the arguments, then
3822 // break out so that we will build the appropriate built-in
3823 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003824 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3825 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003826 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003827
3828 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003829 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003830 }
3831
3832 case OR_No_Viable_Function:
3833 // No viable function; fall through to handling this as a
3834 // built-in operator, which will produce an error message for us.
3835 break;
3836
3837 case OR_Ambiguous:
3838 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3839 << UnaryOperator::getOpcodeStr(Opc)
3840 << Input->getSourceRange();
3841 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003842 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003843 }
3844
3845 // Either we found no viable overloaded operator or we matched a
3846 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003847 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003848 }
3849
Chris Lattner4b009652007-07-25 00:24:17 +00003850 QualType resultType;
3851 switch (Opc) {
3852 default:
3853 assert(0 && "Unimplemented unary expr!");
3854 case UnaryOperator::PreInc:
3855 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003856 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3857 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003858 break;
3859 case UnaryOperator::AddrOf:
3860 resultType = CheckAddressOfOperand(Input, OpLoc);
3861 break;
3862 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003863 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003864 resultType = CheckIndirectionOperand(Input, OpLoc);
3865 break;
3866 case UnaryOperator::Plus:
3867 case UnaryOperator::Minus:
3868 UsualUnaryConversions(Input);
3869 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003870 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3871 break;
3872 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3873 resultType->isEnumeralType())
3874 break;
3875 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3876 Opc == UnaryOperator::Plus &&
3877 resultType->isPointerType())
3878 break;
3879
Sebastian Redl8b769972009-01-19 00:08:26 +00003880 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3881 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003882 case UnaryOperator::Not: // bitwise complement
3883 UsualUnaryConversions(Input);
3884 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003885 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3886 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3887 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003888 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003889 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003890 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3892 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003893 break;
3894 case UnaryOperator::LNot: // logical negation
3895 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3896 DefaultFunctionArrayConversion(Input);
3897 resultType = Input->getType();
3898 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003899 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3900 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003901 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003902 // In C++, it's bool. C++ 5.3.1p8
3903 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003904 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003905 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003906 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003907 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003908 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003909 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003910 resultType = Input->getType();
3911 break;
3912 }
3913 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003914 return ExprError();
3915 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003916 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003917}
3918
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003919/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3920Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003921 SourceLocation LabLoc,
3922 IdentifierInfo *LabelII) {
3923 // Look up the record for this label identifier.
3924 LabelStmt *&LabelDecl = LabelMap[LabelII];
3925
Daniel Dunbar879788d2008-08-04 16:51:22 +00003926 // If we haven't seen this label yet, create a forward reference. It
3927 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003928 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00003929 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00003930
3931 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00003932 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3933 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003934}
3935
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003936Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003937 SourceLocation RPLoc) { // "({..})"
3938 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3939 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3940 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3941
Eli Friedmanbc941e12009-01-24 23:09:00 +00003942 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3943 if (isFileScope) {
3944 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
3945 }
3946
Chris Lattner4b009652007-07-25 00:24:17 +00003947 // FIXME: there are a variety of strange constraints to enforce here, for
3948 // example, it is not possible to goto into a stmt expression apparently.
3949 // More semantic analysis is needed.
3950
3951 // FIXME: the last statement in the compount stmt has its value used. We
3952 // should not warn about it being unused.
3953
3954 // If there are sub stmts in the compound stmt, take the type of the last one
3955 // as the type of the stmtexpr.
3956 QualType Ty = Context.VoidTy;
3957
Chris Lattner200964f2008-07-26 19:51:01 +00003958 if (!Compound->body_empty()) {
3959 Stmt *LastStmt = Compound->body_back();
3960 // If LastStmt is a label, skip down through into the body.
3961 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3962 LastStmt = Label->getSubStmt();
3963
3964 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003965 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003966 }
Chris Lattner4b009652007-07-25 00:24:17 +00003967
Steve Naroff774e4152009-01-21 00:14:39 +00003968 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00003969}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003970
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003971Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3972 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003973 SourceLocation TypeLoc,
3974 TypeTy *argty,
3975 OffsetOfComponent *CompPtr,
3976 unsigned NumComponents,
3977 SourceLocation RPLoc) {
3978 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3979 assert(!ArgTy.isNull() && "Missing type argument!");
3980
3981 // We must have at least one component that refers to the type, and the first
3982 // one is known to be a field designator. Verify that the ArgTy represents
3983 // a struct/union/class.
3984 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003985 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003986
3987 // Otherwise, create a compound literal expression as the base, and
3988 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00003989 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00003990 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00003991 IList->setType(ArgTy);
3992 Expr *Res =
3993 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
3994
Chris Lattnerb37522e2007-08-31 21:49:13 +00003995 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3996 // GCC extension, diagnose them.
3997 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003998 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3999 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004000
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004001 for (unsigned i = 0; i != NumComponents; ++i) {
4002 const OffsetOfComponent &OC = CompPtr[i];
4003 if (OC.isBrackets) {
4004 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004005 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004006 if (!AT) {
4007 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004008 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004009 }
4010
Chris Lattner2af6a802007-08-30 17:59:59 +00004011 // FIXME: C++: Verify that operator[] isn't overloaded.
4012
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004013 // C99 6.5.2.1p1
4014 Expr *Idx = static_cast<Expr*>(OC.U.E);
4015 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004016 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4017 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004018
Steve Naroff774e4152009-01-21 00:14:39 +00004019 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4020 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004021 continue;
4022 }
4023
4024 const RecordType *RC = Res->getType()->getAsRecordType();
4025 if (!RC) {
4026 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004027 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004028 }
4029
4030 // Get the decl corresponding to this.
4031 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004032 FieldDecl *MemberDecl
Steve Naroffc349ee22009-01-29 00:07:50 +00004033 = dyn_cast_or_null<FieldDecl>(LookupDeclInContext(OC.U.IdentInfo,
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004034 Decl::IDNS_Ordinary,
Steve Naroffc349ee22009-01-29 00:07:50 +00004035 RD, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004036 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004037 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4038 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004039
4040 // FIXME: C++: Verify that MemberDecl isn't a static field.
4041 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004042 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4043 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004044 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4045 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004046 }
4047
Steve Naroff774e4152009-01-21 00:14:39 +00004048 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4049 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004050}
4051
4052
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004053Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004054 TypeTy *arg1, TypeTy *arg2,
4055 SourceLocation RPLoc) {
4056 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4057 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4058
4059 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4060
Steve Naroff774e4152009-01-21 00:14:39 +00004061 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4062 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004063}
4064
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004065Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004066 ExprTy *expr1, ExprTy *expr2,
4067 SourceLocation RPLoc) {
4068 Expr *CondExpr = static_cast<Expr*>(cond);
4069 Expr *LHSExpr = static_cast<Expr*>(expr1);
4070 Expr *RHSExpr = static_cast<Expr*>(expr2);
4071
4072 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4073
4074 // The conditional expression is required to be a constant expression.
4075 llvm::APSInt condEval(32);
4076 SourceLocation ExpLoc;
4077 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004078 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4079 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004080
4081 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4082 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4083 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004084 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4085 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004086}
4087
Steve Naroff52a81c02008-09-03 18:15:37 +00004088//===----------------------------------------------------------------------===//
4089// Clang Extensions.
4090//===----------------------------------------------------------------------===//
4091
4092/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004093void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004094 // Analyze block parameters.
4095 BlockSemaInfo *BSI = new BlockSemaInfo();
4096
4097 // Add BSI to CurBlock.
4098 BSI->PrevBlockInfo = CurBlock;
4099 CurBlock = BSI;
4100
4101 BSI->ReturnType = 0;
4102 BSI->TheScope = BlockScope;
4103
Steve Naroff52059382008-10-10 01:28:17 +00004104 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004105 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004106}
4107
4108void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004109 // Analyze arguments to block.
4110 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4111 "Not a function declarator!");
4112 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4113
Steve Naroff52059382008-10-10 01:28:17 +00004114 CurBlock->hasPrototype = FTI.hasPrototype;
4115 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004116
4117 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4118 // no arguments, not a function that takes a single void argument.
4119 if (FTI.hasPrototype &&
4120 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4121 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4122 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4123 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004124 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004125 } else if (FTI.hasPrototype) {
4126 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004127 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4128 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004129 }
Steve Naroff52059382008-10-10 01:28:17 +00004130 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4131
4132 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4133 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4134 // If this has an identifier, add it to the scope stack.
4135 if ((*AI)->getIdentifier())
4136 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004137}
4138
4139/// ActOnBlockError - If there is an error parsing a block, this callback
4140/// is invoked to pop the information about the block from the action impl.
4141void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4142 // Ensure that CurBlock is deleted.
4143 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4144
4145 // Pop off CurBlock, handle nested blocks.
4146 CurBlock = CurBlock->PrevBlockInfo;
4147
4148 // FIXME: Delete the ParmVarDecl objects as well???
4149
4150}
4151
4152/// ActOnBlockStmtExpr - This is called when the body of a block statement
4153/// literal was successfully completed. ^(int x){...}
4154Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4155 Scope *CurScope) {
4156 // Ensure that CurBlock is deleted.
4157 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4158 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4159
Steve Naroff52059382008-10-10 01:28:17 +00004160 PopDeclContext();
4161
Steve Naroff52a81c02008-09-03 18:15:37 +00004162 // Pop off CurBlock, handle nested blocks.
4163 CurBlock = CurBlock->PrevBlockInfo;
4164
4165 QualType RetTy = Context.VoidTy;
4166 if (BSI->ReturnType)
4167 RetTy = QualType(BSI->ReturnType, 0);
4168
4169 llvm::SmallVector<QualType, 8> ArgTypes;
4170 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4171 ArgTypes.push_back(BSI->Params[i]->getType());
4172
4173 QualType BlockTy;
4174 if (!BSI->hasPrototype)
4175 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4176 else
4177 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004178 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004179
4180 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004181
Steve Naroff95029d92008-10-08 18:44:00 +00004182 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004183 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004184}
4185
Nate Begemanbd881ef2008-01-30 20:50:20 +00004186/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004187/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004188/// The number of arguments has already been validated to match the number of
4189/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004190static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4191 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004192 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004193 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004194 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4195 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004196
4197 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004198 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004199 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004200 return true;
4201}
4202
4203Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4204 SourceLocation *CommaLocs,
4205 SourceLocation BuiltinLoc,
4206 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004207 // __builtin_overload requires at least 2 arguments
4208 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004209 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4210 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004211
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004212 // The first argument is required to be a constant expression. It tells us
4213 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004214 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004215 Expr *NParamsExpr = Args[0];
4216 llvm::APSInt constEval(32);
4217 SourceLocation ExpLoc;
4218 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004219 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4220 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004221
4222 // Verify that the number of parameters is > 0
4223 unsigned NumParams = constEval.getZExtValue();
4224 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004225 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4226 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004227 // Verify that we have at least 1 + NumParams arguments to the builtin.
4228 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004229 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4230 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004231
4232 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004233 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004234 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004235 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4236 // UsualUnaryConversions will convert the function DeclRefExpr into a
4237 // pointer to function.
4238 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004239 const FunctionTypeProto *FnType = 0;
4240 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4241 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004242
4243 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4244 // parameters, and the number of parameters must match the value passed to
4245 // the builtin.
4246 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004247 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4248 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004249
4250 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004251 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004252 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004253 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004254 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004255 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4256 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004257 // Remember our match, and continue processing the remaining arguments
4258 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004259 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004260 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004261 BuiltinLoc, RParenLoc);
4262 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004263 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004264 // Return the newly created OverloadExpr node, if we succeded in matching
4265 // exactly one of the candidate functions.
4266 if (OE)
4267 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004268
4269 // If we didn't find a matching function Expr in the __builtin_overload list
4270 // the return an error.
4271 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004272 for (unsigned i = 0; i != NumParams; ++i) {
4273 if (i != 0) typeNames += ", ";
4274 typeNames += Args[i+1]->getType().getAsString();
4275 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004276
Chris Lattner77d52da2008-11-20 06:06:08 +00004277 return Diag(BuiltinLoc, diag::err_overload_no_match)
4278 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004279}
4280
Anders Carlsson36760332007-10-15 20:28:48 +00004281Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4282 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004283 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004284 Expr *E = static_cast<Expr*>(expr);
4285 QualType T = QualType::getFromOpaquePtr(type);
4286
4287 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004288
4289 // Get the va_list type
4290 QualType VaListType = Context.getBuiltinVaListType();
4291 // Deal with implicit array decay; for example, on x86-64,
4292 // va_list is an array, but it's supposed to decay to
4293 // a pointer for va_arg.
4294 if (VaListType->isArrayType())
4295 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004296 // Make sure the input expression also decays appropriately.
4297 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004298
4299 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004300 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004301 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004302 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004303
4304 // FIXME: Warn if a non-POD type is passed in.
4305
Steve Naroff774e4152009-01-21 00:14:39 +00004306 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004307}
4308
Douglas Gregorad4b3792008-11-29 04:51:27 +00004309Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4310 // The type of __null will be int or long, depending on the size of
4311 // pointers on the target.
4312 QualType Ty;
4313 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4314 Ty = Context.IntTy;
4315 else
4316 Ty = Context.LongTy;
4317
Steve Naroff774e4152009-01-21 00:14:39 +00004318 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004319}
4320
Chris Lattner005ed752008-01-04 18:04:52 +00004321bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4322 SourceLocation Loc,
4323 QualType DstType, QualType SrcType,
4324 Expr *SrcExpr, const char *Flavor) {
4325 // Decode the result (notice that AST's are still created for extensions).
4326 bool isInvalid = false;
4327 unsigned DiagKind;
4328 switch (ConvTy) {
4329 default: assert(0 && "Unknown conversion type");
4330 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004331 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004332 DiagKind = diag::ext_typecheck_convert_pointer_int;
4333 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004334 case IntToPointer:
4335 DiagKind = diag::ext_typecheck_convert_int_pointer;
4336 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004337 case IncompatiblePointer:
4338 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4339 break;
4340 case FunctionVoidPointer:
4341 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4342 break;
4343 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004344 // If the qualifiers lost were because we were applying the
4345 // (deprecated) C++ conversion from a string literal to a char*
4346 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4347 // Ideally, this check would be performed in
4348 // CheckPointerTypesForAssignment. However, that would require a
4349 // bit of refactoring (so that the second argument is an
4350 // expression, rather than a type), which should be done as part
4351 // of a larger effort to fix CheckPointerTypesForAssignment for
4352 // C++ semantics.
4353 if (getLangOptions().CPlusPlus &&
4354 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4355 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004356 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4357 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004358 case IntToBlockPointer:
4359 DiagKind = diag::err_int_to_block_pointer;
4360 break;
4361 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004362 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004363 break;
Steve Naroff19608432008-10-14 22:18:38 +00004364 case IncompatibleObjCQualifiedId:
4365 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4366 // it can give a more specific diagnostic.
4367 DiagKind = diag::warn_incompatible_qualified_id;
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}