blob: 652397939c0f15f7ac18be0ca23d592f0d9800ed [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000090// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
91// will warn if the resulting type is not a POD type.
92void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
93
94{
95 DefaultArgumentPromotion(Expr);
96
97 if (!Expr->getType()->isPODType()) {
98 Diag(Expr->getLocStart(),
99 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
100 Expr->getType() << CT;
101 }
102}
103
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105/// UsualArithmeticConversions - Performs various conversions that are common to
106/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
107/// routine returns the first non-arithmetic type found. The client is
108/// responsible for emitting appropriate error diagnostics.
109/// FIXME: verify the conversion rules for "complex int" are consistent with
110/// GCC.
111QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
112 bool isCompAssign) {
113 if (!isCompAssign) {
114 UsualUnaryConversions(lhsExpr);
115 UsualUnaryConversions(rhsExpr);
116 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000117
Chris Lattner299b8842008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000124
125 // If both types are identical, no conversion is needed.
126 if (lhs == rhs)
127 return lhs;
128
129 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
130 // The caller can deal with this (e.g. pointer + int).
131 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
132 return lhs;
133
134 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
135 if (!isCompAssign) {
136 ImpCastExprToType(lhsExpr, destType);
137 ImpCastExprToType(rhsExpr, destType);
138 }
139 return destType;
140}
141
142QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
143 // Perform the usual unary conversions. We do this early so that
144 // integral promotions to "int" can allow us to exit early, in the
145 // lhs == rhs check. Also, for conversion purposes, we ignore any
146 // qualifiers. For example, "const float" and "float" are
147 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000148 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
149 else lhs = lhs.getUnqualifiedType();
150 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
151 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000152
Chris Lattner299b8842008-07-25 21:10:04 +0000153 // If both types are identical, no conversion is needed.
154 if (lhs == rhs)
155 return lhs;
156
157 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
158 // The caller can deal with this (e.g. pointer + int).
159 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
160 return lhs;
161
162 // At this point, we have two different arithmetic types.
163
164 // Handle complex types first (C99 6.3.1.8p1).
165 if (lhs->isComplexType() || rhs->isComplexType()) {
166 // if we have an integer operand, the result is the complex type.
167 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
168 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000169 return lhs;
170 }
171 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
172 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000173 return rhs;
174 }
175 // This handles complex/complex, complex/float, or float/complex.
176 // When both operands are complex, the shorter operand is converted to the
177 // type of the longer, and that is the type of the result. This corresponds
178 // to what is done when combining two real floating-point operands.
179 // The fun begins when size promotion occur across type domains.
180 // From H&S 6.3.4: When one operand is complex and the other is a real
181 // floating-point type, the less precise type is converted, within it's
182 // real or complex domain, to the precision of the other type. For example,
183 // when combining a "long double" with a "double _Complex", the
184 // "double _Complex" is promoted to "long double _Complex".
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // The left side is bigger, convert rhs.
188 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000191 }
192 // At this point, lhs and rhs have the same rank/size. Now, make sure the
193 // domains match. This is a requirement for our implementation, C99
194 // does not require this promotion.
195 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
196 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 }
202 return lhs; // The domain/size match exactly.
203 }
204 // Now handle "real" floating types (i.e. float, double, long double).
205 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
206 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000211 if (rhs->isComplexIntegerType()) {
212 // convert rhs to the complex floating point type.
213 return Context.getComplexType(lhs);
214 }
215 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000219 if (lhs->isComplexIntegerType()) {
220 // convert lhs to the complex floating point type.
221 return Context.getComplexType(rhs);
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 // We have two real floating types, float/complex combos were handled above.
224 // Convert the smaller operand to the bigger result.
225 int result = Context.getFloatingTypeOrder(lhs, rhs);
226
227 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000234 }
235 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
236 // Handle GCC complex int extension.
237 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
238 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
239
240 if (lhsComplexInt && rhsComplexInt) {
241 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
242 rhsComplexInt->getElementType()) >= 0) {
243 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return rhs;
253 }
254 }
255 // Finally, we have two differing integer types.
256 // The rules for this case are in C99 6.3.1.8
257 int compare = Context.getIntegerTypeOrder(lhs, rhs);
258 bool lhsSigned = lhs->isSignedIntegerType(),
259 rhsSigned = rhs->isSignedIntegerType();
260 QualType destType;
261 if (lhsSigned == rhsSigned) {
262 // Same signedness; use the higher-ranked type
263 destType = compare >= 0 ? lhs : rhs;
264 } else if (compare != (lhsSigned ? 1 : -1)) {
265 // The unsigned type has greater than or equal rank to the
266 // signed type, so use the unsigned type
267 destType = lhsSigned ? rhs : lhs;
268 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
269 // The two types are different widths; if we are here, that
270 // means the signed type is larger than the unsigned type, so
271 // use the signed type.
272 destType = lhsSigned ? lhs : rhs;
273 } else {
274 // The signed type is higher-ranked than the unsigned type,
275 // but isn't actually any bigger (like unsigned int and long
276 // on most 32-bit systems). Use the unsigned type corresponding
277 // to the signed type.
278 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
279 }
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000289/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
290/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
291/// multiple tokens. However, the common case is that StringToks points to one
292/// string.
293///
294Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000299 if (Literal.hadError)
300 return ExprResult(true);
301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000309
310 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
311 if (getLangOptions().CPlusPlus)
312 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000313
314 // Get an array type for the string, according to C99 6.4.5. This includes
315 // the nul terminator character as well as the string length for pascal
316 // strings.
317 StrTy = Context.getConstantArrayType(StrTy,
318 llvm::APInt(32, Literal.GetStringLength()+1),
319 ArrayType::Normal, 0);
320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
322 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000323 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000324 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000325 StringToks[NumStringToks-1].getLocation());
326}
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.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000361/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
362/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000363Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000364 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000365 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) {
376 if (SS && !SS->isEmpty())
377 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
378 SS->getRange().getBegin());
379 else
380 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
381}
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.
386static ScopedDecl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
387 assert(Record->isAnonymousStructOrUnion() &&
388 "Record must be an anonymous struct or union!");
389
390 // FIXME: Once ScopedDecls are directly linked together, this will
391 // 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");
403 assert(!cast<ScopedDecl>(*D)->getDeclName() && "Decl should be unnamed");
404 return *D;
405 }
406 }
407
408 assert(false && "Missing object for anonymous record");
409 return 0;
410}
411
412Sema::ExprResult
413Sema::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);
432 ScopedDecl *AnonObject = getObjectForAnonymousRecordDecl(Record);
433 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
454 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
455 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".
482 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
483 MD->getThisType(Context));
484 BaseObjectIsPointer = true;
485 }
486 } else {
487 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
488 << Field->getDeclName();
489 }
490 ExtraQuals = MD->getTypeQualifiers();
491 }
492
493 if (!BaseObjectExpr)
494 return Diag(Loc, diag::err_invalid_non_static_member_use)
495 << Field->getDeclName();
496 }
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 }
510 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
511 OpLoc, MemberType);
512 BaseObjectIsPointer = false;
513 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
514 OpLoc = SourceLocation();
515 }
516
517 return Result;
518}
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.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000538Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
539 DeclarationName Name,
540 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000541 const CXXScopeSpec *SS,
542 bool ForceResolution) {
543 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
544 HasTrailingLParen && !SS && !ForceResolution) {
545 // We've seen something of the form
546 // identifier(
547 // and we are in a template, so it is likely that 's' is a
548 // dependent name. However, we won't know until we've parsed all
549 // of the call arguments. So, build a CXXDependentNameExpr node
550 // to represent this name. Then, if it turns out that none of the
551 // arguments are type-dependent, we'll force the resolution of the
552 // dependent name at that point.
553 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
554 Context.DependentTy, Loc);
555 }
556
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000557 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000558 Decl *D = 0;
559 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000560 if (SS && !SS->isEmpty()) {
561 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
562 if (DC == 0)
563 return true;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000564 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000565 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000566 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
567
568 if (Lookup.isAmbiguous())
569 return DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet()? SS->getRange()
571 : SourceRange());
572 else
573 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()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000579 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000585 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
591 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000592 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
593 static_cast<Expr*>(SelfExpr.Val), true, true);
594 Context.setFieldDecl(IFace, IV, MRef);
595 return 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.
Chris Lattner87fada82008-11-20 05:35:30 +0000599 if (SD == 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()));
Douglas Gregord8606632008-11-04 14:56:14 +0000602 return new 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())
Chris Lattner77d52da2008-11-20 06:06:08 +0000615 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000616 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000617 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
618 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000619 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000620 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000621 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000622 }
623 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000624
625 // We may have found a field within an anonymous union or struct
626 // (C++ [class.union]).
627 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
628 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
629 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000630
Douglas Gregor3257fb52008-12-22 05:46:06 +0000631 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
632 if (!MD->isStatic()) {
633 // C++ [class.mfct.nonstatic]p2:
634 // [...] if name lookup (3.4.1) resolves the name in the
635 // id-expression to a nonstatic nontype member of class X or of
636 // a base class of X, the id-expression is transformed into a
637 // class member access expression (5.2.5) using (*this) (9.3.2)
638 // as the postfix-expression to the left of the '.' operator.
639 DeclContext *Ctx = 0;
640 QualType MemberType;
641 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
642 Ctx = FD->getDeclContext();
643 MemberType = FD->getType();
644
645 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
646 MemberType = RefType->getPointeeType();
647 else if (!FD->isMutable()) {
648 unsigned combinedQualifiers
649 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
650 MemberType = MemberType.getQualifiedType(combinedQualifiers);
651 }
652 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
653 if (!Method->isStatic()) {
654 Ctx = Method->getParent();
655 MemberType = Method->getType();
656 }
657 } else if (OverloadedFunctionDecl *Ovl
658 = dyn_cast<OverloadedFunctionDecl>(D)) {
659 for (OverloadedFunctionDecl::function_iterator
660 Func = Ovl->function_begin(),
661 FuncEnd = Ovl->function_end();
662 Func != FuncEnd; ++Func) {
663 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
664 if (!DMethod->isStatic()) {
665 Ctx = Ovl->getDeclContext();
666 MemberType = Context.OverloadTy;
667 break;
668 }
669 }
670 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000671
672 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000673 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
674 QualType ThisType = Context.getTagDeclType(MD->getParent());
675 if ((Context.getCanonicalType(CtxType)
676 == Context.getCanonicalType(ThisType)) ||
677 IsDerivedFrom(ThisType, CtxType)) {
678 // Build the implicit member access expression.
679 Expr *This = new CXXThisExpr(SourceLocation(),
680 MD->getThisType(Context));
681 return new MemberExpr(This, true, cast<NamedDecl>(D),
682 SourceLocation(), MemberType);
683 }
684 }
685 }
686 }
687
Douglas Gregor8acb7272008-12-11 16:49:14 +0000688 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
690 if (MD->isStatic())
691 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000692 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000693 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000694 }
695
Douglas Gregor3257fb52008-12-22 05:46:06 +0000696 // Any other ways we could have found the field in a well-formed
697 // program would have been turned into implicit member expressions
698 // above.
Chris Lattner271d4c22008-11-24 05:29:24 +0000699 return Diag(Loc, diag::err_invalid_non_static_member_use)
700 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000701 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000702
Chris Lattner4b009652007-07-25 00:24:17 +0000703 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000704 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000706 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000707 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000708 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000709
Steve Naroffd6163f32008-09-05 22:11:13 +0000710 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000711 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor566782a2009-01-06 05:10:23 +0000712 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000713
Steve Naroffd6163f32008-09-05 22:11:13 +0000714 ValueDecl *VD = cast<ValueDecl>(D);
715
716 // check if referencing an identifier with __attribute__((deprecated)).
717 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000718 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000719
720 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
721 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
722 Scope *CheckS = S;
723 while (CheckS) {
724 if (CheckS->isWithinElse() &&
725 CheckS->getControlParent()->isDeclScope(Var)) {
726 if (Var->getType()->isBooleanType())
727 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
728 else
729 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
730 break;
731 }
732
733 // Move up one more control parent to check again.
734 CheckS = CheckS->getControlParent();
735 if (CheckS)
736 CheckS = CheckS->getParent();
737 }
738 }
739 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000740
741 // Only create DeclRefExpr's for valid Decl's.
742 if (VD->isInvalidDecl())
743 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000744
745 // If the identifier reference is inside a block, and it refers to a value
746 // that is outside the block, create a BlockDeclRefExpr instead of a
747 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
748 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000749 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000750 // We do not do this for things like enum constants, global variables, etc,
751 // as they do not get snapshotted.
752 //
753 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000754 // The BlocksAttr indicates the variable is bound by-reference.
755 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000756 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
757 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000758
759 // Variable will be bound by-copy, make it const within the closure.
760 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000761 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
762 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000763 }
764 // If this reference is not in a block or if the referenced variable is
765 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000766
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000767 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000768 bool ValueDependent = false;
769 if (getLangOptions().CPlusPlus) {
770 // C++ [temp.dep.expr]p3:
771 // An id-expression is type-dependent if it contains:
772 // - an identifier that was declared with a dependent type,
773 if (VD->getType()->isDependentType())
774 TypeDependent = true;
775 // - FIXME: a template-id that is dependent,
776 // - a conversion-function-id that specifies a dependent type,
777 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
778 Name.getCXXNameType()->isDependentType())
779 TypeDependent = true;
780 // - a nested-name-specifier that contains a class-name that
781 // names a dependent type.
782 else if (SS && !SS->isEmpty()) {
783 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
784 DC; DC = DC->getParent()) {
785 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000786 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000787 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
788 if (Context.getTypeDeclType(Record)->isDependentType()) {
789 TypeDependent = true;
790 break;
791 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000792 }
793 }
794 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000795
Douglas Gregora5d84612008-12-10 20:57:37 +0000796 // C++ [temp.dep.constexpr]p2:
797 //
798 // An identifier is value-dependent if it is:
799 // - a name declared with a dependent type,
800 if (TypeDependent)
801 ValueDependent = true;
802 // - the name of a non-type template parameter,
803 else if (isa<NonTypeTemplateParmDecl>(VD))
804 ValueDependent = true;
805 // - a constant with integral or enumeration type and is
806 // initialized with an expression that is value-dependent
807 // (FIXME!).
808 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000809
Douglas Gregor566782a2009-01-06 05:10:23 +0000810 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
811 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +0000812}
813
Chris Lattner69909292008-08-10 01:53:14 +0000814Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000815 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000816 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000817
818 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000819 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000820 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
821 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
822 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000823 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000824
Chris Lattner7e637512008-01-12 08:14:25 +0000825 // Pre-defined identifiers are of type char[x], where x is the length of the
826 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000827 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000828 if (FunctionDecl *FD = getCurFunctionDecl())
829 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000830 else if (ObjCMethodDecl *MD = getCurMethodDecl())
831 Length = MD->getSynthesizedMethodSize();
832 else {
833 Diag(Loc, diag::ext_predef_outside_function);
834 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
835 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
836 }
837
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000838
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000839 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000840 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000841 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000842 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000843}
844
Steve Naroff87d58b42007-09-16 03:34:24 +0000845Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000846 llvm::SmallString<16> CharBuffer;
847 CharBuffer.resize(Tok.getLength());
848 const char *ThisTokBegin = &CharBuffer[0];
849 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
850
851 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
852 Tok.getLocation(), PP);
853 if (Literal.hadError())
854 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000855
856 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
857
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000858 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
859 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000860}
861
Steve Naroff87d58b42007-09-16 03:34:24 +0000862Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000863 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000864 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
865 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000866 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
867 unsigned IntSize = Context.Target.getIntWidth();
868 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000869 Context.IntTy,
870 Tok.getLocation()));
871 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000872
Chris Lattner4b009652007-07-25 00:24:17 +0000873 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000874 // Add padding so that NumericLiteralParser can overread by one character.
875 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000876 const char *ThisTokBegin = &IntegerBuffer[0];
877
878 // Get the spelling of the token, which eliminates trigraphs, etc.
879 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000880
Chris Lattner4b009652007-07-25 00:24:17 +0000881 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
882 Tok.getLocation(), PP);
883 if (Literal.hadError)
884 return ExprResult(true);
885
Chris Lattner1de66eb2007-08-26 03:42:43 +0000886 Expr *Res;
887
888 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000889 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000890 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000891 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000892 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000893 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000894 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000895 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000896
897 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
898
Ted Kremenekddedbe22007-11-29 00:56:49 +0000899 // isExact will be set by GetFloatValue().
900 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000901 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000902 Ty, Tok.getLocation());
903
Chris Lattner1de66eb2007-08-26 03:42:43 +0000904 } else if (!Literal.isIntegerLiteral()) {
905 return ExprResult(true);
906 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000907 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000908
Neil Booth7421e9c2007-08-29 22:00:19 +0000909 // long long is a C99 feature.
910 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000911 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000912 Diag(Tok.getLocation(), diag::ext_longlong);
913
Chris Lattner4b009652007-07-25 00:24:17 +0000914 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000915 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000916
917 if (Literal.GetIntegerValue(ResultVal)) {
918 // If this value didn't fit into uintmax_t, warn and force to ull.
919 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000920 Ty = Context.UnsignedLongLongTy;
921 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000922 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000923 } else {
924 // If this value fits into a ULL, try to figure out what else it fits into
925 // according to the rules of C99 6.4.4.1p5.
926
927 // Octal, Hexadecimal, and integers with a U suffix are allowed to
928 // be an unsigned int.
929 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
930
931 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000932 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000933 if (!Literal.isLong && !Literal.isLongLong) {
934 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000935 unsigned IntSize = Context.Target.getIntWidth();
936
Chris Lattner4b009652007-07-25 00:24:17 +0000937 // Does it fit in a unsigned int?
938 if (ResultVal.isIntN(IntSize)) {
939 // Does it fit in a signed int?
940 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000941 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000942 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000943 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000944 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000945 }
Chris Lattner4b009652007-07-25 00:24:17 +0000946 }
947
948 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000949 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000950 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000951
952 // Does it fit in a unsigned long?
953 if (ResultVal.isIntN(LongSize)) {
954 // Does it fit in a signed long?
955 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000956 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000957 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000958 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000959 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000960 }
Chris Lattner4b009652007-07-25 00:24:17 +0000961 }
962
963 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000964 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000965 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000966
967 // Does it fit in a unsigned long long?
968 if (ResultVal.isIntN(LongLongSize)) {
969 // Does it fit in a signed long long?
970 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000971 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000972 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000973 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000974 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000975 }
976 }
977
978 // If we still couldn't decide a type, we probably have something that
979 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000980 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000981 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000982 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000983 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
Chris Lattnere4068872008-05-09 05:59:00 +0000985
986 if (ResultVal.getBitWidth() != Width)
987 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
989
Chris Lattner48d7f382008-04-02 04:24:33 +0000990 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000991 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000992
993 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
994 if (Literal.isImaginary)
995 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
996
997 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000998}
999
Steve Naroff87d58b42007-09-16 03:34:24 +00001000Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +00001001 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +00001002 Expr *E = (Expr *)Val;
1003 assert((E != 0) && "ActOnParenExpr() missing expr");
1004 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +00001005}
1006
1007/// The UsualUnaryConversions() function is *not* called by this routine.
1008/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001009bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1010 SourceLocation OpLoc,
1011 const SourceRange &ExprRange,
1012 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001013 // C99 6.5.3.4p1:
1014 if (isa<FunctionType>(exprType) && isSizeof)
1015 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001016 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001017 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001018 Diag(OpLoc, diag::ext_sizeof_void_type)
1019 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1020 else if (exprType->isIncompleteType())
1021 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1022 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001023 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001024
1025 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001026}
1027
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001028/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1029/// the same for @c alignof and @c __alignof
1030/// Note that the ArgRange is invalid if isType is false.
1031Action::ExprResult
1032Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1033 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001035 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001036
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001037 QualType ArgTy;
1038 SourceRange Range;
1039 if (isType) {
1040 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1041 Range = ArgRange;
1042 } else {
1043 // Get the end location.
1044 Expr *ArgEx = (Expr *)TyOrEx;
1045 Range = ArgEx->getSourceRange();
1046 ArgTy = ArgEx->getType();
1047 }
1048
1049 // Verify that the operand is valid.
1050 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +00001051 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001052
1053 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1054 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1055 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +00001056}
1057
Chris Lattner5110ad52007-08-24 21:41:10 +00001058QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001059 DefaultFunctionArrayConversion(V);
1060
Chris Lattnera16e42d2007-08-26 05:39:26 +00001061 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001062 if (const ComplexType *CT = V->getType()->getAsComplexType())
1063 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001064
1065 // Otherwise they pass through real integer and floating point types here.
1066 if (V->getType()->isArithmeticType())
1067 return V->getType();
1068
1069 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001070 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001071 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001072}
1073
1074
Chris Lattner4b009652007-07-25 00:24:17 +00001075
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001076Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001077 tok::TokenKind Kind,
1078 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001079 Expr *Arg = (Expr *)Input;
1080
Chris Lattner4b009652007-07-25 00:24:17 +00001081 UnaryOperator::Opcode Opc;
1082 switch (Kind) {
1083 default: assert(0 && "Unknown unary op!");
1084 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1085 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1086 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001087
1088 if (getLangOptions().CPlusPlus &&
1089 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1090 // Which overloaded operator?
1091 OverloadedOperatorKind OverOp =
1092 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1093
1094 // C++ [over.inc]p1:
1095 //
1096 // [...] If the function is a member function with one
1097 // parameter (which shall be of type int) or a non-member
1098 // function with two parameters (the second of which shall be
1099 // of type int), it defines the postfix increment operator ++
1100 // for objects of that type. When the postfix increment is
1101 // called as a result of using the ++ operator, the int
1102 // argument will have value zero.
1103 Expr *Args[2] = {
1104 Arg,
1105 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1106 /*isSigned=*/true),
1107 Context.IntTy, SourceLocation())
1108 };
1109
1110 // Build the candidate set for overloading
1111 OverloadCandidateSet CandidateSet;
1112 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1113
1114 // Perform overload resolution.
1115 OverloadCandidateSet::iterator Best;
1116 switch (BestViableFunction(CandidateSet, Best)) {
1117 case OR_Success: {
1118 // We found a built-in operator or an overloaded operator.
1119 FunctionDecl *FnDecl = Best->Function;
1120
1121 if (FnDecl) {
1122 // We matched an overloaded operator. Build a call to that
1123 // operator.
1124
1125 // Convert the arguments.
1126 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1127 if (PerformObjectArgumentInitialization(Arg, Method))
1128 return true;
1129 } else {
1130 // Convert the arguments.
1131 if (PerformCopyInitialization(Arg,
1132 FnDecl->getParamDecl(0)->getType(),
1133 "passing"))
1134 return true;
1135 }
1136
1137 // Determine the result type
1138 QualType ResultTy
1139 = FnDecl->getType()->getAsFunctionType()->getResultType();
1140 ResultTy = ResultTy.getNonReferenceType();
1141
1142 // Build the actual expression node.
1143 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1144 SourceLocation());
1145 UsualUnaryConversions(FnExpr);
1146
1147 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1148 } else {
1149 // We matched a built-in operator. Convert the arguments, then
1150 // break out so that we will build the appropriate built-in
1151 // operator node.
1152 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1153 "passing"))
1154 return true;
1155
1156 break;
1157 }
1158 }
1159
1160 case OR_No_Viable_Function:
1161 // No viable function; fall through to handling this as a
1162 // built-in operator, which will produce an error message for us.
1163 break;
1164
1165 case OR_Ambiguous:
1166 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1167 << UnaryOperator::getOpcodeStr(Opc)
1168 << Arg->getSourceRange();
1169 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1170 return true;
1171 }
1172
1173 // Either we found no viable overloaded operator or we matched a
1174 // built-in operator. In either case, fall through to trying to
1175 // build a built-in operation.
1176 }
1177
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001178 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1179 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001180 if (result.isNull())
1181 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001182 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001183}
1184
1185Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001186ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001187 ExprTy *Idx, SourceLocation RLoc) {
1188 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1189
Douglas Gregor80723c52008-11-19 17:17:41 +00001190 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001191 (LHSExp->getType()->isRecordType() ||
1192 LHSExp->getType()->isEnumeralType() ||
1193 RHSExp->getType()->isRecordType() ||
1194 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001195 // Add the appropriate overloaded operators (C++ [over.match.oper])
1196 // to the candidate set.
1197 OverloadCandidateSet CandidateSet;
1198 Expr *Args[2] = { LHSExp, RHSExp };
1199 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1200
1201 // Perform overload resolution.
1202 OverloadCandidateSet::iterator Best;
1203 switch (BestViableFunction(CandidateSet, Best)) {
1204 case OR_Success: {
1205 // We found a built-in operator or an overloaded operator.
1206 FunctionDecl *FnDecl = Best->Function;
1207
1208 if (FnDecl) {
1209 // We matched an overloaded operator. Build a call to that
1210 // operator.
1211
1212 // Convert the arguments.
1213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1214 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1215 PerformCopyInitialization(RHSExp,
1216 FnDecl->getParamDecl(0)->getType(),
1217 "passing"))
1218 return true;
1219 } else {
1220 // Convert the arguments.
1221 if (PerformCopyInitialization(LHSExp,
1222 FnDecl->getParamDecl(0)->getType(),
1223 "passing") ||
1224 PerformCopyInitialization(RHSExp,
1225 FnDecl->getParamDecl(1)->getType(),
1226 "passing"))
1227 return true;
1228 }
1229
1230 // Determine the result type
1231 QualType ResultTy
1232 = FnDecl->getType()->getAsFunctionType()->getResultType();
1233 ResultTy = ResultTy.getNonReferenceType();
1234
1235 // Build the actual expression node.
1236 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1237 SourceLocation());
1238 UsualUnaryConversions(FnExpr);
1239
1240 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1241 } else {
1242 // We matched a built-in operator. Convert the arguments, then
1243 // break out so that we will build the appropriate built-in
1244 // operator node.
1245 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1246 "passing") ||
1247 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1248 "passing"))
1249 return true;
1250
1251 break;
1252 }
1253 }
1254
1255 case OR_No_Viable_Function:
1256 // No viable function; fall through to handling this as a
1257 // built-in operator, which will produce an error message for us.
1258 break;
1259
1260 case OR_Ambiguous:
1261 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1262 << "[]"
1263 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1264 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1265 return true;
1266 }
1267
1268 // Either we found no viable overloaded operator or we matched a
1269 // built-in operator. In either case, fall through to trying to
1270 // build a built-in operation.
1271 }
1272
Chris Lattner4b009652007-07-25 00:24:17 +00001273 // Perform default conversions.
1274 DefaultFunctionArrayConversion(LHSExp);
1275 DefaultFunctionArrayConversion(RHSExp);
1276
1277 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1278
1279 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001280 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001281 // in the subscript position. As a result, we need to derive the array base
1282 // and index from the expression types.
1283 Expr *BaseExpr, *IndexExpr;
1284 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001285 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001286 BaseExpr = LHSExp;
1287 IndexExpr = RHSExp;
1288 // FIXME: need to deal with const...
1289 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001290 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // Handle the uncommon case of "123[Ptr]".
1292 BaseExpr = RHSExp;
1293 IndexExpr = LHSExp;
1294 // FIXME: need to deal with const...
1295 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001296 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1297 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001298 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001299
1300 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001301 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1302 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001303 return Diag(LLoc, diag::err_ext_vector_component_access)
1304 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // FIXME: need to deal with const...
1306 ResultType = VTy->getElementType();
1307 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001308 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1309 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
1311 // C99 6.5.2.1p1
1312 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001313 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1314 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001315
1316 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1317 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001318 // void (*)(int)) and pointers to incomplete types. Functions are not
1319 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001320 if (!ResultType->isObjectType())
1321 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001322 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001323 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001324
1325 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1326}
1327
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001328QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001329CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001330 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001331 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001332
1333 // This flag determines whether or not the component is to be treated as a
1334 // special name, or a regular GLSL-style component access.
1335 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001336
1337 // The vector accessor can't exceed the number of elements.
1338 const char *compStr = CompName.getName();
1339 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001340 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001341 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001342 return QualType();
1343 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001344
1345 // Check that we've found one of the special components, or that the component
1346 // names must come from the same set.
1347 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1348 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1349 SpecialComponent = true;
1350 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001351 do
1352 compStr++;
1353 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1354 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1355 do
1356 compStr++;
1357 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1358 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1359 do
1360 compStr++;
1361 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1362 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001363
Nate Begemanc8e51f82008-05-09 06:41:27 +00001364 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001365 // We didn't get to the end of the string. This means the component names
1366 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001367 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1368 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001369 return QualType();
1370 }
1371 // Each component accessor can't exceed the vector type.
1372 compStr = CompName.getName();
1373 while (*compStr) {
1374 if (vecType->isAccessorWithinNumElements(*compStr))
1375 compStr++;
1376 else
1377 break;
1378 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001379 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001380 // We didn't get to the end of the string. This means a component accessor
1381 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001382 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001383 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001384 return QualType();
1385 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001386
1387 // If we have a special component name, verify that the current vector length
1388 // is an even number, since all special component names return exactly half
1389 // the elements.
1390 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001391 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001392 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001393 return QualType();
1394 }
1395
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001396 // The component accessor looks fine - now we need to compute the actual type.
1397 // The vector type is implied by the component accessor. For example,
1398 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001399 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1400 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001401 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001402 if (CompSize == 1)
1403 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001404
Nate Begemanaf6ed502008-04-18 23:10:10 +00001405 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001406 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001407 // diagostics look bad. We want extended vector types to appear built-in.
1408 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1409 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1410 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001411 }
1412 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001413}
1414
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001415/// constructSetterName - Return the setter name for the given
1416/// identifier, i.e. "set" + Name where the initial character of Name
1417/// has been capitalized.
1418// FIXME: Merge with same routine in Parser. But where should this
1419// live?
1420static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1421 const IdentifierInfo *Name) {
1422 llvm::SmallString<100> SelectorName;
1423 SelectorName = "set";
1424 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1425 SelectorName[3] = toupper(SelectorName[3]);
1426 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1427}
1428
Chris Lattner4b009652007-07-25 00:24:17 +00001429Action::ExprResult Sema::
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001430ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001431 tok::TokenKind OpKind, SourceLocation MemberLoc,
1432 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001433 Expr *BaseExpr = static_cast<Expr *>(Base);
1434 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001435
1436 // Perform default conversions.
1437 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001438
Steve Naroff2cb66382007-07-26 03:11:44 +00001439 QualType BaseType = BaseExpr->getType();
1440 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001441
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001442 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1443 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001444 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001445 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001446 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001447 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001448 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001449 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001450 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001451 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001452 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001453
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001454 // Handle field access to simple records. This also handles access to fields
1455 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001456 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001457 RecordDecl *RDecl = RTy->getDecl();
1458 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001459 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001460 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001461 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001462 // FIXME: Qualified name lookup for C++ is a bit more complicated
1463 // than this.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001464 LookupResult Result
1465 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1466 LookupCriteria(LookupCriteria::Member,
1467 /*RedeclarationOnly=*/false,
1468 getLangOptions().CPlusPlus));
1469
1470 Decl *MemberDecl = 0;
1471 if (!Result)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001472 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001473 << &Member << BaseExpr->getSourceRange();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001474 else if (Result.isAmbiguous())
1475 return DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1476 MemberLoc, BaseExpr->getSourceRange());
1477 else
1478 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001479
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001480 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001481 // We may have found a field within an anonymous union or struct
1482 // (C++ [class.union]).
1483 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1484 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1485 BaseExpr, OpLoc);
1486
Douglas Gregor82d44772008-12-20 23:49:58 +00001487 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1488 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001489 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001490 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1491 MemberType = Ref->getPointeeType();
1492 else {
1493 unsigned combinedQualifiers =
1494 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001495 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001496 combinedQualifiers &= ~QualType::Const;
1497 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1498 }
Eli Friedman76b49832008-02-06 22:48:16 +00001499
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001500 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001501 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001502 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001503 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1504 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001505 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001506 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1507 MemberFn->getType());
1508 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001509 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001510 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1511 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001512 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001513 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1514 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001515 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001516 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1517 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001518
Douglas Gregor82d44772008-12-20 23:49:58 +00001519 // We found a declaration kind that we didn't expect. This is a
1520 // generic error message that tells the user that she can't refer
1521 // to this member with '.' or '->'.
1522 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1523 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001524 }
1525
Chris Lattnere9d71612008-07-21 04:59:05 +00001526 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1527 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001528 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001529 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001530 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1531 BaseExpr,
1532 OpKind == tok::arrow);
1533 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1534 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001535 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001536 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001537 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001538 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001539 }
1540
Chris Lattnere9d71612008-07-21 04:59:05 +00001541 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1542 // pointer to a (potentially qualified) interface type.
1543 const PointerType *PTy;
1544 const ObjCInterfaceType *IFTy;
1545 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1546 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1547 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001548
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001549 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001550 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1551 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1552
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001553 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001554 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1555 E = IFTy->qual_end(); I != E; ++I)
1556 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1557 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001558
1559 // If that failed, look for an "implicit" property by seeing if the nullary
1560 // selector is implemented.
1561
1562 // FIXME: The logic for looking up nullary and unary selectors should be
1563 // shared with the code in ActOnInstanceMessage.
1564
1565 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1566 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1567
1568 // If this reference is in an @implementation, check for 'private' methods.
1569 if (!Getter)
1570 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1571 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1572 if (ObjCImplementationDecl *ImpDecl =
1573 ObjCImplementations[ClassDecl->getIdentifier()])
1574 Getter = ImpDecl->getInstanceMethod(Sel);
1575
Steve Naroff04151f32008-10-22 19:16:27 +00001576 // Look through local category implementations associated with the class.
1577 if (!Getter) {
1578 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1579 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1580 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1581 }
1582 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001583 if (Getter) {
1584 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001585 // will look for the matching setter, in case it is needed.
1586 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1587 &Member);
1588 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1589 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1590 if (!Setter) {
1591 // If this reference is in an @implementation, also check for 'private'
1592 // methods.
1593 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1594 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1595 if (ObjCImplementationDecl *ImpDecl =
1596 ObjCImplementations[ClassDecl->getIdentifier()])
1597 Setter = ImpDecl->getInstanceMethod(SetterSel);
1598 }
1599 // Look through local category implementations associated with the class.
1600 if (!Setter) {
1601 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1602 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1603 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1604 }
1605 }
1606
1607 // FIXME: we must check that the setter has property type.
1608 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001609 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001610 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001611
1612 return Diag(MemberLoc, diag::err_property_not_found) <<
1613 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001614 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001615 // Handle properties on qualified "id" protocols.
1616 const ObjCQualifiedIdType *QIdTy;
1617 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1618 // Check protocols on qualified interfaces.
1619 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001620 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001621 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1622 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001623 // Also must look for a getter name which uses property syntax.
1624 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1625 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1626 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1627 OpLoc, MemberLoc, NULL, 0);
1628 }
1629 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001630
1631 return Diag(MemberLoc, diag::err_property_not_found) <<
1632 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001633 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001634 // Handle 'field access' to vectors, such as 'V.xx'.
1635 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1636 // Component access limited to variables (reject vec4.rg.g).
1637 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1638 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001639 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1640 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001641 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1642 if (ret.isNull())
1643 return true;
1644 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1645 }
1646
Chris Lattner8ba580c2008-11-19 05:08:23 +00001647 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001648 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001649}
1650
Douglas Gregor3257fb52008-12-22 05:46:06 +00001651/// ConvertArgumentsForCall - Converts the arguments specified in
1652/// Args/NumArgs to the parameter types of the function FDecl with
1653/// function prototype Proto. Call is the call expression itself, and
1654/// Fn is the function expression. For a C++ member function, this
1655/// routine does not attempt to convert the object argument. Returns
1656/// true if the call is ill-formed.
1657bool
1658Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1659 FunctionDecl *FDecl,
1660 const FunctionTypeProto *Proto,
1661 Expr **Args, unsigned NumArgs,
1662 SourceLocation RParenLoc) {
1663 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1664 // assignment, to the types of the corresponding parameter, ...
1665 unsigned NumArgsInProto = Proto->getNumArgs();
1666 unsigned NumArgsToCheck = NumArgs;
1667
1668 // If too few arguments are available (and we don't have default
1669 // arguments for the remaining parameters), don't make the call.
1670 if (NumArgs < NumArgsInProto) {
1671 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1672 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1673 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1674 // Use default arguments for missing arguments
1675 NumArgsToCheck = NumArgsInProto;
1676 Call->setNumArgs(NumArgsInProto);
1677 }
1678
1679 // If too many are passed and not variadic, error on the extras and drop
1680 // them.
1681 if (NumArgs > NumArgsInProto) {
1682 if (!Proto->isVariadic()) {
1683 Diag(Args[NumArgsInProto]->getLocStart(),
1684 diag::err_typecheck_call_too_many_args)
1685 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1686 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1687 Args[NumArgs-1]->getLocEnd());
1688 // This deletes the extra arguments.
1689 Call->setNumArgs(NumArgsInProto);
1690 }
1691 NumArgsToCheck = NumArgsInProto;
1692 }
1693
1694 // Continue to check argument types (even if we have too few/many args).
1695 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1696 QualType ProtoArgType = Proto->getArgType(i);
1697
1698 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001699 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001700 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001701
1702 // Pass the argument.
1703 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1704 return true;
1705 } else
1706 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001707 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1708 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001709
Douglas Gregor3257fb52008-12-22 05:46:06 +00001710 Call->setArg(i, Arg);
1711 }
1712
1713 // If this is a variadic call, handle args passed through "...".
1714 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001715 VariadicCallType CallType = VariadicFunction;
1716 if (Fn->getType()->isBlockPointerType())
1717 CallType = VariadicBlock; // Block
1718 else if (isa<MemberExpr>(Fn))
1719 CallType = VariadicMethod;
1720
Douglas Gregor3257fb52008-12-22 05:46:06 +00001721 // Promote the arguments (C99 6.5.2.2p7).
1722 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1723 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001724 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001725 Call->setArg(i, Arg);
1726 }
1727 }
1728
1729 return false;
1730}
1731
Steve Naroff87d58b42007-09-16 03:34:24 +00001732/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001733/// This provides the location of the left/right parens and a list of comma
1734/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001735Action::ExprResult
1736Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1737 ExprTy **args, unsigned NumArgs,
1738 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001739 Expr *Fn = static_cast<Expr *>(fn);
1740 Expr **Args = reinterpret_cast<Expr**>(args);
1741 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001742 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001743 OverloadedFunctionDecl *Ovl = NULL;
1744
Douglas Gregora133e262008-12-06 00:22:45 +00001745 // Determine whether this is a dependent call inside a C++ template,
1746 // in which case we won't do any semantic analysis now.
1747 bool Dependent = false;
1748 if (Fn->isTypeDependent()) {
1749 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1750 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1751 Dependent = true;
1752 else {
1753 // Resolve the CXXDependentNameExpr to an actual identifier;
1754 // it wasn't really a dependent name after all.
1755 ExprResult Resolved
1756 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1757 /*HasTrailingLParen=*/true,
1758 /*SS=*/0,
1759 /*ForceResolution=*/true);
1760 if (Resolved.isInvalid)
1761 return true;
1762 else {
1763 delete Fn;
1764 Fn = (Expr *)Resolved.Val;
1765 }
1766 }
1767 } else
1768 Dependent = true;
1769 } else
1770 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1771
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001772 // FIXME: Will need to cache the results of name lookup (including
1773 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001774 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001775 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1776
Douglas Gregor3257fb52008-12-22 05:46:06 +00001777 // Determine whether this is a call to an object (C++ [over.call.object]).
1778 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1779 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1780 CommaLocs, RParenLoc);
1781
1782 // Determine whether this is a call to a member function.
1783 if (getLangOptions().CPlusPlus) {
1784 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1785 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1786 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1787 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1788 CommaLocs, RParenLoc);
1789 }
1790
Douglas Gregord2baafd2008-10-21 16:13:35 +00001791 // If we're directly calling a function or a set of overloaded
1792 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001793 DeclRefExpr *DRExpr = NULL;
1794 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1795 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1796 else
1797 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1798
1799 if (DRExpr) {
1800 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1801 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001802 }
1803
Douglas Gregord2baafd2008-10-21 16:13:35 +00001804 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001805 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1806 RParenLoc);
1807 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001808 return true;
1809
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001810 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001811 Expr *NewFn = 0;
1812 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1813 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1814 QDRExpr->getLocation(), false, false,
1815 QDRExpr->getSourceRange().getBegin());
1816 else
1817 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1818 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001819 Fn->Destroy(Context);
1820 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001821 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001822
1823 // Promote the function operand.
1824 UsualUnaryConversions(Fn);
1825
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001826 // Make the call expr early, before semantic checks. This guarantees cleanup
1827 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001828 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001829 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001830
Steve Naroffd6163f32008-09-05 22:11:13 +00001831 const FunctionType *FuncT;
1832 if (!Fn->getType()->isBlockPointerType()) {
1833 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1834 // have type pointer to function".
1835 const PointerType *PT = Fn->getType()->getAsPointerType();
1836 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001837 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001838 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001839 FuncT = PT->getPointeeType()->getAsFunctionType();
1840 } else { // This is a block call.
1841 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1842 getAsFunctionType();
1843 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001844 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001845 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001846 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001847
1848 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001849 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001850
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001851 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001852 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1853 RParenLoc))
1854 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001855 } else {
1856 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1857
Steve Naroffdb65e052007-08-28 23:30:39 +00001858 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001859 for (unsigned i = 0; i != NumArgs; i++) {
1860 Expr *Arg = Args[i];
1861 DefaultArgumentPromotion(Arg);
1862 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001863 }
Chris Lattner4b009652007-07-25 00:24:17 +00001864 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001865
Douglas Gregor3257fb52008-12-22 05:46:06 +00001866 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1867 if (!Method->isStatic())
1868 return Diag(LParenLoc, diag::err_member_call_without_object)
1869 << Fn->getSourceRange();
1870
Chris Lattner2e64c072007-08-10 20:18:51 +00001871 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001872 if (FDecl)
1873 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001874
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001875 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001876}
1877
1878Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001879ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001880 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001881 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001882 QualType literalType = QualType::getFromOpaquePtr(Ty);
1883 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001884 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001885 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001886
Eli Friedman8c2173d2008-05-20 05:22:08 +00001887 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001888 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001889 return Diag(LParenLoc, diag::err_variable_object_no_init)
1890 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001891 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001892 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001893 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001894 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001895 }
1896
Douglas Gregor6428e762008-11-05 15:29:30 +00001897 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001898 DeclarationName(), /*FIXME:DirectInit=*/false))
Steve Naroff92590f92008-01-09 20:58:06 +00001899 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001900
Chris Lattnere5cb5862008-12-04 23:50:19 +00001901 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001902 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001903 if (CheckForConstantInitializer(literalExpr, literalType))
1904 return true;
1905 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001906 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1907 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001908}
1909
1910Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001911ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001912 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001913 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001914 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001915
Steve Naroff0acc9c92007-09-15 18:49:24 +00001916 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001917 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001918
Chris Lattner71ca8c82008-10-26 23:43:26 +00001919 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1920 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001921 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1922 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001923}
1924
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001925/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001926bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001927 UsualUnaryConversions(castExpr);
1928
1929 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1930 // type needs to be scalar.
1931 if (castType->isVoidType()) {
1932 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001933 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1934 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001935 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001936 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1937 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1938 (castType->isStructureType() || castType->isUnionType())) {
1939 // GCC struct/union extension: allow cast to self.
1940 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1941 << castType << castExpr->getSourceRange();
1942 } else if (castType->isUnionType()) {
1943 // GCC cast to union extension
1944 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1945 RecordDecl::field_iterator Field, FieldEnd;
1946 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1947 Field != FieldEnd; ++Field) {
1948 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1949 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1950 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1951 << castExpr->getSourceRange();
1952 break;
1953 }
1954 }
1955 if (Field == FieldEnd)
1956 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1957 << castExpr->getType() << castExpr->getSourceRange();
1958 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001959 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001960 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001961 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001962 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001963 } else if (!castExpr->getType()->isScalarType() &&
1964 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001965 return Diag(castExpr->getLocStart(),
1966 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001967 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001968 } else if (castExpr->getType()->isVectorType()) {
1969 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1970 return true;
1971 } else if (castType->isVectorType()) {
1972 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1973 return true;
1974 }
1975 return false;
1976}
1977
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001978bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001979 assert(VectorTy->isVectorType() && "Not a vector type!");
1980
1981 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001982 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001983 return Diag(R.getBegin(),
1984 Ty->isVectorType() ?
1985 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001986 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001987 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001988 } else
1989 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001990 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001991 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001992
1993 return false;
1994}
1995
Chris Lattner4b009652007-07-25 00:24:17 +00001996Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001997ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001998 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001999 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002000
2001 Expr *castExpr = static_cast<Expr*>(Op);
2002 QualType castType = QualType::getFromOpaquePtr(Ty);
2003
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002004 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2005 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00002006 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002007}
2008
Chris Lattner98a425c2007-11-26 01:40:58 +00002009/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2010/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002011inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2012 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2013 UsualUnaryConversions(cond);
2014 UsualUnaryConversions(lex);
2015 UsualUnaryConversions(rex);
2016 QualType condT = cond->getType();
2017 QualType lexT = lex->getType();
2018 QualType rexT = rex->getType();
2019
2020 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002021 if (!cond->isTypeDependent()) {
2022 if (!condT->isScalarType()) { // C99 6.5.15p2
2023 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2024 return QualType();
2025 }
Chris Lattner4b009652007-07-25 00:24:17 +00002026 }
Chris Lattner992ae932008-01-06 22:42:25 +00002027
2028 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002029 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2030 return Context.DependentTy;
2031
Chris Lattner992ae932008-01-06 22:42:25 +00002032 // If both operands have arithmetic type, do the usual arithmetic conversions
2033 // to find a common type: C99 6.5.15p3,5.
2034 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002035 UsualArithmeticConversions(lex, rex);
2036 return lex->getType();
2037 }
Chris Lattner992ae932008-01-06 22:42:25 +00002038
2039 // If both operands are the same structure or union type, the result is that
2040 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002041 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002042 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002043 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002044 // "If both the operands have structure or union type, the result has
2045 // that type." This implies that CV qualifiers are dropped.
2046 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002047 }
Chris Lattner992ae932008-01-06 22:42:25 +00002048
2049 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002050 // The following || allows only one side to be void (a GCC-ism).
2051 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002052 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002053 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2054 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002055 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002056 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2057 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002058 ImpCastExprToType(lex, Context.VoidTy);
2059 ImpCastExprToType(rex, Context.VoidTy);
2060 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002061 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002062 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2063 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002064 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2065 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002066 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002067 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002068 return lexT;
2069 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002070 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2071 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002072 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002073 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002074 return rexT;
2075 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002076 // Handle the case where both operands are pointers before we handle null
2077 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002078 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2079 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2080 // get the "pointed to" types
2081 QualType lhptee = LHSPT->getPointeeType();
2082 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002083
Chris Lattner71225142007-07-31 21:27:01 +00002084 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2085 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002086 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002087 // Figure out necessary qualifiers (C99 6.5.15p6)
2088 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002089 QualType destType = Context.getPointerType(destPointee);
2090 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2091 ImpCastExprToType(rex, destType); // promote to void*
2092 return destType;
2093 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002094 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002095 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002096 QualType destType = Context.getPointerType(destPointee);
2097 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2098 ImpCastExprToType(rex, destType); // promote to void*
2099 return destType;
2100 }
Chris Lattner4b009652007-07-25 00:24:17 +00002101
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002102 QualType compositeType = lexT;
2103
2104 // If either type is an Objective-C object type then check
2105 // compatibility according to Objective-C.
2106 if (Context.isObjCObjectPointerType(lexT) ||
2107 Context.isObjCObjectPointerType(rexT)) {
2108 // If both operands are interfaces and either operand can be
2109 // assigned to the other, use that type as the composite
2110 // type. This allows
2111 // xxx ? (A*) a : (B*) b
2112 // where B is a subclass of A.
2113 //
2114 // Additionally, as for assignment, if either type is 'id'
2115 // allow silent coercion. Finally, if the types are
2116 // incompatible then make sure to use 'id' as the composite
2117 // type so the result is acceptable for sending messages to.
2118
2119 // FIXME: This code should not be localized to here. Also this
2120 // should use a compatible check instead of abusing the
2121 // canAssignObjCInterfaces code.
2122 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2123 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2124 if (LHSIface && RHSIface &&
2125 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2126 compositeType = lexT;
2127 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002128 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002129 compositeType = rexT;
2130 } else if (Context.isObjCIdType(lhptee) ||
2131 Context.isObjCIdType(rhptee)) {
2132 // FIXME: This code looks wrong, because isObjCIdType checks
2133 // the struct but getObjCIdType returns the pointer to
2134 // struct. This is horrible and should be fixed.
2135 compositeType = Context.getObjCIdType();
2136 } else {
2137 QualType incompatTy = Context.getObjCIdType();
2138 ImpCastExprToType(lex, incompatTy);
2139 ImpCastExprToType(rex, incompatTy);
2140 return incompatTy;
2141 }
2142 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2143 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002144 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002145 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002146 // In this situation, we assume void* type. No especially good
2147 // reason, but this is what gcc does, and we do have to pick
2148 // to get a consistent AST.
2149 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002150 ImpCastExprToType(lex, incompatTy);
2151 ImpCastExprToType(rex, incompatTy);
2152 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002153 }
2154 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002155 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2156 // differently qualified versions of compatible types, the result type is
2157 // a pointer to an appropriately qualified version of the *composite*
2158 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002159 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002160 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002161 ImpCastExprToType(lex, compositeType);
2162 ImpCastExprToType(rex, compositeType);
2163 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002164 }
Chris Lattner4b009652007-07-25 00:24:17 +00002165 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002166 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2167 // evaluates to "struct objc_object *" (and is handled above when comparing
2168 // id with statically typed objects).
2169 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2170 // GCC allows qualified id and any Objective-C type to devolve to
2171 // id. Currently localizing to here until clear this should be
2172 // part of ObjCQualifiedIdTypesAreCompatible.
2173 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2174 (lexT->isObjCQualifiedIdType() &&
2175 Context.isObjCObjectPointerType(rexT)) ||
2176 (rexT->isObjCQualifiedIdType() &&
2177 Context.isObjCObjectPointerType(lexT))) {
2178 // FIXME: This is not the correct composite type. This only
2179 // happens to work because id can more or less be used anywhere,
2180 // however this may change the type of method sends.
2181 // FIXME: gcc adds some type-checking of the arguments and emits
2182 // (confusing) incompatible comparison warnings in some
2183 // cases. Investigate.
2184 QualType compositeType = Context.getObjCIdType();
2185 ImpCastExprToType(lex, compositeType);
2186 ImpCastExprToType(rex, compositeType);
2187 return compositeType;
2188 }
2189 }
2190
Steve Naroff3eac7692008-09-10 19:17:48 +00002191 // Selection between block pointer types is ok as long as they are the same.
2192 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2193 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2194 return lexT;
2195
Chris Lattner992ae932008-01-06 22:42:25 +00002196 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002197 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002198 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002199 return QualType();
2200}
2201
Steve Naroff87d58b42007-09-16 03:34:24 +00002202/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002203/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00002204Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002205 SourceLocation ColonLoc,
2206 ExprTy *Cond, ExprTy *LHS,
2207 ExprTy *RHS) {
2208 Expr *CondExpr = (Expr *) Cond;
2209 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00002210
2211 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2212 // was the condition.
2213 bool isLHSNull = LHSExpr == 0;
2214 if (isLHSNull)
2215 LHSExpr = CondExpr;
2216
Chris Lattner4b009652007-07-25 00:24:17 +00002217 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2218 RHSExpr, QuestionLoc);
2219 if (result.isNull())
2220 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002221 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2222 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002223}
2224
Chris Lattner4b009652007-07-25 00:24:17 +00002225
2226// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2227// being closely modeled after the C99 spec:-). The odd characteristic of this
2228// routine is it effectively iqnores the qualifiers on the top level pointee.
2229// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2230// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002231Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002232Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2233 QualType lhptee, rhptee;
2234
2235 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002236 lhptee = lhsType->getAsPointerType()->getPointeeType();
2237 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002238
2239 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002240 lhptee = Context.getCanonicalType(lhptee);
2241 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002242
Chris Lattner005ed752008-01-04 18:04:52 +00002243 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002244
2245 // C99 6.5.16.1p1: This following citation is common to constraints
2246 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2247 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002248 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002249 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002250 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002251
2252 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2253 // incomplete type and the other is a pointer to a qualified or unqualified
2254 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002255 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002256 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002257 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002258
2259 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002260 assert(rhptee->isFunctionType());
2261 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002262 }
2263
2264 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002265 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002266 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002267
2268 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002269 assert(lhptee->isFunctionType());
2270 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002271 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002272
2273 // Check for ObjC interfaces
2274 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2275 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2276 if (LHSIface && RHSIface &&
2277 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2278 return ConvTy;
2279
2280 // ID acts sort of like void* for ObjC interfaces
2281 if (LHSIface && Context.isObjCIdType(rhptee))
2282 return ConvTy;
2283 if (RHSIface && Context.isObjCIdType(lhptee))
2284 return ConvTy;
2285
Chris Lattner4b009652007-07-25 00:24:17 +00002286 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2287 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002288 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2289 rhptee.getUnqualifiedType()))
2290 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002291 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002292}
2293
Steve Naroff3454b6c2008-09-04 15:10:53 +00002294/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2295/// block pointer types are compatible or whether a block and normal pointer
2296/// are compatible. It is more restrict than comparing two function pointer
2297// types.
2298Sema::AssignConvertType
2299Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2300 QualType rhsType) {
2301 QualType lhptee, rhptee;
2302
2303 // get the "pointed to" type (ignoring qualifiers at the top level)
2304 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2305 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2306
2307 // make sure we operate on the canonical type
2308 lhptee = Context.getCanonicalType(lhptee);
2309 rhptee = Context.getCanonicalType(rhptee);
2310
2311 AssignConvertType ConvTy = Compatible;
2312
2313 // For blocks we enforce that qualifiers are identical.
2314 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2315 ConvTy = CompatiblePointerDiscardsQualifiers;
2316
2317 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2318 return IncompatibleBlockPointer;
2319 return ConvTy;
2320}
2321
Chris Lattner4b009652007-07-25 00:24:17 +00002322/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2323/// has code to accommodate several GCC extensions when type checking
2324/// pointers. Here are some objectionable examples that GCC considers warnings:
2325///
2326/// int a, *pint;
2327/// short *pshort;
2328/// struct foo *pfoo;
2329///
2330/// pint = pshort; // warning: assignment from incompatible pointer type
2331/// a = pint; // warning: assignment makes integer from pointer without a cast
2332/// pint = a; // warning: assignment makes pointer from integer without a cast
2333/// pint = pfoo; // warning: assignment from incompatible pointer type
2334///
2335/// As a result, the code for dealing with pointers is more complex than the
2336/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002337///
Chris Lattner005ed752008-01-04 18:04:52 +00002338Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002339Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002340 // Get canonical types. We're not formatting these types, just comparing
2341 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002342 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2343 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002344
2345 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002346 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002347
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002348 // If the left-hand side is a reference type, then we are in a
2349 // (rare!) case where we've allowed the use of references in C,
2350 // e.g., as a parameter type in a built-in function. In this case,
2351 // just make sure that the type referenced is compatible with the
2352 // right-hand side type. The caller is responsible for adjusting
2353 // lhsType so that the resulting expression does not have reference
2354 // type.
2355 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2356 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002357 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002358 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002359 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002360
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002361 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2362 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002363 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002364 // Relax integer conversions like we do for pointers below.
2365 if (rhsType->isIntegerType())
2366 return IntToPointer;
2367 if (lhsType->isIntegerType())
2368 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002369 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002370 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002371
Nate Begemanc5f0f652008-07-14 18:02:46 +00002372 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002373 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002374 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2375 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002376 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002377
Nate Begemanc5f0f652008-07-14 18:02:46 +00002378 // If we are allowing lax vector conversions, and LHS and RHS are both
2379 // vectors, the total size only needs to be the same. This is a bitcast;
2380 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002381 if (getLangOptions().LaxVectorConversions &&
2382 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002383 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2384 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002385 }
2386 return Incompatible;
2387 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002388
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002389 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002390 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002391
Chris Lattner390564e2008-04-07 06:49:41 +00002392 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002393 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002394 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002395
Chris Lattner390564e2008-04-07 06:49:41 +00002396 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002397 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002398
Steve Naroffa982c712008-09-29 18:10:17 +00002399 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002400 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002401 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002402
2403 // Treat block pointers as objects.
2404 if (getLangOptions().ObjC1 &&
2405 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2406 return Compatible;
2407 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002408 return Incompatible;
2409 }
2410
2411 if (isa<BlockPointerType>(lhsType)) {
2412 if (rhsType->isIntegerType())
2413 return IntToPointer;
2414
Steve Naroffa982c712008-09-29 18:10:17 +00002415 // Treat block pointers as objects.
2416 if (getLangOptions().ObjC1 &&
2417 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2418 return Compatible;
2419
Steve Naroff3454b6c2008-09-04 15:10:53 +00002420 if (rhsType->isBlockPointerType())
2421 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2422
2423 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2424 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002425 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002426 }
Chris Lattner1853da22008-01-04 23:18:45 +00002427 return Incompatible;
2428 }
2429
Chris Lattner390564e2008-04-07 06:49:41 +00002430 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002431 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002432 if (lhsType == Context.BoolTy)
2433 return Compatible;
2434
2435 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002436 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002437
Chris Lattner390564e2008-04-07 06:49:41 +00002438 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002439 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002440
2441 if (isa<BlockPointerType>(lhsType) &&
2442 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002443 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002444 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002445 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002446
Chris Lattner1853da22008-01-04 23:18:45 +00002447 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002448 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002449 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002450 }
2451 return Incompatible;
2452}
2453
Chris Lattner005ed752008-01-04 18:04:52 +00002454Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002455Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002456 if (getLangOptions().CPlusPlus) {
2457 if (!lhsType->isRecordType()) {
2458 // C++ 5.17p3: If the left operand is not of class type, the
2459 // expression is implicitly converted (C++ 4) to the
2460 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002461 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2462 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002463 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002464 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002465 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002466 }
2467
2468 // FIXME: Currently, we fall through and treat C++ classes like C
2469 // structures.
2470 }
2471
Steve Naroffcdee22d2007-11-27 17:58:44 +00002472 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2473 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002474 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2475 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002476 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002477 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002478 return Compatible;
2479 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002480
2481 // We don't allow conversion of non-null-pointer constants to integers.
2482 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2483 return IntToBlockPointer;
2484
Chris Lattner5f505bf2007-10-16 02:55:40 +00002485 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002486 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002487 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002488 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002489 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002490 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002491 if (!lhsType->isReferenceType())
2492 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002493
Chris Lattner005ed752008-01-04 18:04:52 +00002494 Sema::AssignConvertType result =
2495 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002496
2497 // C99 6.5.16.1p2: The value of the right operand is converted to the
2498 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002499 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2500 // so that we can use references in built-in functions even in C.
2501 // The getNonReferenceType() call makes sure that the resulting expression
2502 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002503 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002504 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002505 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002506}
2507
Chris Lattner005ed752008-01-04 18:04:52 +00002508Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002509Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2510 return CheckAssignmentConstraints(lhsType, rhsType);
2511}
2512
Chris Lattner1eafdea2008-11-18 01:30:42 +00002513QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002514 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002515 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002516 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002517 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002518}
2519
Chris Lattner1eafdea2008-11-18 01:30:42 +00002520inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002521 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002522 // For conversion purposes, we ignore any qualifiers.
2523 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002524 QualType lhsType =
2525 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2526 QualType rhsType =
2527 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002528
Nate Begemanc5f0f652008-07-14 18:02:46 +00002529 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002530 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002531 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002532
Nate Begemanc5f0f652008-07-14 18:02:46 +00002533 // Handle the case of a vector & extvector type of the same size and element
2534 // type. It would be nice if we only had one vector type someday.
2535 if (getLangOptions().LaxVectorConversions)
2536 if (const VectorType *LV = lhsType->getAsVectorType())
2537 if (const VectorType *RV = rhsType->getAsVectorType())
2538 if (LV->getElementType() == RV->getElementType() &&
2539 LV->getNumElements() == RV->getNumElements())
2540 return lhsType->isExtVectorType() ? lhsType : rhsType;
2541
2542 // If the lhs is an extended vector and the rhs is a scalar of the same type
2543 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002544 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002545 QualType eltType = V->getElementType();
2546
2547 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2548 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2549 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002550 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002551 return lhsType;
2552 }
2553 }
2554
Nate Begemanc5f0f652008-07-14 18:02:46 +00002555 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002556 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002557 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002558 QualType eltType = V->getElementType();
2559
2560 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2561 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2562 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002563 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002564 return rhsType;
2565 }
2566 }
2567
Chris Lattner4b009652007-07-25 00:24:17 +00002568 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002569 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002570 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002571 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002572 return QualType();
2573}
2574
2575inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002576 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002577{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002578 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002579 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002580
Steve Naroff8f708362007-08-24 19:07:16 +00002581 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002582
Chris Lattner4b009652007-07-25 00:24:17 +00002583 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002584 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002585 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002586}
2587
2588inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002589 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002590{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002591 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2592 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2593 return CheckVectorOperands(Loc, lex, rex);
2594 return InvalidOperands(Loc, lex, rex);
2595 }
Chris Lattner4b009652007-07-25 00:24:17 +00002596
Steve Naroff8f708362007-08-24 19:07:16 +00002597 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002598
Chris Lattner4b009652007-07-25 00:24:17 +00002599 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002600 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002601 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002602}
2603
2604inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002605 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002606{
2607 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002608 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002609
Steve Naroff8f708362007-08-24 19:07:16 +00002610 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002611
Chris Lattner4b009652007-07-25 00:24:17 +00002612 // handle the common case first (both operands are arithmetic).
2613 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002614 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002615
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002616 // Put any potential pointer into PExp
2617 Expr* PExp = lex, *IExp = rex;
2618 if (IExp->getType()->isPointerType())
2619 std::swap(PExp, IExp);
2620
2621 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2622 if (IExp->getType()->isIntegerType()) {
2623 // Check for arithmetic on pointers to incomplete types
2624 if (!PTy->getPointeeType()->isObjectType()) {
2625 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002626 Diag(Loc, diag::ext_gnu_void_ptr)
2627 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002628 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002629 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002630 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002631 return QualType();
2632 }
2633 }
2634 return PExp->getType();
2635 }
2636 }
2637
Chris Lattner1eafdea2008-11-18 01:30:42 +00002638 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002639}
2640
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002641// C99 6.5.6
2642QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002643 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002644 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002645 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002646
Steve Naroff8f708362007-08-24 19:07:16 +00002647 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002648
Chris Lattnerf6da2912007-12-09 21:53:25 +00002649 // Enforce type constraints: C99 6.5.6p3.
2650
2651 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002652 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002653 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002654
2655 // Either ptr - int or ptr - ptr.
2656 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002657 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002658
Chris Lattnerf6da2912007-12-09 21:53:25 +00002659 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002660 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002661 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002662 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002663 Diag(Loc, diag::ext_gnu_void_ptr)
2664 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002665 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002666 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002667 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002668 return QualType();
2669 }
2670 }
2671
2672 // The result type of a pointer-int computation is the pointer type.
2673 if (rex->getType()->isIntegerType())
2674 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002675
Chris Lattnerf6da2912007-12-09 21:53:25 +00002676 // Handle pointer-pointer subtractions.
2677 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002678 QualType rpointee = RHSPTy->getPointeeType();
2679
Chris Lattnerf6da2912007-12-09 21:53:25 +00002680 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002681 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002682 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002683 if (rpointee->isVoidType()) {
2684 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002685 Diag(Loc, diag::ext_gnu_void_ptr)
2686 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002687 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002688 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002689 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002690 return QualType();
2691 }
2692 }
2693
2694 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002695 if (!Context.typesAreCompatible(
2696 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2697 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002698 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002699 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002700 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002701 return QualType();
2702 }
2703
2704 return Context.getPointerDiffType();
2705 }
2706 }
2707
Chris Lattner1eafdea2008-11-18 01:30:42 +00002708 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002709}
2710
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002711// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002712QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002713 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002714 // C99 6.5.7p2: Each of the operands shall have integer type.
2715 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002716 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002717
Chris Lattner2c8bff72007-12-12 05:47:28 +00002718 // Shifts don't perform usual arithmetic conversions, they just do integer
2719 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002720 if (!isCompAssign)
2721 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002722 UsualUnaryConversions(rex);
2723
2724 // "The type of the result is that of the promoted left operand."
2725 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002726}
2727
Eli Friedman0d9549b2008-08-22 00:56:42 +00002728static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2729 ASTContext& Context) {
2730 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2731 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2732 // ID acts sort of like void* for ObjC interfaces
2733 if (LHSIface && Context.isObjCIdType(RHS))
2734 return true;
2735 if (RHSIface && Context.isObjCIdType(LHS))
2736 return true;
2737 if (!LHSIface || !RHSIface)
2738 return false;
2739 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2740 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2741}
2742
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002743// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002744QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002745 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002746 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002747 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002748
Chris Lattner254f3bc2007-08-26 01:18:55 +00002749 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002750 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2751 UsualArithmeticConversions(lex, rex);
2752 else {
2753 UsualUnaryConversions(lex);
2754 UsualUnaryConversions(rex);
2755 }
Chris Lattner4b009652007-07-25 00:24:17 +00002756 QualType lType = lex->getType();
2757 QualType rType = rex->getType();
2758
Ted Kremenek486509e2007-10-29 17:13:39 +00002759 // For non-floating point types, check for self-comparisons of the form
2760 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2761 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002762 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002763 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2764 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002765 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002766 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002767 }
2768
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002769 // The result of comparisons is 'bool' in C++, 'int' in C.
2770 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2771
Chris Lattner254f3bc2007-08-26 01:18:55 +00002772 if (isRelational) {
2773 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002774 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002775 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002776 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002777 if (lType->isFloatingType()) {
2778 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002779 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002780 }
2781
Chris Lattner254f3bc2007-08-26 01:18:55 +00002782 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002783 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002784 }
Chris Lattner4b009652007-07-25 00:24:17 +00002785
Chris Lattner22be8422007-08-26 01:10:14 +00002786 bool LHSIsNull = lex->isNullPointerConstant(Context);
2787 bool RHSIsNull = rex->isNullPointerConstant(Context);
2788
Chris Lattner254f3bc2007-08-26 01:18:55 +00002789 // All of the following pointer related warnings are GCC extensions, except
2790 // when handling null pointer constants. One day, we can consider making them
2791 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002792 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002793 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002794 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002795 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002796 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002797
Steve Naroff3b435622007-11-13 14:57:38 +00002798 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002799 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2800 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002801 RCanPointeeTy.getUnqualifiedType()) &&
2802 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002803 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002804 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002805 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002806 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002807 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002808 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002809 // Handle block pointer types.
2810 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2811 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2812 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2813
2814 if (!LHSIsNull && !RHSIsNull &&
2815 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002816 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002817 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002818 }
2819 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002820 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002821 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002822 // Allow block pointers to be compared with null pointer constants.
2823 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2824 (lType->isPointerType() && rType->isBlockPointerType())) {
2825 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002826 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002827 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002828 }
2829 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002830 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002831 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002832
Steve Naroff936c4362008-06-03 14:04:54 +00002833 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002834 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002835 const PointerType *LPT = lType->getAsPointerType();
2836 const PointerType *RPT = rType->getAsPointerType();
2837 bool LPtrToVoid = LPT ?
2838 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2839 bool RPtrToVoid = RPT ?
2840 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2841
2842 if (!LPtrToVoid && !RPtrToVoid &&
2843 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002844 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002845 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002846 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002847 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002848 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002849 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002850 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002851 }
Steve Naroff936c4362008-06-03 14:04:54 +00002852 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2853 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002854 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002855 } else {
2856 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002857 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002858 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002859 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002860 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002861 }
Steve Naroff936c4362008-06-03 14:04:54 +00002862 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002863 }
Steve Naroff936c4362008-06-03 14:04:54 +00002864 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2865 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002866 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002867 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002868 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002869 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002870 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002871 }
Steve Naroff936c4362008-06-03 14:04:54 +00002872 if (lType->isIntegerType() &&
2873 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002874 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002875 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002876 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002877 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002878 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002879 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002880 // Handle block pointers.
2881 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2882 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002883 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002884 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002885 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002886 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002887 }
2888 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2889 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002890 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002891 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002892 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002893 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002894 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002895 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002896}
2897
Nate Begemanc5f0f652008-07-14 18:02:46 +00002898/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2899/// operates on extended vector types. Instead of producing an IntTy result,
2900/// like a scalar comparison, a vector comparison produces a vector of integer
2901/// types.
2902QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002903 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002904 bool isRelational) {
2905 // Check to make sure we're operating on vectors of the same type and width,
2906 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002907 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002908 if (vType.isNull())
2909 return vType;
2910
2911 QualType lType = lex->getType();
2912 QualType rType = rex->getType();
2913
2914 // For non-floating point types, check for self-comparisons of the form
2915 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2916 // often indicate logic errors in the program.
2917 if (!lType->isFloatingType()) {
2918 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2919 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2920 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002921 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002922 }
2923
2924 // Check for comparisons of floating point operands using != and ==.
2925 if (!isRelational && lType->isFloatingType()) {
2926 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002927 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002928 }
2929
2930 // Return the type for the comparison, which is the same as vector type for
2931 // integer vectors, or an integer type of identical size and number of
2932 // elements for floating point vectors.
2933 if (lType->isIntegerType())
2934 return lType;
2935
2936 const VectorType *VTy = lType->getAsVectorType();
2937
2938 // FIXME: need to deal with non-32b int / non-64b long long
2939 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2940 if (TypeSize == 32) {
2941 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2942 }
2943 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2944 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2945}
2946
Chris Lattner4b009652007-07-25 00:24:17 +00002947inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002948 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002949{
2950 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002951 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002952
Steve Naroff8f708362007-08-24 19:07:16 +00002953 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002954
2955 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002956 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002957 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002958}
2959
2960inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002961 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002962{
2963 UsualUnaryConversions(lex);
2964 UsualUnaryConversions(rex);
2965
Eli Friedmanbea3f842008-05-13 20:16:47 +00002966 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002967 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002968 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002969}
2970
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002971/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2972/// is a read-only property; return true if so. A readonly property expression
2973/// depends on various declarations and thus must be treated specially.
2974///
2975static bool IsReadonlyProperty(Expr *E, Sema &S)
2976{
2977 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2978 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2979 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2980 QualType BaseType = PropExpr->getBase()->getType();
2981 if (const PointerType *PTy = BaseType->getAsPointerType())
2982 if (const ObjCInterfaceType *IFTy =
2983 PTy->getPointeeType()->getAsObjCInterfaceType())
2984 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2985 if (S.isPropertyReadonly(PDecl, IFace))
2986 return true;
2987 }
2988 }
2989 return false;
2990}
2991
Chris Lattner4c2642c2008-11-18 01:22:49 +00002992/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2993/// emit an error and return true. If so, return false.
2994static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002995 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2996 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
2997 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002998 if (IsLV == Expr::MLV_Valid)
2999 return false;
3000
3001 unsigned Diag = 0;
3002 bool NeedType = false;
3003 switch (IsLV) { // C99 6.5.16p2
3004 default: assert(0 && "Unknown result from isModifiableLvalue!");
3005 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003006 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003007 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3008 NeedType = true;
3009 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003010 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003011 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3012 NeedType = true;
3013 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003014 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003015 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3016 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003017 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003018 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3019 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003020 case Expr::MLV_IncompleteType:
3021 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003022 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
3023 NeedType = true;
3024 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003025 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003026 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3027 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003028 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003029 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3030 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003031 case Expr::MLV_ReadonlyProperty:
3032 Diag = diag::error_readonly_property_assignment;
3033 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003034 case Expr::MLV_NoSetterProperty:
3035 Diag = diag::error_nosetter_property_assignment;
3036 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003037 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003038
Chris Lattner4c2642c2008-11-18 01:22:49 +00003039 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003040 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003041 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003042 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003043 return true;
3044}
3045
3046
3047
3048// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003049QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3050 SourceLocation Loc,
3051 QualType CompoundType) {
3052 // Verify that LHS is a modifiable lvalue, and emit error if not.
3053 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003054 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003055
3056 QualType LHSType = LHS->getType();
3057 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003058
Chris Lattner005ed752008-01-04 18:04:52 +00003059 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003060 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003061 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003062 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003063 // Special case of NSObject attributes on c-style pointer types.
3064 if (ConvTy == IncompatiblePointer &&
3065 ((Context.isObjCNSObjectType(LHSType) &&
3066 Context.isObjCObjectPointerType(RHSType)) ||
3067 (Context.isObjCNSObjectType(RHSType) &&
3068 Context.isObjCObjectPointerType(LHSType))))
3069 ConvTy = Compatible;
3070
Chris Lattner34c85082008-08-21 18:04:13 +00003071 // If the RHS is a unary plus or minus, check to see if they = and + are
3072 // right next to each other. If so, the user may have typo'd "x =+ 4"
3073 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003074 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3076 RHSCheck = ICE->getSubExpr();
3077 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3078 if ((UO->getOpcode() == UnaryOperator::Plus ||
3079 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003081 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003082 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003083 Diag(Loc, diag::warn_not_compound_assign)
3084 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3085 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003086 }
3087 } else {
3088 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003089 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003090 }
Chris Lattner005ed752008-01-04 18:04:52 +00003091
Chris Lattner1eafdea2008-11-18 01:30:42 +00003092 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3093 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003094 return QualType();
3095
Chris Lattner4b009652007-07-25 00:24:17 +00003096 // C99 6.5.16p3: The type of an assignment expression is the type of the
3097 // left operand unless the left operand has qualified type, in which case
3098 // it is the unqualified version of the type of the left operand.
3099 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3100 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003101 // C++ 5.17p1: the type of the assignment expression is that of its left
3102 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003103 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003104}
3105
Chris Lattner1eafdea2008-11-18 01:30:42 +00003106// C99 6.5.17
3107QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3108 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003109
3110 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003111 DefaultFunctionArrayConversion(RHS);
3112 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003113}
3114
3115/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3116/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003117QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3118 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003119 QualType ResType = Op->getType();
3120 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003121
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003122 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3123 // Decrement of bool is not allowed.
3124 if (!isInc) {
3125 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3126 return QualType();
3127 }
3128 // Increment of bool sets it to true, but is deprecated.
3129 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3130 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003131 // OK!
3132 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3133 // C99 6.5.2.4p2, 6.5.6p2
3134 if (PT->getPointeeType()->isObjectType()) {
3135 // Pointer to object is ok!
3136 } else if (PT->getPointeeType()->isVoidType()) {
3137 // Pointer to void is extension.
3138 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3139 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00003140 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003141 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003142 return QualType();
3143 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003144 } else if (ResType->isComplexType()) {
3145 // C99 does not support ++/-- on complex types, we allow as an extension.
3146 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003148 } else {
3149 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003150 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003151 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003152 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003153 // At this point, we know we have a real, complex or pointer type.
3154 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003155 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003156 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003157 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003158}
3159
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003160/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003161/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003162/// where the declaration is needed for type checking. We only need to
3163/// handle cases when the expression references a function designator
3164/// or is an lvalue. Here are some examples:
3165/// - &(x) => x
3166/// - &*****f => f for f a function designator.
3167/// - &s.xx => s
3168/// - &s.zz[1].yy -> s, if zz is an array
3169/// - *(x + 1) -> x, if x is an array
3170/// - &"123"[2] -> 0
3171/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003172static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003173 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003174 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003175 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003176 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003177 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003178 // Fields cannot be declared with a 'register' storage class.
3179 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003180 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003181 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003182 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003183 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003184 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003185
Douglas Gregord2baafd2008-10-21 16:13:35 +00003186 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003187 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003188 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003189 return 0;
3190 else
3191 return VD;
3192 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003193 case Stmt::UnaryOperatorClass: {
3194 UnaryOperator *UO = cast<UnaryOperator>(E);
3195
3196 switch(UO->getOpcode()) {
3197 case UnaryOperator::Deref: {
3198 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003199 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3200 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3201 if (!VD || VD->getType()->isPointerType())
3202 return 0;
3203 return VD;
3204 }
3205 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003206 }
3207 case UnaryOperator::Real:
3208 case UnaryOperator::Imag:
3209 case UnaryOperator::Extension:
3210 return getPrimaryDecl(UO->getSubExpr());
3211 default:
3212 return 0;
3213 }
3214 }
3215 case Stmt::BinaryOperatorClass: {
3216 BinaryOperator *BO = cast<BinaryOperator>(E);
3217
3218 // Handle cases involving pointer arithmetic. The result of an
3219 // Assign or AddAssign is not an lvalue so they can be ignored.
3220
3221 // (x + n) or (n + x) => x
3222 if (BO->getOpcode() == BinaryOperator::Add) {
3223 if (BO->getLHS()->getType()->isPointerType()) {
3224 return getPrimaryDecl(BO->getLHS());
3225 } else if (BO->getRHS()->getType()->isPointerType()) {
3226 return getPrimaryDecl(BO->getRHS());
3227 }
3228 }
3229
3230 return 0;
3231 }
Chris Lattner4b009652007-07-25 00:24:17 +00003232 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003233 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003234 case Stmt::ImplicitCastExprClass:
3235 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003236 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003237 default:
3238 return 0;
3239 }
3240}
3241
3242/// CheckAddressOfOperand - The operand of & must be either a function
3243/// designator or an lvalue designating an object. If it is an lvalue, the
3244/// object cannot be declared with storage class register or be a bit field.
3245/// Note: The usual conversions are *not* applied to the operand of the &
3246/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003247/// In C++, the operand might be an overloaded function name, in which case
3248/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003249QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003250 if (op->isTypeDependent())
3251 return Context.DependentTy;
3252
Steve Naroff9c6c3592008-01-13 17:10:08 +00003253 if (getLangOptions().C99) {
3254 // Implement C99-only parts of addressof rules.
3255 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3256 if (uOp->getOpcode() == UnaryOperator::Deref)
3257 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3258 // (assuming the deref expression is valid).
3259 return uOp->getSubExpr()->getType();
3260 }
3261 // Technically, there should be a check for array subscript
3262 // expressions here, but the result of one is always an lvalue anyway.
3263 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003264 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003265 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003266
Chris Lattner4b009652007-07-25 00:24:17 +00003267 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003268 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3269 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003270 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3271 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003272 return QualType();
3273 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003274 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003275 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3276 if (Field->isBitField()) {
3277 Diag(OpLoc, diag::err_typecheck_address_of)
3278 << "bit-field" << op->getSourceRange();
3279 return QualType();
3280 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003281 }
3282 // Check for Apple extension for accessing vector components.
3283 } else if (isa<ArraySubscriptExpr>(op) &&
3284 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003285 Diag(OpLoc, diag::err_typecheck_address_of)
3286 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003287 return QualType();
3288 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003289 // We have an lvalue with a decl. Make sure the decl is not declared
3290 // with the register storage-class specifier.
3291 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3292 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003293 Diag(OpLoc, diag::err_typecheck_address_of)
3294 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003295 return QualType();
3296 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003297 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003298 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003299 } else if (isa<FieldDecl>(dcl)) {
3300 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003301 } else if (isa<FunctionDecl>(dcl)) {
3302 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003303 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003304 else
Chris Lattner4b009652007-07-25 00:24:17 +00003305 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003306 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003307
Chris Lattner4b009652007-07-25 00:24:17 +00003308 // If the operand has type "type", the result has type "pointer to type".
3309 return Context.getPointerType(op->getType());
3310}
3311
Chris Lattnerda5c0872008-11-23 09:13:29 +00003312QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3313 UsualUnaryConversions(Op);
3314 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003315
Chris Lattnerda5c0872008-11-23 09:13:29 +00003316 // Note that per both C89 and C99, this is always legal, even if ptype is an
3317 // incomplete type or void. It would be possible to warn about dereferencing
3318 // a void pointer, but it's completely well-defined, and such a warning is
3319 // unlikely to catch any mistakes.
3320 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003321 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003322
Chris Lattner77d52da2008-11-20 06:06:08 +00003323 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003324 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003325 return QualType();
3326}
3327
3328static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3329 tok::TokenKind Kind) {
3330 BinaryOperator::Opcode Opc;
3331 switch (Kind) {
3332 default: assert(0 && "Unknown binop!");
3333 case tok::star: Opc = BinaryOperator::Mul; break;
3334 case tok::slash: Opc = BinaryOperator::Div; break;
3335 case tok::percent: Opc = BinaryOperator::Rem; break;
3336 case tok::plus: Opc = BinaryOperator::Add; break;
3337 case tok::minus: Opc = BinaryOperator::Sub; break;
3338 case tok::lessless: Opc = BinaryOperator::Shl; break;
3339 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3340 case tok::lessequal: Opc = BinaryOperator::LE; break;
3341 case tok::less: Opc = BinaryOperator::LT; break;
3342 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3343 case tok::greater: Opc = BinaryOperator::GT; break;
3344 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3345 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3346 case tok::amp: Opc = BinaryOperator::And; break;
3347 case tok::caret: Opc = BinaryOperator::Xor; break;
3348 case tok::pipe: Opc = BinaryOperator::Or; break;
3349 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3350 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3351 case tok::equal: Opc = BinaryOperator::Assign; break;
3352 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3353 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3354 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3355 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3356 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3357 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3358 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3359 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3360 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3361 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3362 case tok::comma: Opc = BinaryOperator::Comma; break;
3363 }
3364 return Opc;
3365}
3366
3367static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3368 tok::TokenKind Kind) {
3369 UnaryOperator::Opcode Opc;
3370 switch (Kind) {
3371 default: assert(0 && "Unknown unary op!");
3372 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3373 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3374 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3375 case tok::star: Opc = UnaryOperator::Deref; break;
3376 case tok::plus: Opc = UnaryOperator::Plus; break;
3377 case tok::minus: Opc = UnaryOperator::Minus; break;
3378 case tok::tilde: Opc = UnaryOperator::Not; break;
3379 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003380 case tok::kw___real: Opc = UnaryOperator::Real; break;
3381 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3382 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3383 }
3384 return Opc;
3385}
3386
Douglas Gregord7f915e2008-11-06 23:29:22 +00003387/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3388/// operator @p Opc at location @c TokLoc. This routine only supports
3389/// built-in operations; ActOnBinOp handles overloaded operators.
3390Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3391 unsigned Op,
3392 Expr *lhs, Expr *rhs) {
3393 QualType ResultTy; // Result type of the binary operator.
3394 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3395 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3396
3397 switch (Opc) {
3398 default:
3399 assert(0 && "Unknown binary expr!");
3400 case BinaryOperator::Assign:
3401 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3402 break;
3403 case BinaryOperator::Mul:
3404 case BinaryOperator::Div:
3405 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3406 break;
3407 case BinaryOperator::Rem:
3408 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3409 break;
3410 case BinaryOperator::Add:
3411 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3412 break;
3413 case BinaryOperator::Sub:
3414 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3415 break;
3416 case BinaryOperator::Shl:
3417 case BinaryOperator::Shr:
3418 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3419 break;
3420 case BinaryOperator::LE:
3421 case BinaryOperator::LT:
3422 case BinaryOperator::GE:
3423 case BinaryOperator::GT:
3424 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3425 break;
3426 case BinaryOperator::EQ:
3427 case BinaryOperator::NE:
3428 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3429 break;
3430 case BinaryOperator::And:
3431 case BinaryOperator::Xor:
3432 case BinaryOperator::Or:
3433 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3434 break;
3435 case BinaryOperator::LAnd:
3436 case BinaryOperator::LOr:
3437 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3438 break;
3439 case BinaryOperator::MulAssign:
3440 case BinaryOperator::DivAssign:
3441 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3442 if (!CompTy.isNull())
3443 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3444 break;
3445 case BinaryOperator::RemAssign:
3446 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3447 if (!CompTy.isNull())
3448 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3449 break;
3450 case BinaryOperator::AddAssign:
3451 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3452 if (!CompTy.isNull())
3453 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3454 break;
3455 case BinaryOperator::SubAssign:
3456 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3457 if (!CompTy.isNull())
3458 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3459 break;
3460 case BinaryOperator::ShlAssign:
3461 case BinaryOperator::ShrAssign:
3462 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3463 if (!CompTy.isNull())
3464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3465 break;
3466 case BinaryOperator::AndAssign:
3467 case BinaryOperator::XorAssign:
3468 case BinaryOperator::OrAssign:
3469 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3470 if (!CompTy.isNull())
3471 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3472 break;
3473 case BinaryOperator::Comma:
3474 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3475 break;
3476 }
3477 if (ResultTy.isNull())
3478 return true;
3479 if (CompTy.isNull())
3480 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3481 else
3482 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3483}
3484
Chris Lattner4b009652007-07-25 00:24:17 +00003485// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003486Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3487 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003488 ExprTy *LHS, ExprTy *RHS) {
3489 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3490 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3491
Steve Naroff87d58b42007-09-16 03:34:24 +00003492 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3493 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003494
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003495 // If either expression is type-dependent, just build the AST.
3496 // FIXME: We'll need to perform some caching of the result of name
3497 // lookup for operator+.
3498 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3499 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3500 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3501 Context.DependentTy, TokLoc);
3502 else
3503 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3504 }
3505
Douglas Gregord7f915e2008-11-06 23:29:22 +00003506 if (getLangOptions().CPlusPlus &&
3507 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3508 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003509 // If this is one of the assignment operators, we only perform
3510 // overload resolution if the left-hand side is a class or
3511 // enumeration type (C++ [expr.ass]p3).
3512 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3513 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3514 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3515 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003516
3517 // Determine which overloaded operator we're dealing with.
3518 static const OverloadedOperatorKind OverOps[] = {
3519 OO_Star, OO_Slash, OO_Percent,
3520 OO_Plus, OO_Minus,
3521 OO_LessLess, OO_GreaterGreater,
3522 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3523 OO_EqualEqual, OO_ExclaimEqual,
3524 OO_Amp,
3525 OO_Caret,
3526 OO_Pipe,
3527 OO_AmpAmp,
3528 OO_PipePipe,
3529 OO_Equal, OO_StarEqual,
3530 OO_SlashEqual, OO_PercentEqual,
3531 OO_PlusEqual, OO_MinusEqual,
3532 OO_LessLessEqual, OO_GreaterGreaterEqual,
3533 OO_AmpEqual, OO_CaretEqual,
3534 OO_PipeEqual,
3535 OO_Comma
3536 };
3537 OverloadedOperatorKind OverOp = OverOps[Opc];
3538
Douglas Gregor5ed15042008-11-18 23:14:02 +00003539 // Add the appropriate overloaded operators (C++ [over.match.oper])
3540 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003541 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003542 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003543 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003544
3545 // Perform overload resolution.
3546 OverloadCandidateSet::iterator Best;
3547 switch (BestViableFunction(CandidateSet, Best)) {
3548 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003549 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003550 FunctionDecl *FnDecl = Best->Function;
3551
Douglas Gregor70d26122008-11-12 17:17:38 +00003552 if (FnDecl) {
3553 // We matched an overloaded operator. Build a call to that
3554 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003555
Douglas Gregor70d26122008-11-12 17:17:38 +00003556 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3558 if (PerformObjectArgumentInitialization(lhs, Method) ||
3559 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3560 "passing"))
3561 return true;
3562 } else {
3563 // Convert the arguments.
3564 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3565 "passing") ||
3566 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3567 "passing"))
3568 return true;
3569 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003570
Douglas Gregor70d26122008-11-12 17:17:38 +00003571 // Determine the result type
3572 QualType ResultTy
3573 = FnDecl->getType()->getAsFunctionType()->getResultType();
3574 ResultTy = ResultTy.getNonReferenceType();
3575
3576 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003577 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3578 SourceLocation());
3579 UsualUnaryConversions(FnExpr);
3580
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003581 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003582 } else {
3583 // We matched a built-in operator. Convert the arguments, then
3584 // break out so that we will build the appropriate built-in
3585 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003586 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3587 Best->Conversions[0], "passing") ||
3588 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3589 Best->Conversions[1], "passing"))
Douglas Gregor70d26122008-11-12 17:17:38 +00003590 return true;
3591
3592 break;
3593 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003594 }
3595
3596 case OR_No_Viable_Function:
3597 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003598 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003599 break;
3600
3601 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003602 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3603 << BinaryOperator::getOpcodeStr(Opc)
3604 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003605 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3606 return true;
3607 }
3608
Douglas Gregor70d26122008-11-12 17:17:38 +00003609 // Either we found no viable overloaded operator or we matched a
3610 // built-in operator. In either case, fall through to trying to
3611 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003612 }
Chris Lattner4b009652007-07-25 00:24:17 +00003613
Douglas Gregord7f915e2008-11-06 23:29:22 +00003614 // Build a built-in binary operation.
3615 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003616}
3617
3618// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003619Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3620 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003621 Expr *Input = (Expr*)input;
3622 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003623
3624 if (getLangOptions().CPlusPlus &&
3625 (Input->getType()->isRecordType()
3626 || Input->getType()->isEnumeralType())) {
3627 // Determine which overloaded operator we're dealing with.
3628 static const OverloadedOperatorKind OverOps[] = {
3629 OO_None, OO_None,
3630 OO_PlusPlus, OO_MinusMinus,
3631 OO_Amp, OO_Star,
3632 OO_Plus, OO_Minus,
3633 OO_Tilde, OO_Exclaim,
3634 OO_None, OO_None,
3635 OO_None,
3636 OO_None
3637 };
3638 OverloadedOperatorKind OverOp = OverOps[Opc];
3639
3640 // Add the appropriate overloaded operators (C++ [over.match.oper])
3641 // to the candidate set.
3642 OverloadCandidateSet CandidateSet;
3643 if (OverOp != OO_None)
3644 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3645
3646 // Perform overload resolution.
3647 OverloadCandidateSet::iterator Best;
3648 switch (BestViableFunction(CandidateSet, Best)) {
3649 case OR_Success: {
3650 // We found a built-in operator or an overloaded operator.
3651 FunctionDecl *FnDecl = Best->Function;
3652
3653 if (FnDecl) {
3654 // We matched an overloaded operator. Build a call to that
3655 // operator.
3656
3657 // Convert the arguments.
3658 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3659 if (PerformObjectArgumentInitialization(Input, Method))
3660 return true;
3661 } else {
3662 // Convert the arguments.
3663 if (PerformCopyInitialization(Input,
3664 FnDecl->getParamDecl(0)->getType(),
3665 "passing"))
3666 return true;
3667 }
3668
3669 // Determine the result type
3670 QualType ResultTy
3671 = FnDecl->getType()->getAsFunctionType()->getResultType();
3672 ResultTy = ResultTy.getNonReferenceType();
3673
3674 // Build the actual expression node.
3675 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3676 SourceLocation());
3677 UsualUnaryConversions(FnExpr);
3678
3679 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3680 } else {
3681 // We matched a built-in operator. Convert the arguments, then
3682 // break out so that we will build the appropriate built-in
3683 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003684 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3685 Best->Conversions[0], "passing"))
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003686 return true;
3687
3688 break;
3689 }
3690 }
3691
3692 case OR_No_Viable_Function:
3693 // No viable function; fall through to handling this as a
3694 // built-in operator, which will produce an error message for us.
3695 break;
3696
3697 case OR_Ambiguous:
3698 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3699 << UnaryOperator::getOpcodeStr(Opc)
3700 << Input->getSourceRange();
3701 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3702 return true;
3703 }
3704
3705 // Either we found no viable overloaded operator or we matched a
3706 // built-in operator. In either case, fall through to trying to
3707 // build a built-in operation.
3708 }
3709
Chris Lattner4b009652007-07-25 00:24:17 +00003710 QualType resultType;
3711 switch (Opc) {
3712 default:
3713 assert(0 && "Unimplemented unary expr!");
3714 case UnaryOperator::PreInc:
3715 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003716 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3717 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003718 break;
3719 case UnaryOperator::AddrOf:
3720 resultType = CheckAddressOfOperand(Input, OpLoc);
3721 break;
3722 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003723 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003724 resultType = CheckIndirectionOperand(Input, OpLoc);
3725 break;
3726 case UnaryOperator::Plus:
3727 case UnaryOperator::Minus:
3728 UsualUnaryConversions(Input);
3729 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003730 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3731 break;
3732 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3733 resultType->isEnumeralType())
3734 break;
3735 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3736 Opc == UnaryOperator::Plus &&
3737 resultType->isPointerType())
3738 break;
3739
Chris Lattner77d52da2008-11-20 06:06:08 +00003740 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003741 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003742 case UnaryOperator::Not: // bitwise complement
3743 UsualUnaryConversions(Input);
3744 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003745 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3746 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3747 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003748 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003749 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003750 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003751 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003752 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003753 break;
3754 case UnaryOperator::LNot: // logical negation
3755 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3756 DefaultFunctionArrayConversion(Input);
3757 resultType = Input->getType();
3758 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003759 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003760 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003761 // LNot always has type int. C99 6.5.3.3p5.
3762 resultType = Context.IntTy;
3763 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003764 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003765 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003766 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003767 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003768 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003769 resultType = Input->getType();
3770 break;
3771 }
3772 if (resultType.isNull())
3773 return true;
3774 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3775}
3776
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003777/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3778Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003779 SourceLocation LabLoc,
3780 IdentifierInfo *LabelII) {
3781 // Look up the record for this label identifier.
3782 LabelStmt *&LabelDecl = LabelMap[LabelII];
3783
Daniel Dunbar879788d2008-08-04 16:51:22 +00003784 // If we haven't seen this label yet, create a forward reference. It
3785 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003786 if (LabelDecl == 0)
3787 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3788
3789 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003790 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3791 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003792}
3793
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003794Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003795 SourceLocation RPLoc) { // "({..})"
3796 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3797 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3798 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3799
3800 // FIXME: there are a variety of strange constraints to enforce here, for
3801 // example, it is not possible to goto into a stmt expression apparently.
3802 // More semantic analysis is needed.
3803
3804 // FIXME: the last statement in the compount stmt has its value used. We
3805 // should not warn about it being unused.
3806
3807 // If there are sub stmts in the compound stmt, take the type of the last one
3808 // as the type of the stmtexpr.
3809 QualType Ty = Context.VoidTy;
3810
Chris Lattner200964f2008-07-26 19:51:01 +00003811 if (!Compound->body_empty()) {
3812 Stmt *LastStmt = Compound->body_back();
3813 // If LastStmt is a label, skip down through into the body.
3814 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3815 LastStmt = Label->getSubStmt();
3816
3817 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003818 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003819 }
Chris Lattner4b009652007-07-25 00:24:17 +00003820
3821 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3822}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003823
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003824Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3825 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003826 SourceLocation TypeLoc,
3827 TypeTy *argty,
3828 OffsetOfComponent *CompPtr,
3829 unsigned NumComponents,
3830 SourceLocation RPLoc) {
3831 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3832 assert(!ArgTy.isNull() && "Missing type argument!");
3833
3834 // We must have at least one component that refers to the type, and the first
3835 // one is known to be a field designator. Verify that the ArgTy represents
3836 // a struct/union/class.
3837 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003838 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003839
3840 // Otherwise, create a compound literal expression as the base, and
3841 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003842 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003843
Chris Lattnerb37522e2007-08-31 21:49:13 +00003844 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3845 // GCC extension, diagnose them.
3846 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003847 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3848 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003849
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003850 for (unsigned i = 0; i != NumComponents; ++i) {
3851 const OffsetOfComponent &OC = CompPtr[i];
3852 if (OC.isBrackets) {
3853 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003854 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003855 if (!AT) {
3856 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003857 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003858 }
3859
Chris Lattner2af6a802007-08-30 17:59:59 +00003860 // FIXME: C++: Verify that operator[] isn't overloaded.
3861
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003862 // C99 6.5.2.1p1
3863 Expr *Idx = static_cast<Expr*>(OC.U.E);
3864 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003865 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3866 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003867
3868 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3869 continue;
3870 }
3871
3872 const RecordType *RC = Res->getType()->getAsRecordType();
3873 if (!RC) {
3874 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003875 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003876 }
3877
3878 // Get the decl corresponding to this.
3879 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003880 FieldDecl *MemberDecl
3881 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3882 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003883 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003884 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003885 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3886 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003887
3888 // FIXME: C++: Verify that MemberDecl isn't a static field.
3889 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003890 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3891 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003892 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3893 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003894 }
3895
3896 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3897 BuiltinLoc);
3898}
3899
3900
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003901Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003902 TypeTy *arg1, TypeTy *arg2,
3903 SourceLocation RPLoc) {
3904 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3905 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3906
3907 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3908
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003909 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003910}
3911
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003912Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003913 ExprTy *expr1, ExprTy *expr2,
3914 SourceLocation RPLoc) {
3915 Expr *CondExpr = static_cast<Expr*>(cond);
3916 Expr *LHSExpr = static_cast<Expr*>(expr1);
3917 Expr *RHSExpr = static_cast<Expr*>(expr2);
3918
3919 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3920
3921 // The conditional expression is required to be a constant expression.
3922 llvm::APSInt condEval(32);
3923 SourceLocation ExpLoc;
3924 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003925 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3926 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003927
3928 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3929 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3930 RHSExpr->getType();
3931 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3932}
3933
Steve Naroff52a81c02008-09-03 18:15:37 +00003934//===----------------------------------------------------------------------===//
3935// Clang Extensions.
3936//===----------------------------------------------------------------------===//
3937
3938/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003939void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003940 // Analyze block parameters.
3941 BlockSemaInfo *BSI = new BlockSemaInfo();
3942
3943 // Add BSI to CurBlock.
3944 BSI->PrevBlockInfo = CurBlock;
3945 CurBlock = BSI;
3946
3947 BSI->ReturnType = 0;
3948 BSI->TheScope = BlockScope;
3949
Steve Naroff52059382008-10-10 01:28:17 +00003950 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003951 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003952}
3953
3954void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003955 // Analyze arguments to block.
3956 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3957 "Not a function declarator!");
3958 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3959
Steve Naroff52059382008-10-10 01:28:17 +00003960 CurBlock->hasPrototype = FTI.hasPrototype;
3961 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003962
3963 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3964 // no arguments, not a function that takes a single void argument.
3965 if (FTI.hasPrototype &&
3966 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3967 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3968 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3969 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003970 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003971 } else if (FTI.hasPrototype) {
3972 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003973 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3974 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003975 }
Steve Naroff52059382008-10-10 01:28:17 +00003976 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3977
3978 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3979 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3980 // If this has an identifier, add it to the scope stack.
3981 if ((*AI)->getIdentifier())
3982 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003983}
3984
3985/// ActOnBlockError - If there is an error parsing a block, this callback
3986/// is invoked to pop the information about the block from the action impl.
3987void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3988 // Ensure that CurBlock is deleted.
3989 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3990
3991 // Pop off CurBlock, handle nested blocks.
3992 CurBlock = CurBlock->PrevBlockInfo;
3993
3994 // FIXME: Delete the ParmVarDecl objects as well???
3995
3996}
3997
3998/// ActOnBlockStmtExpr - This is called when the body of a block statement
3999/// literal was successfully completed. ^(int x){...}
4000Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4001 Scope *CurScope) {
4002 // Ensure that CurBlock is deleted.
4003 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4004 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4005
Steve Naroff52059382008-10-10 01:28:17 +00004006 PopDeclContext();
4007
Steve Naroff52a81c02008-09-03 18:15:37 +00004008 // Pop off CurBlock, handle nested blocks.
4009 CurBlock = CurBlock->PrevBlockInfo;
4010
4011 QualType RetTy = Context.VoidTy;
4012 if (BSI->ReturnType)
4013 RetTy = QualType(BSI->ReturnType, 0);
4014
4015 llvm::SmallVector<QualType, 8> ArgTypes;
4016 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4017 ArgTypes.push_back(BSI->Params[i]->getType());
4018
4019 QualType BlockTy;
4020 if (!BSI->hasPrototype)
4021 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4022 else
4023 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004024 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004025
4026 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004027
Steve Naroff95029d92008-10-08 18:44:00 +00004028 BSI->TheDecl->setBody(Body.take());
4029 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004030}
4031
Nate Begemanbd881ef2008-01-30 20:50:20 +00004032/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004033/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004034/// The number of arguments has already been validated to match the number of
4035/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004036static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4037 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004038 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004039 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004040 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4041 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004042
4043 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004044 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004045 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004046 return true;
4047}
4048
4049Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4050 SourceLocation *CommaLocs,
4051 SourceLocation BuiltinLoc,
4052 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004053 // __builtin_overload requires at least 2 arguments
4054 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004055 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4056 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004057
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004058 // The first argument is required to be a constant expression. It tells us
4059 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004060 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004061 Expr *NParamsExpr = Args[0];
4062 llvm::APSInt constEval(32);
4063 SourceLocation ExpLoc;
4064 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004065 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4066 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004067
4068 // Verify that the number of parameters is > 0
4069 unsigned NumParams = constEval.getZExtValue();
4070 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004071 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4072 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004073 // Verify that we have at least 1 + NumParams arguments to the builtin.
4074 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004075 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4076 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004077
4078 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004079 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004080 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004081 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4082 // UsualUnaryConversions will convert the function DeclRefExpr into a
4083 // pointer to function.
4084 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004085 const FunctionTypeProto *FnType = 0;
4086 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4087 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004088
4089 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4090 // parameters, and the number of parameters must match the value passed to
4091 // the builtin.
4092 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004093 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4094 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004095
4096 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004097 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004098 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004099 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004100 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004101 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4102 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004103 // Remember our match, and continue processing the remaining arguments
4104 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004105 OE = new OverloadExpr(Args, NumArgs, i,
4106 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004107 BuiltinLoc, RParenLoc);
4108 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004109 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004110 // Return the newly created OverloadExpr node, if we succeded in matching
4111 // exactly one of the candidate functions.
4112 if (OE)
4113 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004114
4115 // If we didn't find a matching function Expr in the __builtin_overload list
4116 // the return an error.
4117 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004118 for (unsigned i = 0; i != NumParams; ++i) {
4119 if (i != 0) typeNames += ", ";
4120 typeNames += Args[i+1]->getType().getAsString();
4121 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004122
Chris Lattner77d52da2008-11-20 06:06:08 +00004123 return Diag(BuiltinLoc, diag::err_overload_no_match)
4124 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004125}
4126
Anders Carlsson36760332007-10-15 20:28:48 +00004127Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4128 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004129 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004130 Expr *E = static_cast<Expr*>(expr);
4131 QualType T = QualType::getFromOpaquePtr(type);
4132
4133 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004134
4135 // Get the va_list type
4136 QualType VaListType = Context.getBuiltinVaListType();
4137 // Deal with implicit array decay; for example, on x86-64,
4138 // va_list is an array, but it's supposed to decay to
4139 // a pointer for va_arg.
4140 if (VaListType->isArrayType())
4141 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004142 // Make sure the input expression also decays appropriately.
4143 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004144
4145 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004146 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004147 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004148 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004149
4150 // FIXME: Warn if a non-POD type is passed in.
4151
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004152 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004153}
4154
Douglas Gregorad4b3792008-11-29 04:51:27 +00004155Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4156 // The type of __null will be int or long, depending on the size of
4157 // pointers on the target.
4158 QualType Ty;
4159 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4160 Ty = Context.IntTy;
4161 else
4162 Ty = Context.LongTy;
4163
4164 return new GNUNullExpr(Ty, TokenLoc);
4165}
4166
Chris Lattner005ed752008-01-04 18:04:52 +00004167bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4168 SourceLocation Loc,
4169 QualType DstType, QualType SrcType,
4170 Expr *SrcExpr, const char *Flavor) {
4171 // Decode the result (notice that AST's are still created for extensions).
4172 bool isInvalid = false;
4173 unsigned DiagKind;
4174 switch (ConvTy) {
4175 default: assert(0 && "Unknown conversion type");
4176 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004177 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004178 DiagKind = diag::ext_typecheck_convert_pointer_int;
4179 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004180 case IntToPointer:
4181 DiagKind = diag::ext_typecheck_convert_int_pointer;
4182 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004183 case IncompatiblePointer:
4184 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4185 break;
4186 case FunctionVoidPointer:
4187 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4188 break;
4189 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004190 // If the qualifiers lost were because we were applying the
4191 // (deprecated) C++ conversion from a string literal to a char*
4192 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4193 // Ideally, this check would be performed in
4194 // CheckPointerTypesForAssignment. However, that would require a
4195 // bit of refactoring (so that the second argument is an
4196 // expression, rather than a type), which should be done as part
4197 // of a larger effort to fix CheckPointerTypesForAssignment for
4198 // C++ semantics.
4199 if (getLangOptions().CPlusPlus &&
4200 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4201 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004202 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4203 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004204 case IntToBlockPointer:
4205 DiagKind = diag::err_int_to_block_pointer;
4206 break;
4207 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004208 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004209 break;
Steve Naroff19608432008-10-14 22:18:38 +00004210 case IncompatibleObjCQualifiedId:
4211 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4212 // it can give a more specific diagnostic.
4213 DiagKind = diag::warn_incompatible_qualified_id;
4214 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004215 case Incompatible:
4216 DiagKind = diag::err_typecheck_convert_incompatible;
4217 isInvalid = true;
4218 break;
4219 }
4220
Chris Lattner271d4c22008-11-24 05:29:24 +00004221 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4222 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004223 return isInvalid;
4224}
Anders Carlssond5201b92008-11-30 19:50:32 +00004225
4226bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4227{
4228 Expr::EvalResult EvalResult;
4229
4230 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4231 EvalResult.HasSideEffects) {
4232 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4233
4234 if (EvalResult.Diag) {
4235 // We only show the note if it's not the usual "invalid subexpression"
4236 // or if it's actually in a subexpression.
4237 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4238 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4239 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4240 }
4241
4242 return true;
4243 }
4244
4245 if (EvalResult.Diag) {
4246 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4247 E->getSourceRange();
4248
4249 // Print the reason it's not a constant.
4250 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4251 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4252 }
4253
4254 if (Result)
4255 *Result = EvalResult.Val.getInt();
4256 return false;
4257}